How do I use pytest with virtualenv?
PythonVirtualenvPytestPython Problem Overview
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?
Python Solutions
Solution 1 - Python
There is a bit of a dance to get this to work:
- activate your venv :
source venv/bin/activate
- install pytest :
pip install pytest
- re-activate your venv:
deactivate && source venv/bin/activate
The reason is that the path to pytest
is set by the source
ing 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-activate
ing is required for any console entry points installed within your virtual environment.
Solution 2 - Python
Inside your environment, you may try
python -m pytest
Solution 3 - Python
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
Solution 4 - Python
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