How to avoid ‘Asyncio runner is already initialised’ error, when running async tests in a for loop with Python’s Unittesting framework?

I am trying to run an async test case in a loop, with Python’s unittesting framework; however, I am running into a brick wall with the error: AssertionError: asyncio runner is already initialized

As part of my loop, I have to reinitialise the test suite as following:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>tests = get_tests()
suite = unittest.TestSuite(tests)
runner = unittest.TextTestRunner()
for _ in range(3):
result = runner.run(suite)
unittest.registerResult(result)
suite = unittest.TestSuite(tests)
</code>
<code>tests = get_tests() suite = unittest.TestSuite(tests) runner = unittest.TextTestRunner() for _ in range(3): result = runner.run(suite) unittest.registerResult(result) suite = unittest.TestSuite(tests) </code>
tests = get_tests()
suite = unittest.TestSuite(tests)
runner = unittest.TextTestRunner()

for _ in range(3):
  result = runner.run(suite)
  unittest.registerResult(result)
  suite = unittest.TestSuite(tests)

The test that is causing problems is (minimal version):

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>
async def basic_async_func():
await asyncio.sleep(2)
return 'hello'
class MyAsyncTestClass(unittest.IsolatedAsyncioTestCase):
@classmethod
def setUpClass(cls):
cls.name = 'foo'
# Handling async class set up
asyncio.run(cls.asyncSetUpClass())
@classmethod
async def asyncSetUpClass(cls):
cls.statement = await basic_async_func()
def test_set_up(self):
self.assertEqual(self.statement,'hello')
</code>
<code> async def basic_async_func(): await asyncio.sleep(2) return 'hello' class MyAsyncTestClass(unittest.IsolatedAsyncioTestCase): @classmethod def setUpClass(cls): cls.name = 'foo' # Handling async class set up asyncio.run(cls.asyncSetUpClass()) @classmethod async def asyncSetUpClass(cls): cls.statement = await basic_async_func() def test_set_up(self): self.assertEqual(self.statement,'hello') </code>

async def basic_async_func():
    await asyncio.sleep(2)
    return 'hello'

class MyAsyncTestClass(unittest.IsolatedAsyncioTestCase):

    @classmethod
    def setUpClass(cls):
        cls.name = 'foo'
        # Handling async class set up
        asyncio.run(cls.asyncSetUpClass())

    @classmethod
    async def asyncSetUpClass(cls):
        cls.statement = await basic_async_func()

    def test_set_up(self):
        self.assertEqual(self.statement,'hello')

I get the following output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>Traceback (most recent call last):
File "/home/main.py", line 151, in <module>
main()
File "/home/main.py", line 116, in main
test_result = runner.run(single_suite)
^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/lib/python3.12/unittest/runner.py", line 240, in run
test(result)
File "/usr/lib/python3.12/unittest/suite.py", line 84, in __call__
return self.run(*args, **kwds)
^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/lib/python3.12/unittest/suite.py", line 122, in run
test(result)
File "/usr/lib/python3.12/unittest/case.py", line 690, in __call__
return self.run(*args, **kwds)
^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/lib/python3.12/unittest/async_case.py", line 129, in run
self._setupAsyncioRunner()
File "/usr/lib/python3.12/unittest/async_case.py", line 120, in _setupAsyncioRunner
assert self._asyncioRunner is None, 'asyncio runner is already initialized'
^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: asyncio runner is already initialized
</code>
<code>Traceback (most recent call last): File "/home/main.py", line 151, in <module> main() File "/home/main.py", line 116, in main test_result = runner.run(single_suite) ^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/lib/python3.12/unittest/runner.py", line 240, in run test(result) File "/usr/lib/python3.12/unittest/suite.py", line 84, in __call__ return self.run(*args, **kwds) ^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/lib/python3.12/unittest/suite.py", line 122, in run test(result) File "/usr/lib/python3.12/unittest/case.py", line 690, in __call__ return self.run(*args, **kwds) ^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/lib/python3.12/unittest/async_case.py", line 129, in run self._setupAsyncioRunner() File "/usr/lib/python3.12/unittest/async_case.py", line 120, in _setupAsyncioRunner assert self._asyncioRunner is None, 'asyncio runner is already initialized' ^^^^^^^^^^^^^^^^^^^^^^^^^^^ AssertionError: asyncio runner is already initialized </code>
Traceback (most recent call last):
  File "/home/main.py", line 151, in <module>
    main()
  File "/home/main.py", line 116, in main
    test_result = runner.run(single_suite)
                  ^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.12/unittest/runner.py", line 240, in run
    test(result)
  File "/usr/lib/python3.12/unittest/suite.py", line 84, in __call__
    return self.run(*args, **kwds)
           ^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.12/unittest/suite.py", line 122, in run
    test(result)
  File "/usr/lib/python3.12/unittest/case.py", line 690, in __call__
    return self.run(*args, **kwds)
           ^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/lib/python3.12/unittest/async_case.py", line 129, in run
    self._setupAsyncioRunner()
  File "/usr/lib/python3.12/unittest/async_case.py", line 120, in _setupAsyncioRunner
    assert self._asyncioRunner is None, 'asyncio runner is already initialized'
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: asyncio runner is already initialized

I have tried a few different things to resolve this.

Firstly, I’d originally manually set an event loop:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>cls.loop = asyncio.new_event_loop()
asyncio.set_event_loop(cls.loop)
cls.loop.run_until_complete(cls.asyncSetUpClass())
</code>
<code>cls.loop = asyncio.new_event_loop() asyncio.set_event_loop(cls.loop) cls.loop.run_until_complete(cls.asyncSetUpClass()) </code>
cls.loop = asyncio.new_event_loop()
asyncio.set_event_loop(cls.loop)
cls.loop.run_until_complete(cls.asyncSetUpClass())

Secondly, I tried using the asyncio.runner context manager:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>with asyncio.Runner() as runner:
runner.run(cls.asyncSetUpClass())
</code>
<code>with asyncio.Runner() as runner: runner.run(cls.asyncSetUpClass()) </code>
with asyncio.Runner() as runner:
  runner.run(cls.asyncSetUpClass())

Lastly, I tried to remove the classSetUp method (though this has been a requirement of my actual, non-minimal test case), and to instead just use IsolatedAsyncioTestCase’s asyncSetUp function:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>async def asyncSetUp(self):
self.name = 'foo'
self.statement = await basic_async_func()
</code>
<code>async def asyncSetUp(self): self.name = 'foo' self.statement = await basic_async_func() </code>
async def asyncSetUp(self):
  self.name = 'foo'
  self.statement = await basic_async_func()

All of these have given the same error output as above. I am wondering if I need to somehow set or close an asyncio runner at the level of the loop in the first code block? (I tried re-initialising the unittest runner in every loop iteration and this didn’t work)

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật