示例工程 20-taskgroup-cancellation-contextvars
20-taskgroup-cancellation-contextvars/05-shield-cleanup/test_shield_cleanup.py
"""test_shield_cleanup.py"""
from __future__ import annotations
import asyncio
import pytest
from shield_cleanup import main, with_shield, without_shield
def test_cancelled_task_runs_cleanup() -> None:
assert asyncio.run(without_shield()) == ["cancelled"]
def test_shield_keeps_inner_running() -> None:
cleanup, result = asyncio.run(with_shield())
assert cleanup == ["outer-cancelled", "done"]
assert result == "critical"
def test_main_runs(capsys: pytest.CaptureFixture[str]) -> None:
asyncio.run(main())
out = capsys.readouterr().out
assert "without shield: ['cancelled']" in out
assert "with shield: ['outer-cancelled', 'done'] critical" in out