pytest的文件夹结构和导入问题
Folder structure and import problems with pytest
想象一个简单的文件夹结构:
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
会设置路径 运行ning,所以如果不手动处理这些错误就不会出现。
文档也没有给出任何说明...他们只是说:
Typically you can run tests by pointing to test directories or modules:
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
我错过了什么?
测试文件 test_funcs.py
必须来自模块 funcs
所在目录中的 运行 才能成功导入。
作为解决方法,您可以修改 sys.path
,它决定了 interpeter 的模块搜索路径。
test_funcs.py
:
import sys
sys.path.append('/Users/Yahya/Desktop/my_folder')
from funcs import f
def test_f():
assert f() == 2
这是一个非常简单的方法:
- 清空
__init__.py
- 高于
my_folder
运行 python -m pytest
或 python -m pytest tests
(但不是 pytest
)
说明: 运行 带有 -m
选项的模块将把它包含在 PYTHONPATH
中,因此与导入语句相关的所有内容会顺利解决的。
想象一个简单的文件夹结构:
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
会设置路径 运行ning,所以如果不手动处理这些错误就不会出现。
文档也没有给出任何说明...他们只是说:
Typically you can run tests by pointing to test directories or modules:
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
我错过了什么?
测试文件 test_funcs.py
必须来自模块 funcs
所在目录中的 运行 才能成功导入。
作为解决方法,您可以修改 sys.path
,它决定了 interpeter 的模块搜索路径。
test_funcs.py
:
import sys
sys.path.append('/Users/Yahya/Desktop/my_folder')
from funcs import f
def test_f():
assert f() == 2
这是一个非常简单的方法:
- 清空
__init__.py
- 高于
my_folder
运行python -m pytest
或python -m pytest tests
(但不是pytest
)
说明: 运行 带有 -m
选项的模块将把它包含在 PYTHONPATH
中,因此与导入语句相关的所有内容会顺利解决的。