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:
- Make sure that the ‘src’ module or package is available.
- Check the directory structure and verify if the ‘src’ module or package is placed in the correct location.
- Ensure that the ‘src’ package contains the required ‘__init__.py’ files in each relevant directory, which marks them as Python packages.
- 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.
- Pyrcc5′ is not recognized as an internal or external command
- Property ‘join’ does not exist on type ‘string’
- Protoc relative path
- Pycdc.exe download
- Property ref does not exist on type
- Processing string to int
- Packagesnotfounderror: the following packages are missing from the target environment: – tensorflow
- Pydantic partial model
- Pyspark sort array of structs
- Pytest modulenotfounderror: no module named ‘src’