Python:ImportError:尝试进行相对导入,但未知父包。

3

我有一个非常简单的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模块:

enter image description here

但是,当我尝试通过发出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就会失败。

1个回答

2
我找到了解决方法。我需要添加一个额外的(空的)__init__.py文件。所以现在我的结构看起来像这样:
sample/__init__.py
sample/main.py
tests/__init__.py
tests/test_sample.py

输出:

(venv) ➜  python-project-template git:(master) ✗ pytest tests          
=========================================================================================== test session starts ===========================================================================================
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 =======================

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接