めも

主にUnity

Testing async code in python

非同期でpytestを使う場合、pytest-asyncioを使うことになるが、やや使いにくいのでunittestのIsolatedAsyncioTestCaseを使った。

実装例

from asyncio import sleep
from unittest import IsolatedAsyncioTestCase
# test case を得るために非同期関数を呼ばなければいけないときが一番ややこしい。
async def add(a, b) -> int:# function to test
    await sleep(1)
    return a + b

async def get_test_case(x) -> tuple[int, int]:
    await sleep(1)
    return x, 2*x

@parameterized_class(('testcase_func', 'testcase_param', 'answer'), [
    (staticmethod(get_test_case), 2, 6),
    (staticmethod(get_test_case), 3, 9),
])
class TestClass1(IsolatedAsyncioTestCase):
    a: int
    b: int

    async def asyncSetup(self) -> None:
        self.a, self.b = await self.testcase_func(testcase_param)

    async def test_add() -> None:
        self.assertEqual(add(self.a, self.b), self.answer)