【发布时间】:2015-09-03 23:18:34
【问题描述】:
我正在使用 py.test 进行我的 python 单元测试。考虑以下代码:
def mytest():
"Test method"
print "Before with statement"
with TestClass('file.zip', 'r') as test_obj:
print "This shouldn't print after patching."
# some operation on object.
print "After with statement."
是否可以对 TestClass 类进行猴子补丁,以便 with 块中的代码变为 noop?
比如打补丁后的输出应该是:
Before with statement
After with statement
我知道我可以修补 mytest 函数本身,但这是为了获得更好的测试覆盖率。
我已经尝试过,以下几行中的某些内容但无法正常工作。
class MockTestClass(object):
def __init__(self, *args):
print "__init__ called."
def __enter__(self):
print "__enter__ called."
raise TestException("Yeah done with it! Get lost now.")
def __exit__(self, type, value, traceback):
print "__exit__ called."
module_name.setattr('TestClass', MockTestClass)
【问题讨论】:
-
如果 zipFile.ZipFile 变为 no-op ,那么测试将如何进行?
-
抱歉,Anand,我稍微修改了我的代码。但目的是记录
TestClass()是用一些参数调用的,然后它应该立即退出with块。 -
我不确定我是否理解你的问题了。
标签: python pytest with-statement monkeypatching test-coverage