我有以下项目结构:
foo
│
├── foo
│ ├── cli
│ │ ├── tests
│ │ └── __init__.py
│ ├── core
│ │ ├── tests
│ │ └── __init__.py
│ ├── tests
│ │ ├── __init__.py
│ │ └── test_foo.py
│ ├── __init__.py
│ └── foo.py
├── kube
├── requirements
├── ...any-other-non-source-related
└── README.md
在 foo/foo.py
文件中,我有以下占位符代码:
import cli
import core
def say_hi():
print('hi')
if __name__ == '__main__':
say_hi()
在文件 foo/tests/test_foo.py
上,我有以下内容:
from foo import foo
def test_foo():
foo.say_hi()
assert False
然后,在 shell 中,我得到以下信息:
$ python foo/foo.py
hi
$ pipenv run pytest
===================== test session starts =====================
platform linux -- Python 3.7.4, pytest-5.3.1, py-1.8.0, pluggy-0.13.1
rootdir: /xxx/xxx/xxx/xxx/python-project-folder-structures
collected 0 items / 1 error
===================== ERRORS =====================
_____ ERROR collecting foo/tests/test_foo.py _____
ImportError while importing test module '/xxx/xxx/xxx/xxx/python-project-folder-structures/foo/tests/test_foo.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
foo/tests/test_foo.py:1: in <module>
from foo import foo
foo/foo.py:1: in <module>
import cli
E ModuleNotFoundError: No module named 'cli'
!!!!!!! Interrupted: 1 error during collection !!!!!!!
===================== 1 error in 0.05s =====================
有人可以帮忙吗?为什么 Pytest 没有建立我的导入?我尝试了多种方法,即使在 foo
文件夹(根级别)之外使用 tests
文件夹,但错误仍然存在。
我发现解决这个问题的唯一方法是将 conftest.py
文件放在代码级别,这样它就会被 pytest
发现。我真的不想这样做,因为我想将测试与源代码分离。
最佳答案
如果有人为此苦苦挣扎,我能够找到解决方案。我从 foo
目录中删除了 __init__.py
文件,给出了以下结构:
foo
│
├── foo
│ ├── cli
│ │ ├── tests
│ │ └── __init__.py
│ ├── core
│ │ ├── tests
│ │ └── __init__.py
│ ├── tests
│ │ ├── __init__.py
│ │ └── test_foo.py
│ └── foo.py
├── kube
├── requirements
├── ...any-other-non-source-related
└── README.md
他们,在 mt 测试中,我现在得到以下结果:
import foo
def test_foo():
foo.say_hi()
assert False
我注意到 Pytest 的行为是从测试一直到根目录,识别包。由于 foo
是一个包(带有 __init__.py
文件),因此它会将其作为一个包添加到我的 PATH
:)
重要
请注意,import foo
语句涉及 foo.py
文件,而不是 foo
目录。因此,如果您的文件在 foo
目录中名为 boo.py
,则导入应为:import boo
关于在 Pytest 上找不到 Python 包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59120154/