How do you get pytest to understand python modules like python does?

I've been changing directory structure around and adding random init.py and things all over the place for like two hours now and I can't figure out how to get pytest to run a test that imports a file from one directory level up.

Right now, my directory structure is:

├── conftest.py
├── junk
│   ├── __init__.py
│   └── ook.py
└── tests
    ├── test_ook.py

and the contents of ook.py are:

def ook():
    pass

and the contents of test_ook.py are:

from ook import ook


def test_horse():
    pass

The output of running both pytest and python -m pytest is:

ImportError while importing test module '/home/z9/repos/test/tests/test_ook.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
tests/test_ook.py:1: in <module>
    from ook import ook
E   ModuleNotFoundError: No module named 'ook'

This code is copied from this post: Ensuring py.test includes the application directory in sys.path

Other people say it works for them - it works for me in python, like when I write a script to from ook import ook that works fine, but in pytest it just can't figure it out.

Python 3.7, pytest 5.2.2

Ok so to update, the real problem is if ook.py needs to import something. It only works with absolute imports -> the behavior is different when you run "python -m pytest" than "python"

Upvotes: 0

Views: 360

Answers (2)

nikhilesh_koshti
nikhilesh_koshti

Reputation: 403

For importing python modules from other directory path in the pytest execution, you have to modify the ini file of pytest (pytest.ini).

Add a file pytest.ini in the location next to conftest.py with the following format:-

[pytest]
python_paths = . junk/

After that, you could import it from all the location

Please refer:- pytest run tests inside a class with a constructor

Upvotes: 0

tmt
tmt

Reputation: 8604

Your code is in junk/ook.py so the import in tests/test_ook.py should read:

from junk.ook import ook

There really isn't anything special going when pytest is run regarding imports and how Python works. To use a relative import, ook and tests would need to belong to the same package. If you moved tests/ directory to junk/ where ook.py is, then in junk/tests/test_ook.py you could use:

from ..ook import ook

Upvotes: 1

Related Questions