1

I'm running an integration test with unittest, and each test case must share a session to a server. (Too many new sessions are blocked). I want my unittest class to create a new session object once.

The standard @classmethod is never awaited, so this does not work:

class IntegrationTest(unittest.IsolatedAsyncioTestCase):
    @classmethod
    async def setUpClass(self):  # not possible
        self.session = await get_new_aio_session()

This hack to skip get_new_aio_session() does not work. Each new test does not share 'self', apparently. So I still get a new self.session for each test.

async def asyncSetUp(self):
        if hasattr(self, 'session'): # not possible
            return
        self.session = await get_new_aio_session()

What I want is something like

class IntegrationTest(unittest.IsolatedAsyncioTestCase):
    async def fixture(self):
        # this only runs once
        self.session = await get_new_aio_session()

    async def test_a(self):
        case = foo(session=self.session)
        self.assertEqual("foo", case.status)        

    async def test_b(self):
        case = bar(session=self.session)
        self.assertEqual("bar", case.status)        


My question is relatable to this Is there an async equivalent of setUpClass in Python 3.10?

Anders_K
  • 982
  • 9
  • 28
  • If possible, I'd recommend switching to pytest for your tests. It is unittest compatible: so existing tests continue valid, and there are options for a lot of control on when to run setup and teardown code, as well as extensions to proper test async code. – jsbueno Jun 19 '23 at 17:40
  • https://docs.pytest.org/en/7.3.x/ – jsbueno Jun 19 '23 at 17:40

0 Answers0