3

我正在使用 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)
4

2 回答 2

1

我认为 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),但已被拒绝。

于 2015-06-18T22:33:48.327 回答
0

从@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!'
于 2015-06-19T03:39:07.893 回答