Explain Codes LogoExplain Codes Logo

Pytest cannot import module while python can

python
pytest
virtual-environment
import-resolution
Alex KataevbyAlex Kataev·Dec 18, 2024
TLDR

To ensure that pytest uses the same environment as Python, match their versions using pytest --version and python -m pytest --version. The root of issues can often be found in environment differences or PATH discrepancies; both invocations should produce the same outcome. Direct pytest to your module with:

python -m pytest /path/to/your/module

For pytest to correctly recognize packages, each directory should contain an __init__.py. It's crucial to avoid conflicts with standard library modules that may result in import mismatches.

Solutions for common scenarios

1. Directory Structure & init.py

Directory structure plays an important role. Ensure a conftest.py is resident in your tests root if your modules are imported implicitly. __init__.py, though not a necessity in Python 3 for packages, can clear up any ambiguity pytest may have in the "paths" department when present in your test directories.

2. Under the hood: sys.path

By adding the following at the start of your test file, you can get Python to spill the beans on its module paths.

# Don't be shy, Python. Show us what you got! import sys print(sys.path)

Compare the output when run with pytest and python. If there’s a difference, tweak your PYTHONPATH environment variable or use pytest’s --rootdir option to adjust the search trail.

3. Virtual Environment Sanity Check

Double-check these if you're using a virtual environment:

  • Is your virtual environment activated?
  • Is pytest installed within this environment?
  • Are you mistakenly running pytest installed globally?

4. Cracking the conftest.py code

conftest.py can set your test environment stage. Verify its configuration and ensure folder levels are not messing with import resolution.

Further Investigation

1. Ensuring Correct Environment

Always remember to use source venv/bin/activate before invoking pytest, so there’s no accidental use of a different Python or pytest version installed on your system. which python and which pytest will confirm the versions in use.

2. Clearing Path Caches

Shell caches can lead old paths to persist. Use hash -r or specify the pytest full executable path in your virtual environment to prevent this.

3. Circular Imports

Check for sneaky circular imports. They can trigger import errors that behave differently under pytest due to its test collection process.

4. .pth files: Friend or Foe?

Examine your .pth files in the site-packages directory; they might be meddling with your sys.path that works in Python but stirs chaos in pytest.

5. Absolute > Relative Imports

Favor absolute imports over relative ones in tests. They prevent complications that arise from complex directory structures.