pytest支持两种常见的测试布局:app
若是有许多功能测试或出于其余缘由但愿将测试与实际应用程序代码分开(一般是一个好主意),那么将测试放入实际应用程序代码以外的额外目录可能会更好一些:ide
这种方案的优势:布局
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文件夹和子文件夹中,并将它们更改成包: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:code
这种布局避免了许多常见的陷阱,并有许多好处.orm
若是测试和应用程序模块之间有直接关系,并但愿将它们与应用程序一块儿分发,则将测试目录内联到应用程序包中更好: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.
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.