我想问关于处理来自IsolatedAsyncioTestCase的 asyncio.CancelledError 的问题,它是为在 py3.8 上测试 asyncio 而提供的
给定以下测试用例
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()
它被tearDown吸了
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的源代码后,这些是与此错误相关的代码。
- https://github.com/python/cpython/blob/7264e92b718d307cc499b2f10eab7644b00f0499/Lib/unittest/async_case.py#L126
- https://github.com/python/cpython/blob/7264e92b718d307cc499b2f10eab7644b00f0499/Lib/unittest/async_case.py#L105
错误asyncio.CancelledError已被选择性地引发,但没有其他异常。所以,我想知道如何捕捉和处理这个错误,而不是挂在终端上。