prof-rossetti / intro-to-python

An Introduction to Programming in Python
Other
97 stars 244 forks source link

Requests Mock #103

Closed s2t2 closed 2 years ago

s2t2 commented 2 years ago

References

In the wild:

Example:


    # FUNCTION YOU WANT TO TEST (APP)

    def fetch_data():
        request_url = ""
        return json.loads(requests.get(request_url).text)

    # MOCKING THE REQUEST (TEST)

    import requests_mock

    with requests_mock.mock() as mock:
        request_url = "" # same request url used by the fetch data function
        mock_data = {"message": "HELLO"} # the data we will return instead of making a request for real
        mock.get(request_url, json=mock_data)

        results = fetch_data() # a request is never made, but we get the mock data back
        assert results["message"] == "HELLO"