gpt4 book ai didi

python - 使用 pytest 在 Python 中进行单元测试

转载 作者:太空宇宙 更新时间:2023-11-03 16:57:08 25 4
gpt4 key购买 nike

目前我的项目目录的组织结构如下:

.
+-- 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 执行某些操作。

关于python - 使用 pytest 在 Python 中进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35329253/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com