Python 上下文管理器的Unittest失败,AttributeError:\uu退出__
我试图理解使用上下文管理器(with语句)对代码进行单元测试的正确方法 以下是我的示例代码:Python 上下文管理器的Unittest失败,AttributeError:\uu退出__,python,with-statement,python-unittest,Python,With Statement,Python Unittest,我试图理解使用上下文管理器(with语句)对代码进行单元测试的正确方法 以下是我的示例代码: class resources(): def __init__(self): self.data = 'at-init' def __enter__(self): self.data = 'at-enter' return self def __exit__(self, exc_type, exc_val, exc_tb):
class resources():
def __init__(self):
self.data = 'at-init'
def __enter__(self):
self.data = 'at-enter'
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.data = 'at-exit'
以下是我的单元测试代码:
import unittest
import ctxmgr
class TestResources(unittest.TestCase):
def setUp(self):
pass
def test_ctxmgr(self):
with ctxmgr.resources as r:
self.assertEqual(r.data, 'at-enter')
示例代码运行正常,但上面的unittest代码失败
======================================================================
ERROR: test_ctxmgr (__main__.TestResources)
----------------------------------------------------------------------
Traceback (most recent call last):
File "test_ctxmgr.py", line 12, in test_ctxmgr
with ctxmgr.resources as r:
AttributeError: __exit__
----------------------------------------------------------------------
Ran 1 test in 0.003s
FAILED (errors=1)
是什么导致了这个错误?我缺少什么?当您将
资源类与with语句一起使用时,您需要实例化它:
with ctxmgr.resources() as r:
# ^^
演示:
>类资源():
... 定义初始化(自):
... self.data='at init'
... 定义输入(自我):
... self.data='at enter'
... 回归自我
... 定义退出(自身、exc类型、exc val、exc tb):
... self.data='在出口'
...
>>>资源如下:
... R
...
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
AttributeError:\uuu退出__
>>>
>>>将resources()作为r:
... R
...
>>>
>>> class resources():
... def __init__(self):
... self.data = 'at-init'
... def __enter__(self):
... self.data = 'at-enter'
... return self
... def __exit__(self, exc_type, exc_val, exc_tb):
... self.data = 'at-exit'
...
>>> with resources as r:
... r
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: __exit__
>>>
>>> with resources() as r:
... r
...
<__main__.resources object at 0x02112510>
>>>