def setup_with_context_manager(testcase, cm):
    """
    Use a contextmanager in a test setUp that persists until teardown.
    So instead of:

    with ctxmgr(a, b, c) as v:
        # do something with v that only persists for the `with` statement

    use:

    def setUp(self):
        self.v = setup_with_context_manager(self, ctxmgr(a, b, c))

    def test_foo(self):
        # do something with self.v
    """
    val = cm.__enter__()
    testcase.addCleanup(cm.__exit__, None, None, None)
    return val