Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does pytest return a ModuleNotFoundError when trying to import the src folder?

I have a project named unit_testing with 2 subfolders named src/ and tests/. In src there is a file called my_functions.py and in tests I have a file called test_my_functions.py.

This is the code in my_functions.py

def adding_pos(a, b, c):
if a < 0 or b < 0 or c < 0:
    output = f'function needs positive numbers'
else:
    output = a + b + c
return output

This is the code in test_my_functions.py

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

# import libs

import pytest
from src.my_functions import adding_pos


# %% test

class TestAddingPos(object):
    def test_adding(self):
        assert adding_pos(2, 5, 6) == 13

    def test_adding_neg(self):
        assert adding_pos(-1, 2, 3) == 'function needs positive numbers'

In the CLI, if I go to the test folder and then run pytest, I keep getting a ModuleNotfoundError saying the src module can not be found. I don’ understand why because in test_my_functions.py I import functions from src.my_functions and this works.

Why does this not work?

>Solution :

It looks like you’re trying to run tests in the tests/ directory that imports modules from the src/ directory. When you run pytest from the tests/ directory, it doesn’t know where to find the src/ directory.

To fix this, you can add an empty file called __init__.py to the src/ directory. This will make Python treat the directory as a package and allow you to import modules from it.

You can also add the path to the src/ directory to your system’s Python path. You can do this by adding the following code at the top of your test file:

import sys
sys.path.insert(0, '/path/to/src')

Replace /path/to/src with the actual path to your src/ directory.

Here’s the modified code with the path added to the system’s Python path:

import sys
sys.path.insert(0, '/path/to/src')

# import libs

import pytest
from src.my_functions import adding_pos


# %% test

class TestAddingPos(object):
    def test_adding(self):
        assert adding_pos(2, 5, 6) == 13

    def test_adding_neg(self):
        assert adding_pos(-1, 2, 3) == 'function needs positive numbers'

Replace /path/to/src with the actual path to your src/ directory.
I hope it works mate 🙂

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading