Created
June 24, 2012 19:16
-
-
Save cjerdonek/2984537 to your computer and use it in GitHub Desktop.
For Python unit testing, using a context manager instead of setUp() and tearDown()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# For Python unit testing, an idea for how to use a context manager for | |
# a unittest.TestCase instead of the setUp() and tearDown() methods. | |
# | |
# This is a possible answer to-- | |
# | |
# http://stackoverflow.com/questions/8416208/in-python-is-there-a-good-idiom-for-using-context-managers-in-setup-teardown | |
from contextlib import contextmanager | |
import unittest | |
@contextmanager | |
def resource_manager(): | |
yield 'foo' | |
class MyTest(unittest.TestCase): | |
def run(self, result=None): | |
with resource_manager() as resource: | |
self.resource = resource | |
super(MyTest, self).run(result) | |
def test(self): | |
self.assertEqual('foo', self.resource) | |
unittest.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks! :)