我有一个简单的 python 模块(我们称之为 M1),它是独立的(唯一的导入是 collections),在一个包含丑陋的包中。部分丑陋之处在于包的 __init__.py 文件。但是 M1 很好很干净,并且包含一些与 py.test 一起使用的测试函数。
现在,我想测试一下M1,忽略所有的丑陋。但是 py.test 想要运行 __init__.py -- 有什么办法可以防止这种情况发生吗?我真的无法修复 __init__.py 文件,我想将我的测试函数包含在 M1 模块内容本身的旁边。
我已经读过这个 SO 问题:`py.test` and `__init__.py` files这解释了问题,但没有提供解决方案。
我的 __init__.py 文件看起来像这样;它只是将项目提升到包范围内:
from .M1 import CleanThing1, CleanThing2
from .Evil1 import UglyThing1, UglyThing2
问题是 Evil1 模块需要一些 PYTHONPATH 黑客才能正确执行,当我运行时
py.test mymodule/M1.py
由于 Evil1 模块,它失败了。但我现在只想测试 M1 模块。
请您参考如下方法:
您可以使 __init__.py 文件知道 py.test,如 here 所述.
所以基本上创建一个包含以下内容的mymodule/conftest.py文件
def pytest_configure(config):
import sys
sys._called_from_test = True
def pytest_unconfigure(config):
del sys._called_from_test
并在 __init__.py 文件中简单地检查您是否在 py.test session 中,就像
import sys
if hasattr(sys, '_called_from_test'):
# called from within a test run
pass
else:
# failing imports
from .M1 import CleanThing1, CleanThing2
from .Evil1 import UglyThing1, UglyThing2
这样我就可以运行 py.test mymodule/M1.py 而不会出现导入错误。
包结构现在看起来像(我希望它类似于你的结构)
package
|
|- __init__.py
|- mymodule/
|- M1.py
|- conftest.py
