如何在 FastAPI 中测试客户端调用端点的正确方法?

How to test in FastAPI that client calls correct method of endpoint?

我正在尝试进行单元测试以检查是否调用了所需 FastAPI 端点的方法。制作 mock.spy 并在测试期间输出错误,该方法被调用 0 次。虽然输出甚至有来自端点的验证文本 method.How 我要解决这个问题吗?

我的单元测试:

client = TestClient(main.app)

pytestmark = pytest.mark.unit

@pytest.mark.unit
    def test_get_best_authors(mocker: MockFixture):
        mocker.spy(main, 'best_authors')
        client.get('/luchshie-avtori').json()
        assert main.best_authors.assert_called_once()

我在main.py中的端点代码:

@app.get("/luchshie-avtori")
async def best_authors():
    print('test ping')
    return requests.get('', params={'return': 'json'}).json()

发生的事情是 app.get 装饰器正在获取函数的实际对象并将其存储在 FastAPI 应用程序内部。

当您模拟 best_authors 时,这对 FastAPI 无关紧要,因为它将使用它之前存储的对象。

老实说,我不会这样测试的。我会进行单元测试,测试 best_authors.

的行为

在这种情况下,这将是模拟 requests.get 并确保它被调用并正确返回结果。