thyago stall
thyago stall

Reputation: 1704

Unit tests in Python with pytest

Currently my project's directory is organized as the following structure:

.
+-- module1
+-- module2
...
+-- moduleN
+-- test
    +-- test_module1_item1.py
    ...
    +-- test_moduleN_itemM.py

But when I execute py.test in my upper level directory, it throws an error like:

ImportError: No module named 'module1'

How the imports in the test files should be declared? Or how my project structure should be defined in order to the tests be separated from the rest of the code?

Upvotes: 1

Views: 956

Answers (1)

munk
munk

Reputation: 13023

I suspect __init__.py is missing from ./test

» ls *
module1:
__init__.py

test:
test_module1_item1.py

Let's try testing

» py.test
... 
ERROR collecting test/test_module1_item1.py     
test/test_module1_item1.py:8: in <module>
    import module1
E   ImportError: No module named module1

This looks like your error.

» touch test/__init__.py
» py.test

test/test_module1_item1.py:10: in <module>
    assert 1 == 2
E   assert 1 == 2

This looks like your solution. I suspect py.test is doing something with the $pythonpath based on whether ./test is a module or not.

Upvotes: 1

Related Questions