Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running coverage inside virtualenv

I recently stumbled upon some issue with running coverage measurements within virtual environment. I do not remember similar issues in the past, nor I was able to find solution on the web.

Basically, when I am trying to run test suite in virtualenv, it works fine. But as soon, as I try to do it using coverage, it fails because of lack of modules it requires. Based on some answer on StackOverflow I checked my script and found out that coverage uses different interpreter, even if running from inside the same virtualenv.

Here is how to reproduce it:

$ virtualenv --no-site-packages venv
New python executable in venv/bin/python
Installing Setuptools................................................done.
Installing Pip.......................................................done.
$ source venv/bin/activate
(venv)$ echo 'import sys; print(sys.executable)' > test.py
(venv)$ python test.py
/home/tadeck/testground/venv/bin/python
(venv)$ coverage run test.py 
/usr/bin/python

The question is: how to make coverage work with virtual environment seamlessly? I could alter sys.path or install required modules system-wide, but there has to be a cleaner way.

like image 273
Tadeck Avatar asked Sep 23 '13 12:09

Tadeck


People also ask

How do I run a script in virtualenv?

To use the virtual environment you created to run Python scripts, simply invoke Python from the command line in the context where you activated it. For instance, to run a script, just run python myscript.py .

What is pip in virtualenv?

pip is a tool for installing packages from the Python Package Index. virtualenv is a tool for creating isolated Python environments containing their own copy of python , pip , and their own place to keep libraries installed from PyPI.

Is virtualenv better than VENV?

These are almost completely interchangeable, the difference being that virtualenv supports older python versions and has a few more minor unique features, while venv is in the standard library.


2 Answers

I had to leave my virtualenv after installing coverage and reactivate it to get coverage to work.

[alex@gesa ~]$ virtualenv --no-site-packages venv
[alex@gesa ~]$ source venv/bin/activate
(venv)[alex@gesa ~]$ pip install coverage
(venv)[alex@gesa ~]$ deactivate
[alex@gesa ~]$ source venv/bin/activate
like image 119
Dan Hooper Avatar answered Sep 28 '22 19:09

Dan Hooper


pip install coverage in your new venv

[alex@gesa ~]$ virtualenv venv
[alex@gesa ~]$ source venv/bin/activate
(venv)[alex@gesa ~]$ pip install coverage
(venv)[alex@gesa ~]$ echo 'import sys; print(sys.executable)' > test.py
(venv)[alex@gesa ~]$ python test.py
/home/alex/venv/bin/python
(venv)[alex@gesa ~]$ coverage run test.py
/home/alex/venv/bin/python
(venv)[alex@gesa ~]$
like image 39
Tritium21 Avatar answered Sep 28 '22 20:09

Tritium21