I have a test file tests.py
. Currently, to help isolate the problem, the file contains only the following line:
from mock import Mock
When I try to run this file with pytest
:
$ py.test tests.py
I get the following error output:
tests.py:1: in <module>
from mock import Mock
E ImportError: No module named mock
=========================== 1 error in 0.00 seconds ============================
If I run the file with python
:
$ python tests.py
I do not get this error. Similarly, if I open an interactive interpreter, I am able to import mock
without issue. Why am I not able to access mock
in this context?
Turns out the version of Pytest that I was using was installed through apt
, while my version of mock
was installed through pip
in a virtual environment. On the suggestion of @MichaelKarotsieris, I checked the contents of sys.path
after running my tests with Pytest (I used the --pdb
option to pop into the pdb
debugger after the error was raised):
$ py.test tests.py --pdb
...
(Pdb) import sys
(Pdb) sys.path
From this I found that although my virtual environment was active, that environment was not in sys.path
.
Next, I tried installing pytest in my virtual environment through pip:
(my_env) $ pip install pytest
However, with this step alone the version of Pytest installed through apt
was still being used, so I decided to just remove it:
(my_env) $ sudo apt remove --purge python-pytest
After this, running the py.test
command worked as expected.
In hindsight, I suppose I could have kept the version of Pytest installed through apt
, and just ran the executable from the virtualenv directly:
(my_env) $ /path/to/my_env/bin/py.test tests.py