嘲笑background_tasks.add_task

问题描述 投票:0回答:1

我想模拟'background_tasks.add_task',这样我就可以监视它的调用。但是,我不知道如何才能访问它。任何帮助,将不胜感激。

python fastapi
1个回答
0
投票

这是一个可行的例子。创建两个文件:

main.py

from fastapi import FastAPI, BackgroundTasks

app = FastAPI()

def write_notification(email: str, message=""):
    with open("log.txt", mode="w") as email_file:
        content = f"notification for {email}: {message}"
        email_file.write(content)


@app.post("/send-notification/{email}")
async def send_notification(email: str, background_tasks: BackgroundTasks):
    background_tasks.add_task(write_notification, email, message="some notification")
    return {"message": "Notification sent in the background"}

test_main.py

import pytest
from fastapi.testclient import TestClient
from fastapi import BackgroundTasks
from requests import Response

from main import app, write_notification
from unittest.mock import mock_open


@pytest.fixture
def client():
    return TestClient(app)


def test_send_notification(
    client, mocker,
):
    mock_file_open = mocker.patch(
        "main.open", new=mock_open()
    )  # https://docs.python.org/3/library/unittest.mock.html#mock-open
    spy = mocker.spy(BackgroundTasks, "add_task")

    r: Response = client.post("/send-notification/[email protected]")

    # validate the HTTP response
    assert r.status_code == 200
    assert r.json() == {"message": "Notification sent in the background"}

    # validate the add_task call was made
    spy.assert_called_with(
        mocker.ANY,  # add_task() is a method, and as such its first argument is `self`
        write_notification,
        "[email protected]",
        message="some notification",
    )

    # validate the background task did its job
    assert mocker.call("log.txt", mode="w") in mock_file_open.call_args_list
    handle = mock_file_open()
    handle.write.assert_called_once_with(
        "notification for [email protected]: some notification"
    )

并安装以下依赖项:

pip install fastapi==0.53.0 pytest==5.4.1 pytest-mock==2.0.0 requests==2.23.0

最终运行pytest命令:

pytest test_main.py

说明

  • mocker固定装置来自pytest-mock,在使用pytest时非常方便进行模拟/间谍。
  • spy = mocker.spy(BackgroundTasks, "add_task")是您要寻找的。

您可以克隆this要点进行尝试。

© www.soinside.com 2019 - 2024. All rights reserved.