Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

conftest.py ImportError: No module named Foo

Tags:

python

pytest

I have the following directory structure

/home/ubuntu/test/
 - Foo/
   - Foo.py
   - __init__.py
 - Test/
   - conftest.py
   - __init__.py
   - Foo/
     - test_Foo.py
     - __init__.py

Foo.py contains

class Foo(object):
  def __init__(self):
    pass

conftest.py contains:

import pytest

import sys
print sys.path

from Foo.Foo import Foo

@pytest.fixture(scope="session")
def foo():
  return Foo()

test_Foo.py contains:

class TestFoo():
  def test___init__(self,foo):
    assert True

If I run pytest . in the Test folder then I get an error that it can not find the module Foo:

Traceback (most recent call last):
  File "/home/ubuntu/pythonVirtualEnv/local/lib/python2.7/site-packages/_pytest/config.py", line 379, in _importconftest
    mod = conftestpath.pyimport()
  File "/home/ubuntu/pythonVirtualEnv/local/lib/python2.7/site-packages/py/_path/local.py", line 662, in pyimport
    __import__(modname)
  File "/home/ubuntu/pythonVirtualEnv/local/lib/python2.7/site-packages/_pytest/assertion/rewrite.py", line 212, in load_module
    py.builtin.exec_(co, mod.__dict__)
  File "/home/ubuntu/pythonVirtualEnv/local/lib/python2.7/site-packages/py/_builtin.py", line 221, in exec_
    exec2(obj, globals, locals)
  File "<string>", line 7, in exec2
  File "/home/ubuntu/test/Test/conftest.py", line 6, in <module>
    from Foo.Foo import Foo
ImportError: No module named Foo
ERROR: could not load /home/ubuntu/test/Test/conftest.py

The sys.path that is printed out in conftest.py seems to include the /home/ubuntu/test path so it should be able to find Foo.py, right?

The thing is that it only works when I move conftest.py to the folder below.

I run pytest 3.2.2

like image 385
ddvlamin Avatar asked Sep 13 '17 16:09

ddvlamin


People also ask

What is Conftest PY in pytest?

conftest.py is where you setup test configurations and store the testcases that are used by test functions. The configurations and the testcases are called fixture in pytest.

What is a Conftest?

Conftest is a utility to help you write tests against structured configuration data. For instance, you could write tests for your Kubernetes configurations, Tekton pipeline definitions, Terraform code, Serverless configs or any other structured data.

Where do I put pytest files?

While the pytest discovery mechanism can find tests anywhere, pytests must be placed into separate directories from the product code packages. These directories may either be under the project root or under the Python package.


1 Answers

The error says the conftest.py can not be loaded because of an ImportError. Try moving your import inside the foo fixture like this:

import pytest
import sys
print sys.path


@pytest.fixture(scope="session")
def foo():
    from Foo.Foo import Foo
    return Foo()
like image 185
ldiary Avatar answered Sep 24 '22 02:09

ldiary