Skip to content

Instantly share code, notes, and snippets.

@cjerdonek
Created June 24, 2012 19:16
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cjerdonek/2984537 to your computer and use it in GitHub Desktop.
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()
# 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()
@Tarrasch
Copy link

Tarrasch commented Sep 1, 2015

Thanks! :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment