[英]Monkey patch python with statement
我正在使用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)
我认为你试图做的是Python语言规范不允许的。
正如您在PEP-343中所看到的,“with”语句的定义将不允许任何尝试提前退出上下文:
mgr = (EXPR)
exit = type(mgr).__exit__ # Not calling it yet
value = type(mgr).__enter__(mgr)
exc = True
try:
try:
VAR = value # Only if "as VAR" is present
BLOCK
except:
# The exceptional case is handled here
exc = False
if not exit(mgr, *sys.exc_info()):
raise
# The exception is swallowed if exit() returns true
finally:
# The normal and non-local-goto cases are handled here
if exc:
exit(mgr, None, None, None)
有人提议将此更改为您需要的功能( PEP-377 ),但这已被拒绝。
从@ Peter的答案可以清楚地看出,我们不能将整个块作为noop
。 我最后为我的用例做了以下事情。
# Module foo.py
class Foo(object):
def __init__(self):
print "class inited"
def __enter__(self):
print "entered class"
return None
def foo(self):
raise Exception("Not implemented")
def __exit__(self, type, value, traceback):
print "exited class"
return True
----------------------------
# Module FooTest
import foo
class FooTest(object):
def __init__(self):
print "class inited"
def __enter__(self):
print "entered class"
return None
def __exit__(self, type, value, traceback):
print "exited class"
return True
try:
foo.Foo()
print "It shouldn't print"
except:
print "Expected exception"
setattr(foo, 'Foo', FooTest)
print "Patched"
with foo.Foo() as a:
a.foo()
print "It shouldn't print"
print 'Test passed!'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.