Usual pytest workflow - can't run tests in a file

依然范特西╮ 提交于 2019-11-29 16:04:18

Pytest will add the current directory to sys.path, but that doesn't necessarily mean that it makes your package importable from the source tree. In fact, the entire point of using a src and test layout is to prevent pytest from testing against the source tree.

You can check this yourself by running a python interpreter from the top-level directory of your project and attempting to import the package. It won't work, unless it has already been installed in your working environment.

By using the src and test layout, pytest is forced to test against an installed version of your package. See this great blog post with motivation for structuring your project this way. Here's the key paragraph:

You will be forced to test the installed code (e.g.: by installing in a virtualenv). This will ensure that the deployed code works (it's packaged correctly) - otherwise your tests will fail. Early. Before you can publish a broken distribution.

So if you want to use this kind of layout for your project, you need to install your package before testing. There are advantages and disadvantages to either approach, but pytest recommends it and I'm inclined to agree.

[update]

As a workaround for convenient local testing, you can install your package in development mode using either setup.py develop or pip install -e .. This makes your package appear to be installed in your environment, but any updates in your source tree will be immediately reflected in the "installed" version.1

If you choose to follow this approach, you should make sure that you are using a sandboxed development environment (e.g. virtualenv or conda) so that you don't pollute your system environment.


1 You should be aware that if your package provides and C/C++ or Cython extensions, they will need to be rebuilt manually.
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!