cropyeee
cropyeee

Reputation: 43

Pytest: ModuleNotFoundError: No module named 'src'

I'm starting to learn pytest and I want to integrate it with Travis later on. I've created my first tests and I can run them from PyCharm without any problem. But when I try to run pytest from Linux's terminal I get the following error:

Hint: make sure your test modules/packages have valid Python names.
Traceback:
/usr/lib/python3.6/importlib/__init__.py:126: in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
test_prob.py:1: in <module>
    from src.agents import prob
E   ModuleNotFoundError: No module named 'src'

I've found some similar problems and solutions for them but none of them have worked for me. My project structure looks as follow

Upvotes: 4

Views: 11566

Answers (3)

Sardor Abdirayimov
Sardor Abdirayimov

Reputation: 109

I had the same error multiple times. Running python -m pytest does not solve the issue, but it make the pytest to work.

My solution is straightforward:

Create empty conftest.py file at root directory.

It helps the pytest to find 'src' folder in this case.

[Exercise] Contact Book App/
|-- src/
|   |-- main.py  
|-- tests/
|   |-- test_main.py
|-- conftest.py  # just empty file

Upvotes: 4

Mark
Mark

Reputation: 336

I ran into the same issue, and my solution was to execute pytest as a module.

python -m pytest

Upvotes: 15

rite2hhh
rite2hhh

Reputation: 412

It seems that you have marked src as a "Source Root" directory in PyCharm (blue color for the directory indicates that), which means that it's added to the PATH.

That's why it works in PyCharm and not from the shell. Your PyCharm and terminal environments have different PATH's set.

Try to change the import from

from src.agents import prob

to

from proj_lokalizacja.src.agents import prob

alongside with running pytest from the same location (as we discussed in the comments)

If you do not wish to change your import statements, you'll have to update the PATH environment variable to also include src directory

Upvotes: 0

Related Questions