Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run tests without installing package?

Tags:

python

pytest

I have some Python package and some tests. The files are layed out following http://pytest.org/latest/goodpractices.html#choosing-a-test-layout-import-rules

Putting tests into an extra directory outside your actual application code, useful if you have many functional tests or for other reasons want to keep tests separate from actual application code (often a good idea):

setup.py   # your distutils/setuptools Python package metadata mypkg/     __init__.py     appmodule.py tests/         test_app.py 

My problem is, when I run the tests py.test, I get an error

ImportError: No module named 'mypkg'

I can solve this by installing the package python setup.py install but this means the tests run against the installed package, not the local one, which makes development very tedious. Whenever I make a change and want to run the tests, I need to reinstall, else I am testing the old code.

What can I do?

like image 678
Colonel Panic Avatar asked Jun 01 '14 22:06

Colonel Panic


2 Answers

I know this question has been already closed, but a simple way I often use is to call pytest via python -m, from the root (the parent of the package).

$ python -m pytest tests 

This works because -m option adds the current directory to the python path, and hence mypkg is detected as a local package (not as the installed).

See: https://docs.pytest.org/en/latest/usage.html#calling-pytest-through-python-m-pytest

like image 185
Kota Mori Avatar answered Sep 21 '22 23:09

Kota Mori


The normal approach for development is to use a virtualenv and use pip install -e . in the virtualenv (this is almost equivalent to python setup.py develop). Now your source directory is used as installed package on sys.path.

There are of course a bunch of other ways to get your package on sys.path for testing, see Ensuring py.test includes the application directory in sys.path for a question with a more complete answer for this exact same problem.

like image 28
flub Avatar answered Sep 22 '22 23:09

flub