Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Py.test No module named *

Tags:

python

pytest

I have a folder structure like this

App
--App
  --app.py       
--Docs
--Tests
  --test_app.py

In my test_app.py file, I have a line to import my app module. When I run py.test on the root folder, I get this error about no module named app. How should I configure this?

like image 301
zsljulius Avatar asked Jan 08 '14 01:01

zsljulius


People also ask

Does pytest use Pythonpath?

Recently, pytest has added a new core plugin that supports sys. path modifications via the pythonpath configuration value.

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. The test_*. py files are where the actual test functions reside.


3 Answers

Working with Python 3 and getting the same error on a similar project layout, I solved it by adding an __init__ file to my tests module.

$ touch tests/__init__.py

I'm not great at packaging and importing, but I think that this helps pytest work out where the target App module is located.

like image 150
jamesc Avatar answered Oct 23 '22 14:10

jamesc


I already had an __init__.py file in the /App/App directory and wanted to run tests from the project root without any path-mangling magic:

 python -m pytest tests

The output immediately looks like this:

➟  python -m pytest tests
====================================== test session starts ======================================
platform linux -- Python 3.5.1, pytest-2.9.0, py-1.4.31, pluggy-0.3.1
rootdir: /home/andrew/code/app, inifile: 
plugins: teamcity-messages-1.17
collected 46 items 

... lines omitted ...

============================= 44 passed, 2 skipped in 1.61 seconds ==============================
like image 39
berezovskyi Avatar answered Oct 23 '22 15:10

berezovskyi


So you are running py.test from /App. Are you sure /App/App is in your $PYTHONPATH?

If it's not, code that tries to import app will fail with such a message.

EDIT0: including the info from my comment below, for completeness.

An attempt to import app will only succeed if it was executed inside /App/App, which is not the case here. You probably want to make /App/App a package by putting __init__.py inside it, and change your import to qualify app as from App import app.

EDIT1: by request, adding further explanation from my second comment below.

By putting __init__.py inside /App/App, that directory becomes a package. Which means you can import from it, as long as it - the directory - is visible in the $PYTHONPATH. I.e. you can do from App import app if /App is in the $PYTHONPATH. Your current working directory gets automatically added to $PYTHONPATH, so when you run a script from /App, the import will work.

like image 29
Dun Peal Avatar answered Oct 23 '22 13:10

Dun Peal