[Python] Unit Test is not executable by using Pytest

Discussão em 'Python' iniciado por Stack, Maio 8, 2025.

  1. Stack

    Stack Membro Participativo

    I am currently using Pytest as my unit test framework in my Python project (which is a backend service based on AWS Chalice framework). I put my unit tests under a repository named tests as the document says, and it works well.

    However, when I try to run a unit test in the same structure in a pure python project, it went failed by receiving ModuleNotFoundError: No module named 'src'.

    My structure looks like,

    .
    ├── src
    │ └── module_a.py
    └── tests
    └── test_module_a.py


    ./src/module_a.py

    def square(num: int) -> int:
    """Returns the square of a number."""
    return num * num


    ./tests/test_module_a.py

    from src.module_a import square

    def test_square():
    assert square(8) == 64


    and the error I got is

    Traceback:
    ../../../opt/anaconda3/envs/py3.11/lib/python3.11/importlib/__init__.py:126: in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
    tests/test_module_a.py:1: in <module>
    from src.module_a import square
    E ModuleNotFoundError: No module named 'src'
    =========================================================================== short test summary info ===========================================================================
    ERROR tests/test_module_a.py


    I have take a look into my previous project, and just can't find where the environment path is setup. I'm so confused and don't know how to figure it.

    Continue reading...

Compartilhe esta Página