script with imports works but pytest gives "ModuleNotFoundError"? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: script with imports works but pytest gives "ModuleNotFoundError"? (/thread-34113.html) |
script with imports works but pytest gives "ModuleNotFoundError"? - Hpao - Jun-27-2021 I'm trying to setup my first python project with pytest but I'm having trouble executing my tests. The module itself seems to be working as intended and I can't figure it out. I've created a minimal example as follows (using python 3.9):mkdir /tmp/my_test cd /tmp/my_test python -m venv venv . venv/bin/activate pip install pytestCreating the following structure: my_test |- venv |- src | |- a | | |- __init__.py | | |- a.py | | |- b.py |- tests | |- testing_a | | |- test_a.pyWhere src/a/a.py is executable and contains:#!/usr/bin/env python3 import b def foo(): print("A") b.bar() if __name__ == "__main__": foo()And src/a/b.py is a simple module containing:def bar(): print("B")And finally tests/testing_a/test_a.py contains:from a import a, b def test_a(): a.foo() def test_b(): b.bar()Running src/a/a.py produces the expected output:A BBut running pytest -v throws ModuleNotFoundError: No module named 'a' . Same if I try to run as python -m pytest -v .Why is this? How come the imports doesn't work the same way when running the script directly compared to running pytest ?I'm sure I'm missing something about how python imports work and I'm sure it would be obvious with a nudge in the right direction :/ |