How do I use pytest with virtualenv?

I installed pytest into a virtual environment (using virtualenv) and am running it from that virtual environment, but it is not using the packages that I installed in that virtual environment. Instead, it is using the main system packages. (Using python -m unittest discover, I can actually run my tests with the right python and packages, but I want to use the py.test framework.)

Is it possible that py.test is actually not running the pytest inside the virtual environment and I have to specify which pytest to run?

How to I get py.test to use only the python and packages that are in my virtualenv?

Also, since I have several version of Python on my system, how do I tell which Python that Pytest is using? Will it automatically use the Python within my virtual environment, or do I have to specify somehow?

37023 次浏览

you have to activate your python env every time you want to run your python script, you have several ways to activate it, we assume that your virtualenv is installed under /home/venv :

1- the based one is to run the python with one command line >>> /home/venv/bin/python <your python file.py>

2- add this line on the top of python script file #! /home/venv/bin/python and then run python <you python file.py>

3- activate your python env source /home/venv/bin/activate and then run you script like python <you python file.py>

4- use virtualenvwrapper to manager and activate your python environments

In my case I was obliged to leave the venv (deactivate), remove pytest (pip uninstall pytest), enter the venv (source /my/path/to/venv), and then reinstall pytest (pip install pytest). I don't known exacttly why pip refuse to install pytest in venv (it says it already present).

I hope this helps

Inside your environment, you may try

python -m pytest

There is a bit of a dance to get this to work:

  1. activate your venv : source venv/bin/activate
  2. install pytest : pip install pytest
  3. re-activate your venv: deactivate && source venv/bin/activate

The reason is that the path to pytest is set by the sourceing the activate file only after pytest is actually installed in the venv. You can't set the path to something before it is installed.

Re-activateing is required for any console entry points installed within your virtual environment.