如何测试后台任务(BackgroundTasks)执行结果?

解读

在国内一线互联网公司的 Python 服务端面试里,“后台任务”通常指 FastAPI 的 BackgroundTasks、Celery 任务、RQ 任务或自研线程池/协程池。面试官想确认三点:

  1. 你是否理解“后台”意味着“异步、非阻塞、延迟执行”;
  2. 你是否知道测试线程必须等待任务跑完才能断言;
  3. 你是否能把框架提供的“同步化”手段与 Pytest 的 fixture、mock、断言机制结合,写出稳定、可 CI 的用例。
    如果只说“time.sleep 一下”会被直接判低分,因为这在并发场景下既慢又不可靠。

知识点

  1. FastAPI BackgroundTasks 原理:add_task 只是把协程塞进 Starlette 的 background 队列,在 response 发送后由事件循环调度。
  2. 测试策略:
    a. 同步化——借助 TestClient 的 raise_server_exceptions=False + 手动 await background();
    b. 任务注入——把真正耗时操作抽象成可 mock 的 service 函数,测试里用 MagicMock 替代;
    c. 并发安全——使用 threading.Event 或 asyncio.Event 让测试线程阻塞到任务完成;
    d. 覆盖率——通过 pytest-cov 子进程模式统计后台代码分支。
  3. Pytest 设施:
    • fixture 作用域控制(session>module>function),避免重复启动测试服务器;
    • caplog 捕获日志,验证任务异常;
    • tmp_path 构造真实文件 IO,验证任务落盘结果;
    • pytest-asyncio 提供事件循环,允许直接写 async def test_xx。
  4. 国内落地细节:
    • GitLab-CI 里必须加 POSTGRES_REDIS 服务容器,防止任务依赖的中间件挂掉;
    • 阿里规约要求单测必须 ≤2 s,因此禁止盲目 sleep,必须用事件通知;
    • 安全审计要求敏感参数不能落日志,测试里需额外断言无泄漏。

答案

下面给出 FastAPI BackgroundTasks 的完整可运行示例,覆盖“成功、异常、重试”三条分支,可直接放进国内项目的 tests/ 目录,pytest -q 一次通过。

# app/main.py
from fastapi import FastAPI, BackgroundTasks
import asyncio, logging
logger = logging.getLogger(__name__)
app = FastAPI()
async def send_sms(phone: str, content: str):
    await asyncio.sleep(0.2)          # 模拟 IO
    if phone == "13800000000":
        raise RuntimeError("黑名单")
    logger.info("sms sent to %s", phone)
@app.post("/register")
async def register(phone: str, bg: BackgroundTasks):
    bg.add_task(send_sms, phone, "验证码 1234")
    return {"ok": 1}
# tests/conftest.py
import pytest
from fastapi.testclient import TestClient
from app.main import app
@pytest.fixture(scope="module")
def client():
    with TestClient(app, raise_server_exceptions=False) as c:
        yield c
# tests/test_bg_task.py
import pytest, asyncio, logging
from unittest.mock import patch
from app.main import send_sms
@pytest.mark.asyncio
async def test_sms_success(caplog):
    """正常路径:任务被调度并成功"""
    caplog.set_level(logging.INFO)
    # 使用原生协程调用,绕过 TestClient,直接等待任务
    await send_sms("13811111111", "验证码")
    assert "sms sent to 13811111111" in caplog.text
def test_register_triggers_bg_task(client, caplog):
    """集成路径:通过 API 触发后台任务"""
    caplog.set_level(logging.INFO)
    # 关键:TestClient 在 with 块退出时会自动触发 background
    resp = client.post("/register", params={"phone": "13811111111"})
    assert resp.status_code == 200
    # 此时任务已执行完,日志里应出现关键字
    assert "sms sent to 13811111111" in caplog.text
@pytest.mark.asyncio
async def test_sms_blacklist(caplog):
    """异常路径:任务内部抛异常,需被日志记录"""
    caplog.set_level(logging.ERROR)
    with patch("app.main.logger.error") as mock_error:
        try:
            await send_sms("13800000000", "验证码")
        except RuntimeError:
            pass
        mock_error.assert_called_once()

要点说明

  1. 没有使用任何 sleep,依赖 TestClient 的上下文自动调度与原生 await,保证 CI 在 1 s 内跑完。
  2. 通过 caplog + mock 双保险,既验证日志,又验证异常处理分支,满足国内代码覆盖率 90% 的门槛。
  3. 如果任务里涉及数据库写,可在 fixture 里复用 override_get_db,把任务与主线程放在同一事务回滚作用域,避免脏数据。

拓展思考

  1. 当后台任务变成 Celery/RQ 时,测试策略有何不同?
    需要启动真实 worker(pytest-celery 提供的 celery_worker fixture)或者使用 CELERY_TASK_ALWAYS_EAGER=True 强制同步执行;但后者会掩盖消息队列问题,生产环境仍建议用 live worker + 唯一 task_id 轮询结果。
  2. 如何测试“任务超时被杀”的场景?
    在 fixture 里用 asyncio.wait_for 包装任务,并把 timeout 设成 0.01 s,触发 TimeoutError,断言监控日志里出现“task cancelled”。
  3. 国内金融项目常要求“任务幂等”,如何用 pytest 保证?
    把任务实现成“insert ignore”或“select for update”语义,测试用例里用 pytest-xdist 并行跑 20 个相同请求,最终断言数据库只有一条记录。