如何修复 pytest E ModuleNotFoundError: No module named ...
问题
在你的项目中运行 pytest 时,你看到以下错误消息:
pytest_import_error.txt
________ ERROR collecting test/test_Algorithms.py ________
ImportError while importing test module '/home/uli/dev/MyModule/test/test_Algorithms.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
/usr/lib/python3.10/importlib/__init__.py:126: in import_module
return _bootstrap._gcd_import(name[level:], package, level)
test/test_Algorithms.py:3: in <module>
from MyModule.Algorithms import Algorithms
E ModuleNotFoundError: No module named 'MyModule'解决方案
在你的 tests 目录中,创建 __init__.py:
create_tests_init.sh
touch tests/__init__.py在不常见的情况下,如果这不起作用,你可能需要将项目根目录添加到 PYTHONPATH:
run_pytest_with_pythonpath.sh
PYTHONPATH=. pytestsCheck out similar posts by category:
Python, Unit Testing
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow