title: In python, is there a good idiom for using context managers in setup/teardown
body: <p>I am finding that I am using plenty of context managers in Python. However, I have been testing a number of things using them, and I am often needing the following:</p>
  
  <pre><code>class MyTestCase(unittest.TestCase):
    def testFirstThing(self):
      with GetResource() as resource:
        u = UnderTest(resource)
        u.doStuff()
        self.assertEqual(u.getSomething(), 'a value')
  
    def testSecondThing(self):
      with GetResource() as resource:
        u = UnderTest(resource)
        u.doOtherStuff()
        self.assertEqual(u.getSomething(), 'a value')
  </code></pre>
  
  <p>When this gets to many tests, this is clearly going to get boring, so in the spirit of SPOT/DRY (single point of truth/dont repeat yourself), I'd want to refactor those bits into the test <code>setUp()</code> and <code>tearDown()</code> methods.</p>
  
  <p>However, trying to do that has lead to this ugliness:</p>
  
  <pre><code>  def setUp(self):
      self._resource = GetSlot()
      self._resource.__enter__()
  
    def tearDown(self):
      self._resource.__exit__(None, None, None)
  </code></pre>
  
  <p>There must be a better way to do this. Ideally, in the <code>setUp()</code>/<code>tearDown()</code> without repetitive bits for each test method (I can see how repeating a decorator on each method could do it).</p>
  
  <p><strong>Edit:</strong> Consider the undertest object to be internal, and the <code>GetResource</code> object to be a third party thing (which we aren't changing).</p>
  
  <p>I've renamed <code>GetSlot</code> to <code>GetResource</code> here—this is more general than specific case—where context managers are the way which the object is intended to go into a locked state and out.</p>