简体   繁体   中英

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

I am trying to make a unit test that checks whether the method of the desired FastAPI endpoint was called. Made mock.spy and during testing outputs an error that the method was called 0 times. Although the output even has a verification text from the endpoint method.How do I fix this?

My unit test:

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()

My endpoint code in main.py:

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

What's happening is that the app.get decorator is getting the actual object of your function and storing it internally in your FastAPI app.

When you mock best_authors it won't matter to FastAPI, since it'll use the object it had stored previously.

Honestly, I wouldn't test it this way. I would have a unit test where I test the behaviour of best_authors .

Which in this case would be mocking requests.get and making sure it was called and that the result was returned properly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM