在异步任务中,如何处理和测试取消操作(cancellation)?请给出一个完整的测试用例。

在异步任务中,处理和测试取消操作通常涉及使用 asyncio 提供的取消机制。以下是一个完整的测试用例,展示了如何启动异步任务、取消它,并验证取消操作的正确行为。

import asyncio
import pytest

async def long_running_task():
    try:
        print("Task started")
        await asyncio.sleep(10)  # 模拟长时间运行的任务
        print("Task completed")
        return "Task completed successfully"
    except asyncio.CancelledError:
        print("Task was cancelled")
        raise

@pytest.mark.asyncio
async def test_cancellation():
    # 创建任务
    task = asyncio.create_task(long_running_task())
    
    # 等待一小段时间以确保任务已经开始
    await asyncio.sleep(0.1)
    
    # 取消任务
    task.cancel()
    
    # 验证任务是否被取消
    with pytest.raises(asyncio.CancelledError):
        await task
    
    # 验证任务是否正确地处理了取消
    assert task.cancelled()
    assert task.done()
    print("Test passed: Task was cancelled successfully")

详细说明

  1. 异步任务定义

    • long_running_task 是一个模拟的长时间运行的任务,内部使用 await asyncio.sleep(10) 模拟耗时操作。
    • 在任务中捕获 asyncio.CancelledError 异常,确保任务在被取消时能够正确清理资源或执行其他必要的操作。
  2. 测试逻辑

    • 在测试函数 test_cancellation 中,首先创建并启动任务 long_running_task。
    • 使用 await asyncio.sleep(0.1) 确保任务已经开始执行。
    • 调用 task.cancel() 方法取消任务。
    • 使用 with pytest.raises(asyncio.CancelledError): 捕获并验证任务是否抛出了取消异常。
    • 通过 task.cancelled() 和 task.done() 进一步验证任务状态。
  3. 运行测试

    • 确保安装了 pytest 和 pytest-asyncio 插件:
      pip install pytest pytest-asyncio
      
    • 运行测试文件:
      pytest test_file.py -v
      
  4. 预期输出

    • 测试通过,且日志显示任务被成功取消。

注意事项

  • 资源清理:如果任务中打开了文件或网络连接等资源,应在捕获 CancelledError 后及时清理。
  • 任务状态检查:在测试中验证 cancelled() 和 done() 可以确保任务状态符合预期。
  • 异步测试环境:使用 pytest-asyncio 插件可以方便地编写异步测试用例。

通过这种方式,可以有效地测试异步任务的取消操作,确保任务在取消时行为符合预期。