我正在使用 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."
是否可以对类进行monkeypatch 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)