You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pyodide中使用IsolatedAsyncioTestCase执行异步单元测试报错求助

Pyodide中异步单元测试报错的解决方法

问题原因

Pyodide运行在浏览器的JavaScript事件循环之上,Python的IsolatedAsyncioTestCase默认会为每个测试创建新的asyncio事件循环,而Pyodide仅允许使用一个与JS事件循环集成的全局asyncio循环,两者冲突导致报错。

解决办法

办法一:重写IsolatedAsyncioTestCase的循环初始化逻辑

修改测试类,复用Pyodide的现有事件循环,而不是创建新循环:

from unittest import IsolatedAsyncioTestCase
import asyncio

class TestClass(IsolatedAsyncioTestCase):
    def _setupAsyncioLoop(self):
        # 重写方法,使用Pyodide全局事件循环
        self._asyncio_loop = asyncio.get_event_loop()
        self._asyncio_loop.set_debug(False)

    async def test_case_one(self):
        print('hello')
        result = await functionality()
        self.assertEqual(expected, result)

办法二:改用普通TestCase,手动执行异步逻辑

放弃IsolatedAsyncioTestCase,在普通测试方法中用asyncio.run()调用异步函数:

import unittest
import asyncio

class TestClass(unittest.TestCase):
    def test_case_one(self):
        print('hello')
        result = asyncio.run(functionality())
        self.assertEqual(expected, result)

运行测试

保持原有的测试运行代码即可:

import unittest

runner = unittest.TextTestRunner()
result = runner.run(unittest.makeSuite(TestClass))

内容的提问来源于stack exchange,提问作者whiteBear22

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 19:54:39