Skip to content Skip to sidebar Skip to footer

Importerror Shows Up With Py.test, But Not When Running The App

Unlike in this question: Importing modules from a sibling directory for use with py.test I can import something from my app, but there's an import error (looking like a circular de

Solution 1:

Setting the PYTHONPATH should do the trick.

$ export PYTHONPATH=<ABSOLUTE PATH TO TOPMOST myapp dir>

(in this example, it is the path to myapp/myapp; and ensure you've exportedPYTHONPATH, not only set it).

and from myapp run either

$ py.test

or

$ python3 -m pytest

Solution 2:

Another way of doing this is to put a conftest.py file into the top level of myapp, or in myapp/tests. Like this:

$ pwd
/home/nico/temp/projects_structures/test04/myapp/tests
$ touch conftest.py
$ cd ..
$ py.test
================================================================= test session starts =================================================================
platform linux2 -- Python 2.7.6, pytest-2.9.1, py-1.4.31, pluggy-0.3.1
rootdir: /home/nico/temp/projects_structures/test04/myapp, inifile: 
collected 1 items 

tests/test_things.py .

============================================================== 1 passed in 0.05 seconds ===============================================================
$

(and PYTHONPATH is empty:

$ echo$PYTHONPATH
$

)

This way, py.test automatically adds myapp to PYTHONPATH. This avoids to forget exporting PYTHONPATH and will make the tests of myapp easier for other devs (who neither will need to solve this problem).

Post a Comment for "Importerror Shows Up With Py.test, But Not When Running The App"