I've tried other solutions with no luck (pytest.ini
, __init__.py
inside test\
, conftest.py
...)
I have the following project structure:
.
├── module
│ ├── bar.py
│ ├── foo.py
│ ├── __init__.py
│ └── __main__.py
└── tests
├── __init__.py
└── test_module.py
Module works, test fails
and the files are:
module/bar.py
:
def bar():
return "bar"
module/foo.py
: I suspect this import should be done in other way... * more on this later
from bar import bar
def foo():
value = bar()
print(value)
return value
module/__init__.py
:
empty
module/__main__.py
:
from foo import foo
foo()
And my module works, so if I call it:
python module
I get bar
so far so good.
Now the test, tests/test_module.py
:
from module import foo
def test_foo():
assert foo.bar() == "bar"
tests/__init__.py
:
empty
If I try to execute the tests, either with pytest .
or python -m pytest
I get
_________________________________________________________________________________________________________________________________ ERROR collecting tests/test_module.py __________________________________________________________________________________________________________________________________
ImportError while importing test module '/home/susensio/Projects/sandbox/pytest/tests/test_module.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
/usr/lib/python3.11/importlib/__init__.py:126: in import_module
return _bootstrap._gcd_import(name[level:], package, level)
tests/test_module.py:1: in <module>
from module import foo
E ModuleNotFoundError: No module named 'module'
So, at this point module works, test does not
Module fails, test works
I've tried several things, the only one that changes something is the following:
changing foo.py
to (note the relative import):
from .bar import bar
def foo():
value = bar()
print(value)
return value
causes the tests to work, but I cannot call the module with python module
, it throws an error:
Traceback (most recent call last):
File "<frozen runpy>", line 198, in _run_module_as_main
File "<frozen runpy>", line 88, in _run_code
File "/home/susensio/Projects/sandbox/pytest/module/__main__.py", line 1, in <module>
from foo import foo
File "/home/susensio/Projects/sandbox/pytest/module/foo.py", line 1, in <module>
from .bar import bar
ImportError: attempted relative import with no known parent package
As I've said, other questions didn't help to solve this issue.