Reputation: 83
I'm trying to understand the correct way to unit test code with context-manager (with statement).
Here is my sample code:
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'
Here is my unittest code:
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')
The sample code runs fine but the unittest code above fails with,
======================================================================
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)
What is causing this error? What am I missing?
Upvotes: 8
Views: 3968
Reputation:
You need to instantiate the resources
class when you use it with the with-statement:
with ctxmgr.resources() as r:
# ^^
Demo:
>>> 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>
>>>
Upvotes: 12