Using Pytest and Request-Mock to mock API calls

--

This fixture creates an object with the same structure as an API response object. Here we’re using requests_mock.get to pass in the parameters we want (there are more options besides for url, json and status_code) and return the response object.

This is a usage example. The fixture mock_response is passed in to the test function. We patch called_function (which would otherwise attempt to call the API) and set the mock_response as its return value.

Now, after calling outer_function we can confirm that it returns the response object it receives from called_function, comparing headers and json or whatever needs to be checked.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Half of a Glazier
Half of a Glazier

Written by Half of a Glazier

Software engineer and general messer-arounder. And coffee drinker. Coffee’s important.

No responses yet

Write a response