我有一个非常简单的Python项目:
sample/__init__.py
sample/main.py
tests/test_sample.py
main.py
包含:
def echo_the_arg(the_arg):
return the_arg
test_sample.py
包含如下内容:
import unittest
from sample.main import echo_the_arg
class SampleTest (unittest.TestCase):
def test_echo_the_arg(self):
assert echo_the_arg(1) == 1
我的IDE可以正常解析sample.main
模块:
但是,当我尝试通过发出pytest tests
命令从项目的根目录运行测试时,我会遇到错误:
ImportError while importing test module '/Users/me/python-project-template/tests/test_sample.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
/usr/local/Cellar/python@3.9/3.9.2_4/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py:127: in import_module
return _bootstrap._gcd_import(name[level:], package, level)
tests/test_sample.py:2: in <module>
from sample.main import echo_the_arg
E ModuleNotFoundError: No module named 'sample'
我已经查看了许多与相对导入相关的SO搜索结果,但我对为什么会出现此错误仍然不清楚。为什么pytest找不到我的sample
模块?
更新,我发现可以通过运行python -m pytest tests
来运行我的测试。
platform darwin -- Python 3.9.2, pytest-6.2.4, py-1.10.0, pluggy-0.13.1
rootdir: /Users/me/python-project-template
collected 1 item
tests/test_sample.py . [100%]
======================= 1 passed in 0.02s =======================
我很好奇为什么仅仅从命令行运行pytest
就会失败。