【问题标题】:Unit tests in Python with pytest使用 pytest 在 Python 中进行单元测试
【发布时间】:2020-04-07 01:38:49
【问题描述】:

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

.
+-- module1
+-- module2
...
+-- moduleN
+-- test
    +-- test_module1_item1.py
    ...
    +-- test_moduleN_itemM.py

但是当我在上层目录中执行py.test 时,它会抛出如下错误:

ImportError: 没有名为“module1”的模块

应该如何声明测试文件中的导入?或者应该如何定义我的项目结构以便将测试与其余代码分开?

【问题讨论】:

  • 所有__init__.py 都在场吗?好像你没有找到你的模块。

标签: python pytest


【解决方案1】:

我怀疑./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。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-09
    • 1970-01-01
    相关资源
    最近更新 更多