首页 > 解决方案 > 将上下文管理器与 X() 一起用作 foo 然后在使用后检查来自 foo 的信息的模式是什么?

问题描述

我想做类似的事情:

with open("a.txt"), 'w') as f:
    f.write("update1")
    raise Exception("Mocked error for this unit test")

assert f.closed == True

这是一个愚蠢的例子,但我想要的行为with X() as ffwith.

这是我希望以单元测试形式出现的行为。我不知道如何让我想要的行为通过:

with LogManager(self.tv) as lm:        
    # do some stuff
    raise Exception("Oh no! Unexpected Exception!")
self.assertIsNotNone(lm)
self.assertTrue(os.path.exists(lm.filepath))

我可以通过执行以下操作来获得行为,首先将返回分配给一个函数,但我宁愿使用open as f. 我查看了来源,open但无法弄清楚如何复制它。

lm = LogManager(self.tv)
with lm:
    # do some stuff
    raise Exception("Oh no! Unexpected Exception!")

self.assertIsNotNone(lm)
self.assertTrue(os.path.exists(lm.filepath)

尝试的解决方案 1

LogManager 的尝试实现(精简到与我想要更改的行为相关的基本机制):

class LogManager(object):
    def __init__(self):
        self._result_file = None

    @property
    def filepath(self):
        return self._result_file

    def __enter__(self):
        self.tv._start_capture()

    def __exit__(self, exc_type, exc_value, traceback):
        self._result_file = self.tv._stop_capture()

尝试的解决方案 2

这基本上就是上述内容,但在单元测试之外以经过验证的可运行形式供人们尝试提供帮助。仍然不起作用,但至少它被进一步剥离。

from __future__ import unicode_literals, print_function, nested_scopes

import os
from contextlib2 import ContextDecorator

class Manager(ContextDecorator):
    def __init__(self):
        pass

    def __enter__(self):
        print("enter")
        self.a = "a"

    def __exit__(self, exc_type, exc_value, traceback):
        print("exit")
        self.z = "z"
        return "hello"

try:
    n = Manager()
    print("next manager")
    j = ""
    with Manager() as m:
        j = m
        print("one thing")
        raise Exception("Oh no!")
        print("another thing")
except:
    pass

print(type(j))
print(type(m))
print(m.a)
print(m.z)

输出

next manager
enter
one thing
exit
<type 'NoneType'>
<type 'NoneType'>
Traceback (most recent call last):
  File "test_context.py", line 48, in <module>
    print(m.a)
AttributeError: 'NoneType' object has no attribute 'a'

标签: pythonpython-2.7exception-handlingcontextmanager

解决方案


推荐阅读