python - 将上下文管理器与 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 f
是f
在with
.
这是我希望以单元测试形式出现的行为。我不知道如何让我想要的行为通过:
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'
解决方案
推荐阅读
- python - 为什么python修改元组中的列表并抛出异常
- r - 根据列的其他值向 data.table 中的每周数据添加多列的有效方法
- mapping - 将图像结果剪辑到 Google 地球引擎中的 ROI
- amazon-web-services - AWS SNS - 尝试在 aws 上保存短信首选项时出错
- azure - Azure ServiceBusConnection 应该是单例的吗?
- r - R逻辑回归和边际效应 - 如何排除分类自变量中的NA值
- powershell - 纠缠测试模块是否存在。不应抛出特定的 ExceptionType
- javascript - 使用 jQuery 的 attr() 编写 if 语句
- java - 从右手方向使用 JAVA 中的子字符串
- java - Ant javac 任务未编译。它的 'srcdir' 参数的行为不像记录的那样。这是一个错误吗?