【发布时间】:2019-03-15 19:26:39
【问题描述】:
想象一个简单的文件夹结构:
my_folder/
__init__.py
funcs.py
tests/
test_funcs.py
funcs.py:
def f():
return 2
__init__.py:
from funcs import f
test_funcs.py:
from funcs import f
def test_f():
assert f() == 2
这是文档中建议的方法之一: https://pytest.readthedocs.io/en/reorganize-docs/new-docs/user/directory_structure.html
但是当我从 my_folder 运行 pytest 时:
tests/test_funcs.py:1: in <module>
from funcs import f
E ModuleNotFoundError: No module named 'funcs'
这很奇怪,因为我本以为 pytest 设置了它运行的路径,所以如果不手动处理就不会出现这些错误。
文档也没有对此给出任何指示......他们只是说:
通常您可以通过指向测试目录或模块来运行测试:
pytest tests/test_appmodule.py # for external test dirs pytest src/tests/test_appmodule.py # for inlined test dirs pytest src # run tests in all below test directories pytest # run all tests below current dir
我错过了什么?
【问题讨论】:
-
你的
__init__.py你应该有from .funcs import f-- 你正在做一个相对于包的导入 -
@AnthonySottile 我也考虑过这个解决方案。不幸的是,使用该修改运行 pytest 仍然会产生相同的错误:
E ModuleNotFoundError: No module named 'funcs' -
哦,你的测试文件也应该有
from my_folder.funcs import f--$ python -m pytest -q my_folder==>1 passed in 0.01 seconds -
行得通! (当它在 my_folder 之外运行时)。但是在 my_folder 中运行
pytest仍然失败 -
这证明文档缺少一些东西!您甚至提供了另一种运行测试的方法!文档只是说
pytest...
标签: python python-import pytest