简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM