When encountering the error "ImportError: No module named..." while using pytest, it is important to consider the potential issue of PATH configuration, especially on Linux or Windows systems. In this specific case, the user has installed pytest using easy_install on a Mac and encountered the problem while testing a project with the following file structure:
repo/ |--app.py |--settings.py |--models.py |--tests/ |--test_app.py
To resolve this issue, the following approaches are recommended:
Pytest has introduced a core plugin that enables sys.path modifications via the 'pythonpath' configuration setting. This simplified solution involves adding the following lines to your project's pyproject.toml or pytest.ini file:
# pyproject.toml [tool.pytest.ini_options] pythonpath = [ "." ] # pytest.ini [pytest] pythonpath = .
By specifying the path entries relative to the root directory, you effectively add that directory to sys.path, resolving the import issues.
For older versions of pytest, a less invasive approach involves creating an empty file named 'conftest.py' in the project's root directory:
$ touch repo/conftest.py
By doing so, pytest will automatically add the parent directory of 'conftest.py' to sys.path, enabling successful imports.
Pytest searches for 'conftest' modules during test collection to gather custom hooks and fixtures. To import these custom objects, pytest adds the parent directory of 'conftest.py' to sys.path.
The recommended approach for resolving import issues in pytest depends on the version you are using. For pytest >= 7, the 'pythonpath' configuration is preferred, while for pytest < 7, the 'conftest' solution remains effective.
The above is the detailed content of How Do I Fix 'ImportError: No module named...' Errors in Pytest?. For more information, please follow other related articles on the PHP Chinese website!