pythonpytestmodulenotfounderror

moduleNotFoundError: no module named (*)


 I'm trying to run my tests using python -m pytest but I get an error that ModuleNotFoundError: No module named 'sample' When using nosetests or anything else it works fine, but when trying to use pytest, it doesn't work. My tree looks like below, do you have any advice why it doesn't work?

├── LICENSE.txt
├── README.md
├── data
│   └── data_file
├── exported_register.csv
├── pyproject.toml
├── requirements.txt
├── setup.cfg
├── setup.py
├── src
│   └── sample
│       ├── __init__.py
│       ├── __pycache__
│       │   ├── __init__.cpython-39.pyc
│       │   ├── dziennik.cpython-39.pyc
│       │   ├── przedmiot.cpython-39.pyc
│       │   ├── simple.cpython-39.pyc
│       │   └── uczen.cpython-39.pyc
│       ├── dziennik.py
│       ├── package_data.dat
│       ├── przedmiot.py
│       ├── simple.py
│       └── uczen.py
├── tests
│   ├── __init__.py
│   ├── __pycache__
│   │   ├── __init__.cpython-39.pyc
│   │   ├── test_ASSERTPY_uczen.cpython-39-pytest-6.2.1.pyc
│   │   ├── test_ASSERTPY_uczen.cpython-39-pytest-6.2.5.pyc
│   │   ├── test_ASSERTPY_uczen.cpython-39.pyc
│   │   ├── test_PYHAMCREST_uczen.cpython-39-pytest-6.2.1.pyc
│   │   ├── test_PYHAMCREST_uczen.cpython-39-pytest-6.2.5.pyc
│   │   ├── test_PYHAMCREST_uczen.cpython-39.pyc
│   │   ├── test_UNITTEST_register.cpython-39-pytest-6.2.1.pyc
│   │   ├── test_UNITTEST_register.cpython-39-pytest-6.2.5.pyc
│   │   ├── test_UNITTEST_register.cpython-39.pyc
│   │   ├── test_UNITTEST_uczen.cpython-39-pytest-6.2.1.pyc
│   │   ├── test_UNITTEST_uczen.cpython-39-pytest-6.2.5.pyc
│   │   ├── test_UNITTEST_uczen.cpython-39.pyc
│   │   ├── test_simple.cpython-39-pytest-6.2.1.pyc
│   │   ├── test_simple.cpython-39-pytest-6.2.5.pyc
│   │   └── test_simple.cpython-39.pyc
│   ├── test_ASSERTPY_uczen.py
│   ├── test_PYHAMCREST_uczen.py
│   ├── test_UNITTEST_register.py
│   ├── test_UNITTEST_uczen.py
│   └── test_simple.py
└── tox.ini

Solution

  • When you run pytest with python -m pytest it uses the current directory as it its working dir, which doesn't contain the sample module (located inside ./src). The way I deal with this is I have a conftest.py inside my tests directory where I add my source dir to python path something like this:

    import os
    from pathlib import Path
    import sys
    
    source_path = Path(__file__).parents[1].joinpath("src").resolve()
    sys.path.append(os.fspath(source_path))