[pytest-dev] syntax for importing modules in Pytest tests

dpb dpb dpb.mediamath at gmail.com
Fri Jul 24 19:16:02 CEST 2015


I'm converting some tests written earlier for Unittest and am having
trouble with import statements when running them with Pytest.

As an example, in the older code the module create.py in directory lib
might be imported as

import lib.create
>

but this syntax usually raises errors when I run the code with Pytest.

I'd appreciate any advice. Details and minimal examples below.

1. I am in the directory temp:

temp/
    lib/
        __init__.py
        create.py
    tests/
        test_caller.py



2. File __init__.py is empty. The other two files are as follows:

# test_caller.py
>
> import lib.create
>
> def test_show():
>     assert True
>

and

# create.py
>
> def create():
>     pass
>



3. Running Pytest from within temp typically generates an ImportError:

$ py.test tests
> ============================= test session starts
> ==============================
> platform darwin -- Python 2.7.6 -- py-1.4.26 -- pytest-2.7.0
> rootdir: .../temp/tests, inifile:
> collected 0 items / 1 errors
>
> ==================================== ERRORS
> ====================================
> _______________________ ERROR collecting test_caller.py
> ________________________
> tests/test_caller.py:3: in <module>
>     import lib.create
> E   ImportError: No module named lib.create
> =========================== 1 error in 0.01 seconds
> ============================
>



4. I have tried updating the sys.path list in test_caller.py:

import sys
> sys.path.append('lib')
>

or

sys.path.extend(['..', 'lib'])
>

but the result is the same.

Thanks for any suggestions as to how to deal with this.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/pytest-dev/attachments/20150724/dcd34cbf/attachment.html>


More information about the pytest-dev mailing list