1

So I have a class Foo in src/foo.py. I also have a pytest test in test/test_foo.py. When I run pytest in the root folder it does not recognize src/ as the place I've gathered all my prod source code. It spits out a error like so:

$ pytest 
=== test session starts ===
platform darwin -- Python 3.7.5, pytest-5.2.1, py-1.8.0, pluggy-0.13.0
rootdir: /path/to/minimal_pytest_example
collected 0 items / 1 errors                                                                                                                                                   

=== ERRORS ===
___ ERROR collecting test/test_foo.py ___
ImportError while importing test module '/path/to/minimal_pytest_example/test/test_foo.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
test/test_foo.py:3: in <module>
    from foo import Foo
E   ModuleNotFoundError: No module named 'foo'
!!! Interrupted: 1 errors during collection !!!
=== 1 error in 0.10s ===

Note - foo/Foo.say_hello() is simple - just does a print of "hello", and that's all that is exercised in the test.

Cloneable repo here - https://github.com/wene-gilder/minimal_pytest_example <-- my attempt to make a minimal reproducible representation of the problem I'm trying to solve, and if you clone this, the error represents as copy/pasted above.

[EDIT] This is the commit that fixed it: https://github.com/wene-gilder/minimal_pytest_example/commit/c6a30c84f4026a6ea0a21285b865620089e84a15

  • Because in the project root dir, there‘s no module `foo`, and the problem isn't related to `pytest`. Running `python -c "from foo import Foo"` from the project root will fail, while `python -c "from src.foo import Foo"` will succeed. Reorganize your module layout, or set the variable `PYTHONPATH=src` for imports to resolve. – hoefling Dec 21 '19 at 14:07
  • import sys, os \n myPath = os.path.dirname(os.path.abspath(__file__)) \n sys.path.insert(0, myPath + '/../src/') \n .... in `test/__init__.py` solves in – wene-gilder Dec 21 '19 at 14:57

0 Answers0