How to import packages with py.test correctly?

I have the following layout:

/spamalot /spam __init__.py spam.py /spam_on_eggs __init__.py spam_on_eggs.py /tests test_spam.py 

Spam just happens to be a flask app.

Inside spam.py I have

 import spam_on_eggs.spam_on_eggs as eggs # Other Flask setup & application code here. 

And it works great - from the spamalot directory spamalot I can run python spam/spam.py

However, when I start throwing tests into the mix, it’s not so scary.

In my test_spam.py file, I have:

 import spam.spam test_client = spam.spam.app.test_client() def test_it_fails(): assert False 

However, instead of failing where I expect it does not work on the import line:

 /spamalot/ $ py.test # some output E ImportError 

I can fix this by placing __init__.py in my /tests folder, but then I get another ImportError:

 spam/spam.py:1: in <module> > import spam_on_eggs.spam_on_eggs as eggs E ImportError: No module named 'spam_on_eggs' 

I can solve this by changing the line to:

 from spam.spam_on_eggs import spam_on_eggs 

Which allows me to test , but then I violate my ability to run $ python spam/spam.py - because I get

 ImportError: no module named 'spam' 

Obviously, I have a gap in my understanding of how module import works and how py.test works with this system.

What am I missing?

Is it possible to have the layout described above and be able to run both py.test and my server from the spamalot directory?

+6
source share
1 answer

py.test will always use the shortest path to the directory with __init__.py in it.

Put a __init__.py in spamalot and you can import spamalot.spam.spam .

Link: test layout selection

-1
source

All Articles