[英]Python: ImportError: attempted relative import with no known parent package
I have a very simple python project:我有一个非常简单的 python 项目:
sample/__init__.py
sample/main.py
tests/test_sample.py
main.py
contains: main.py
包含:
def echo_the_arg(the_arg):
return the_arg
test_sample.py
contains: 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
My IDE resolves sample.main
module OK:我的 IDE 解析
sample.main
模块 OK:
but when I attempt to run the test from the root of the project by issuing pytest tests
I get an error:但是当我尝试通过发出
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'
I've perused the many many search results on SO pertaining to relative imports like this but I'm none the wiser as to why i'm getting this failure.我已经仔细阅读了很多关于 SO 的搜索结果,这些结果与这样的相对进口有关,但我对为什么我会遇到这种失败一无所知。 Why can pytest not find my
sample
module?为什么pytest找不到我的
sample
模块?
UPDATE, I discovered I can run my tests by running python -m pytest tests
更新,我发现我可以通过运行
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 =======================
so I'm left wondering why just running pytest
from the command-line fails.所以我想知道为什么从命令行运行
pytest
会失败。
I figured it out.我想到了。 I needed to add an extra (empty)
__init__.py
file.我需要添加一个额外的(空的)
__init__.py
文件。 So my structure now looks like this:所以我的结构现在看起来像这样:
sample/__init__.py
sample/main.py
tests/__init__.py
tests/test_sample.py
Output: Output:
(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 =======================
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.