Python Forum

Full Version: script with imports works but pytest gives "ModuleNotFoundError"?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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 pytest
Creating the following structure:

my_test
|- venv
|- src
| |- a
| | |- __init__.py
| | |- a.py
| | |- b.py
|- tests
| |- testing_a
| | |- test_a.py
Where 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
B
But 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 :/