Pytest no module named src

Pytest: No Module Named ‘src’ Error

When encountering the “No module named ‘src'” error in pytest, it implies that pytest is unable to find the specified module or package ‘src’ in the current directory or in the PYTHONPATH.

This error is commonly encountered when the module or package ‘src’ is missing or not properly referenced in the test case files. To resolve this issue, you can follow the steps below:

  1. Make sure that the ‘src’ module or package is available.
  2. Check the directory structure and verify if the ‘src’ module or package is placed in the correct location.
  3. Ensure that the ‘src’ package contains the required ‘__init__.py’ files in each relevant directory, which marks them as Python packages.
  4. Ensure that the ‘src’ package is accessible in the current directory or in the PYTHONPATH.

Here’s an example to illustrate a possible directory structure:

    project/
    │
    ├─ tests/
    │    └─ test_sample.py
    │
    └─ src/
         ├─ __init__.py
         └─ my_module.py
  

In the above example, the ‘src’ package contains a ‘__init__.py’ file, marking it as a package, and a custom module ‘my_module.py’.

Next, let’s assume we have a test case in ‘test_sample.py’, which requires importing the ‘my_module’ from the ‘src’ package:

    # test_sample.py
    from src.my_module import my_function

    def test_my_function():
        # ...
        assert my_function() == expected_result
  

Ensure that the ‘src’ package is accessible in the current directory or PYTHONPATH. This can be achieved by executing pytest from the parent directory:

    $ cd project/
    $ pytest tests/
  

By running pytest from the parent directory, the ‘src’ package will be discoverable, and the ‘No module named ‘src” error should not occur anymore.

Leave a comment