示例工程 18-asyncio-event-loop

18-asyncio-event-loop/03-to-thread-offload/test_to_thread_offload.py

python · 0.8 KB

"""test_to_thread_offload.py"""
 
from __future__ import annotations
 
import asyncio
 
import pytest
from to_thread_offload import blocking_io, main, offload
 
 
def test_blocking_io_returns_value() -> None:
    assert blocking_io(0.01) == "done"
 
 
def test_offload_runs_concurrently() -> None:
    async def run() -> float:
        import time
 
        started = time.perf_counter()
        results = await asyncio.gather(offload(0.05), offload(0.05), offload(0.05))
        assert results == ["done", "done", "done"]
        return time.perf_counter() - started
 
    assert asyncio.run(run()) < 0.12
 
 
def test_main_runs(capsys: pytest.CaptureFixture[str]) -> None:
    asyncio.run(main())
    out = capsys.readouterr().out
    assert "offloaded: ['done', 'done', 'done']" in out
    assert "threads_concurrent: True" in out