Skip to content
Advertisement

ImportError in test files

I’ve seen a lot of questions that are similar to this but none of the solutions have worked for me. I’m getting an import error when trying to run pytest on a test package I’m developing to teach myself how to create python packages.

Currently I have a python package that looks like

MyPackage/
  - src/
    - modules/
        - __init__.py
        - module_a.py
  - tests/
    - test_module_a.py

and my test_module_a.py contains

import pytest
from modules.module_a import MyClass

# ... some tests

Running the command pytest in the terminal displays

ImportError while importing test module '/Users/.../Desktop/MyPackage/tests/test_module_a.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
../../anaconda3/lib/python3.8/importlib/__init__.py:127: in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
tests/test_module_a.py:2: in <module>
    from modules.module_a import MyClass
E   ModuleNotFoundError: No module named 'modules'

I’ve attempted to add the path through the pycharm interpreter but it hasn’t fixed it. I’ve also seen ways that use the sys package to change the path in the test file, but I’m fairly certain there is a way to set up test to work in pycharm without it. Additionally I’d like to be prepared to setup automatic tests through github so figuring out a way that also integrates well with that would be ideal.

Advertisement

Answer

The error didn’t have anything to do with the environment. The tutorial I followed put a different name under name in setup.cfg than the module name, so setting that to match solved the problem.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement