使用 pytest 在 Python 中进行单元测试
Unit tests in Python with pytest
目前我的项目目录结构如下:
.
+-- module1
+-- module2
...
+-- moduleN
+-- test
+-- test_module1_item1.py
...
+-- test_moduleN_itemM.py
但是当我在我的上层目录执行py.test
时,它会抛出这样的错误:
ImportError: No module named 'module1'
测试文件中的导入应该如何声明?或者应该如何定义我的项目结构以便将测试与其余代码分开?
我怀疑 ./test
中缺少 __init__.py
» ls *
module1:
__init__.py
test:
test_module1_item1.py
让我们试试测试
» py.test
...
ERROR collecting test/test_module1_item1.py
test/test_module1_item1.py:8: in <module>
import module1
E ImportError: No module named module1
这看起来像是你的错误。
» touch test/__init__.py
» py.test
test/test_module1_item1.py:10: in <module>
assert 1 == 2
E assert 1 == 2
这看起来像你的解决方案。我怀疑 py.test 正在根据 ./test
是否是一个模块对 $pythonpath 做一些事情。
目前我的项目目录结构如下:
.
+-- module1
+-- module2
...
+-- moduleN
+-- test
+-- test_module1_item1.py
...
+-- test_moduleN_itemM.py
但是当我在我的上层目录执行py.test
时,它会抛出这样的错误:
ImportError: No module named 'module1'
测试文件中的导入应该如何声明?或者应该如何定义我的项目结构以便将测试与其余代码分开?
我怀疑 ./test
__init__.py
» ls *
module1:
__init__.py
test:
test_module1_item1.py
让我们试试测试
» py.test
...
ERROR collecting test/test_module1_item1.py
test/test_module1_item1.py:8: in <module>
import module1
E ImportError: No module named module1
这看起来像是你的错误。
» touch test/__init__.py
» py.test
test/test_module1_item1.py:10: in <module>
assert 1 == 2
E assert 1 == 2
这看起来像你的解决方案。我怀疑 py.test 正在根据 ./test
是否是一个模块对 $pythonpath 做一些事情。