pytest支持两种常见的测试布局:

一、外部测试代码¶

如果有许多功能测试或出于其他原因希望将测试与实际应用程序代码分开(通常是一个好主意),那么将测试放入实际应用程序代码之外的额外目录可能会更好一些:

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用法之目录布局

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.

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.

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用法之目录布局

这种布局避免了许多常见的陷阱,并有许多好处.

二、作为应用程序代码一部分的测试

如果测试和应用程序模块之间有直接关系,并希望将它们与应用程序一起分发,则将测试目录内联到应用程序包中更好:
Pytest用法之目录布局

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.