简体   繁体   English

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

[英]Unit tests in Python with pytest

Currently my project's directory is organized as the following structure:目前我的项目目录按以下结构组织:

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

But when I execute py.test in my upper level directory, it throws an error like:但是当我在我的上级目录中执行py.test时,它会抛出如下错误:

ImportError: No module named 'module1'导入错误:没有名为“module1”的模块

How the imports in the test files should be declared?应如何声明测试文件中的导入? Or how my project structure should be defined in order to the tests be separated from the rest of the code?或者应该如何定义我的项目结构以便将测试与其余代码分开?

I suspect __init__.py is missing from ./test我怀疑./test缺少__init__.py

» ls *
module1:
__init__.py

test:
test_module1_item1.py

Let's try testing让我们尝试测试

» 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

This looks like your error.这看起来像你的错误。

» touch test/__init__.py
» py.test

test/test_module1_item1.py:10: in <module>
    assert 1 == 2
E   assert 1 == 2

This looks like your solution.这看起来像您的解决方案。 I suspect py.test is doing something with the $pythonpath based on whether ./test is a module or not.我怀疑 py.test 正在根据./test是否是模块对 $pythonpath 做一些事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM