如何使用 python 3.8 unittest IsolatedAsyncioTestCase 处理 CancelledError

How to handle CancelledError with python 3.8 unittest IsolatedAsyncioTestCase

我想问一下 IsolatedAsyncioTestCase 中处理 asyncio.CancelledError 的问题,它是为在 py3.8

上测试异步而提供的

给定以下测试用例

import unittest
from unittest import IsolatedAsyncioTestCase
import asyncio


class Test(IsolatedAsyncioTestCase):
    def setUp(self):
        print('setup')

    async def asyncSetUp(self):
        print('async setup')

    async def test_response(self):
        print('test_response')
        self.addAsyncCleanup(self.on_cleanup)

    def tearDown(self):
        print('teardown')

    async def asyncTearDown(self):
        print('before async teardown')
        fut = asyncio.Future()
        fut.cancel()
        await fut
        print('after async teardown')

    async def on_cleanup(self):
        print('clean up')


if __name__ == "__main__":
    unittest.main()

它在拆解时被吸了

root@1318a3fe59d0:/# python --version
Python 3.8.0
root@1318a3fe59d0:/# python /workspace/b.py 
setup
async setup
test_response
before async teardown
....

深入研究错误堆栈(通过按 CTRL+C 终止进程)和来自 github 的源代码后,这些是与此错误相关的代码。

错误 asyncio.CancelledError 已被有选择地引发,但没有引发其他异常。所以,我想知道如何捕捉和处理这个错误,而不是挂在终端上。

最近,我从python的票务系统中找到了一个similar issue

希望它已于 2020-12-16 得到解决。此外,通过 checking what they modified 在 3.8 分支中,他们改变了捕获异常的方式。

因此,只要您有最新的 python,其中包含此修复程序,您就不会再遇到此问题。