Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 886
Henry Grantham Avatar asked Jan 27 '16 18:01

Henry Grantham


People also ask

Which Python does pytest use?

Prerequisites. This tutorial uses Python 3, and we will be working inside a virtualenv . This creates a virtual environment called pytest-env in our working directory. As long as the virtualenv is active, any packages we install will be installed in our virtual environment, rather than in the global Python installation ...

Where do I put the pytest test?

While the pytest discovery mechanism can find tests anywhere, pytests must be placed into separate directories from the product code packages. These directories may either be under the project root or under the Python package.


2 Answers

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.

like image 105
7yl4r Avatar answered Sep 21 '22 08:09

7yl4r


Inside your environment, you may try

python -m pytest 
like image 31
Icarus Avatar answered Sep 21 '22 08:09

Icarus