I am using py.test for my python unit testing. Consider following code:
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."
Is it possible to monkeypatch TestClass
class so that code in with
block becomes a noop
?
For example, the output after patching should be:
Before with statement
After with statement
I know I can patch mytest
function itself, but this is in an attempt to have better test coverage.
I have tried, something on following lines but couldn't get it working.
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)
It's clear from @Peter's answer that we cannot make entire block as
noop
. I ended up doing following for my use case.