I have a test that passes with pytest. I also have an adjacent source that's a console app (not pytest) that exercises the same function that barfs with ModuleNotFoundError for the same function call.
mylib/mylib.py:
def adder(num1, num2): return num1 + num2 test/my_test.py:
from mylib.mylib import adder def test_adder(): assert adder(2, 2) == 4 test/mytest_outside_pytest.py:
from mylib.mylib import adder print(str(adder(2, 2))) As I suggest pytest completes and indicates the test passed, but the following does not:
$ python3 test/mytest_outside_pytest.py Traceback (most recent call last): File "test/mytest_outside_pytest.py", line 1, in <module> from mylib.mylib import adder ModuleNotFoundError: No module named 'mylib' Nor does:
$ cd test/ $ python3 mytest_outside_pytest.py Traceback (most recent call last): File "mytest_outside_pytest.py", line 1, in <module> from mylib.mylib import adder ModuleNotFoundError: No module named 'mylib' I have empty __init__.py in both folders. I don't know what pytest does to path loading that I can't replicate in my "main" console app. Of course I don't really care about an adder lib, I'm just aiming at the smallest reproducible problem.
python3 -m pytest ..., it adds the current path to the Python path, so the modules will be found. Just callingpython3 test/mytest.pydoes not do this. As the import is relative to that root dir, the root dir must be in the Python path for the import to work.python3 -m pytest test/mytest_outside_pytest.pyand it says "collected 0 items" so not quite the outcome I was looking for .. "4" in stdout.