使用py.test,在不同目录中调用相同的两个测试会导致py.test失败。这是为什么?我怎样才能改变这一点,而无需重新命名所有的测试?py.test - 测试发现失败时,在不同目录中测试称为相同
要重复做:
; cd /var/tmp/my_test_module
; mkdir -p ook/test
; mkdir -p eek/test
; touch ook/test/test_proxy.py
; touch eek/test/test_proxy.py
; py.test
============================= test session starts ==============================
platform linux2 -- Python 2.7.3 -- pytest-2.2.4
collected 0 items/1 errors
==================================== ERRORS ====================================
___________________ ERROR collecting ook/test/test_proxy.py ____________________
import file mismatch:
imported module 'test_proxy' has this __file__ attribute:
/home/ygolanski/code/junk/python/mymodule/eek/test/test_proxy.py
which is not the same as the test file we want to collect:
/home/ygolanski/code/junk/python/mymodule/ook/test/test_proxy.py
HINT: remove __pycache__/.pyc files and/or use a unique basename for your test file modules
=========================== 1 error in 0.01 seconds ============================
我同意需要__init__.py有道理。如果测试不在包中,那么它本质上是一个顶级模块(在OP中是test_proxy),应该只有一个。通过将测试模块放入相关的包(ook和eek)中,它提供了适当的测试命名空间。我说现状是最好的。它可能会减轻一些痛苦,让错误信息链接到这个问题或文档中解释推理和解决问题的技术。 –
请注意,py.test文件特别建议不要在测试目录中放置'__init __。py':_“在您的测试目录中避免'__init __。py'文件。这样,您的测试可以轻松地对照已安装版本的mypkg运行,独立于安装的软件包是否包含测试“_”。采自[pytest.org - 良好集成实践](http://pytest.org/latest/goodpractises.html#choosing-a-test-layout-import-rules)。 – famousgarkin
更新:上面的@ famousgarkin评论和回答(https://stackoverflow.com/a/21942491/260303)中的建议似乎不再存在于文档中(至少搜索“避免”不会显示引用以上):https://docs.pytest.org/en/latest/goodpractices.html#tests-as-part-of-application-code。实际上,该链接中的示例在测试目录中显示“__init __。py”,所以看起来接受的答案是正确的。 –