Ensuring py.test includes the application directory in sys.path

你离开我真会死。 提交于 2019-11-28 16:50:18
flub

As you say yourself py.test basically assumes you have the PYTHONPATH setup up correctly. There are several ways of achieving this:

  • Give your project a setup.py and use pip install -e . in a virtualenv for this project. This is probably the standard method.

  • As a variation on this if you have a virtualenv but no setup.py use your venv's facility to add the projects directory on sys.path, e.g. pew add . if you use pew, or add2virtualenv . if you use virtualenv and the extensions of virtualenvwrapper.

  • If you always like the current working directory on sys.path you can simply always export PYTHONPATH='' in your shell. That is ensure the empty string on on sys.path which python will interpret as the current working direcotry. This is potentially a security hazard though.

  • My own favourite hack, abuse how py.test loads conftest files: put an empty conftest.py in the project's top-level directory.

The reason for py.test to behave this way is to make it easy to run the tests in a tests/ directory of a checkout against an installed package. If it would unconditionally add the project directory to the PYTHONPATH then this would not be possible anymore.

sleepycal

The answer is actually much easier, as seen here.

All you need to do is add an __init__.py to your test directory and each of its sub directories, like so;

tests/__init__.py
tests/functional/__init__.py
tests/unit/__init__.py
A H

The easy way of doing it is, in terminal/cmd change directory to where the parent directory is, (e.g. in this case cd C:/.../my_project).

Then run: python -m pytest --cov=mypkg tests

No need to mess with the PYTHONPATH environment variable. By running with python -m pytest, it automatically adds the current directory to sys.path.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!