Pytest用法之目錄佈局

pytest支持兩種常見的測試佈局:app

1、外部測試代碼¶

若是有許多功能測試或出於其餘緣由但願將測試與實際應用程序代碼分開(一般是一個好主意),那麼將測試放入實際應用程序代碼以外的額外目錄可能會更好一些:ide

Pytest用法之目錄佈局

這種方案的優勢:
Pytest用法之目錄佈局佈局

Note that this scheme has a drawback if you are using prepend import mode (which is the default): your test files must have unique names, because pytest will import them as top-level modules since there are no packages to derive a full package name from. In other words, the test files in the example above will be imported as test_app and test_view top-level modules by adding tests/ to sys.path.測試

若是您須要具備相同名稱的測試模塊,您能夠將__init___.py文件添加到您的tests文件夾和子文件夾中,並將它們更改成包:
Pytest用法之目錄佈局this

Now pytest will load the modules as tests.foo.test_view and tests.bar.test_view, allowing you to have modules with the same name. But now this introduces a subtle problem: in order to load the test modules from the tests directory, pytest prepends the root of the repository to sys.path, which adds the side-effect that now mypkg is also importable.spa

This is problematic if you are using a tool like tox to test your package in a virtual environment, because you want to test the installed version of your package, not the local code from the repository.3d

In this situation, it is strongly suggested to use a src layout where application root package resides in a sub-directory of your root:
Pytest用法之目錄佈局code

這種佈局避免了許多常見的陷阱,並有許多好處.orm

2、做爲應用程序代碼一部分的測試

若是測試和應用程序模塊之間有直接關係,並但願將它們與應用程序一塊兒分發,則將測試目錄內聯到應用程序包中更好:
Pytest用法之目錄佈局blog

In this scheme, it is easy to run your tests using the --pyargs option:

pytest --pyargs mypkg
pytest will discover where mypkg is installed and collect tests from there.

Note that this layout also works in conjunction with the src layout mentioned in the previous section.

Note
You can use Python3 namespace packages (PEP420) for your application but pytest will still perform test package name discovery based on the presence of init.py files. If you use one of the two recommended file system layouts above but leave away the init.py files from your directories it should just work on Python3.3 and above. From 「inlined tests」, however, you will need to use absolute imports for getting at your application code.

tox¶

Once you are done with your work and want to make sure that your actual package passes all tests you may want to look into tox, the virtualenv test automation tool and its pytest support. tox helps you to setup virtualenv environments with pre-defined dependencies and then executing a pre-configured test command with options. It will run tests against the installed package and not against your source code checkout, helping to detect packaging glitches.

相關文章
相關標籤/搜索