Fyzzys
Fyzzys

Reputation: 885

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

Upvotes: 1

Views: 3026

Answers (1)

Gabriel Cappelli
Gabriel Cappelli

Reputation: 4170

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.

Upvotes: 1

Related Questions