1

I am using requests-mock and I am trying to figure out how to assert that the put request has been called correctly:


def funtion_to_be_tested():
    requests.put(
        headers={'X-API-Key': 'api_key'},
        url=url,
        params={'param1': 'foo'},
        data='This is the data'
    )


def test_upload(requests_mock):
    url = 'http://example.com/upload'
    requests_mock.put(url, text='ok')
    funtion_to_be_tested()
    # how to check that `data` was `This is the data` and that `headers` contained the `X-API-Key`?

Edit: I refactored out the code to be tested to a function called funtion_to_be_tested

Michael_Scharf
  • 33,154
  • 22
  • 74
  • 95

2 Answers2

1

The standard way to do this is run through your function and then make assertions on the request_history:

Altering the example because it always takes me a while to make pytest work correctly, but it will work basically the same way:

import requests
import requests_mock

def funtion_to_be_tested():
    requests.put(
        headers={'X-API-Key': 'api_key'},
        url=url,
        params={'param1': 'foo'},
        data='This is the data'
    )

with requests_mock.mock() as m:
    url = 'http://example.com/upload'
    m.put(url, text='ok')
    funtion_to_be_tested()

    assert m.last_request.headers['X-API-Key'] == 'api_key'
    assert m.last_request.text == 'This is the data'
jamielennox
  • 368
  • 1
  • 2
  • 9
  • I solved it similarly but used the Matcher object directly, e.g. `matcher = m.put(url, text='ok'); assert matcher.last_request.text == ...` this was so I could check individual mocked endpoints rather than the full history. not sure your thoughts on that – user10000000 Mar 08 '23 at 17:03
0

If you just want check the method being used, you can check that by verifying the sent request.

def test_upload(requests_mock: Any):
    url = 'http://example.com/upload'
    requests_mock.put(url, text='ok')
    r = requests.put(
        headers={'X-API-Key': 'api_key'},
        url=url,
        params={'param1': 'foo'},
        data='This is the data'
    )
    print(r.request.method)  # Prints PUT/POST 
    print(r.request.headers) # Prints your headers sent
    print(r.request.body)    # Prints your data sent

I have included the request headers/body in the code above in case you want to check the other parameters as well.

isopach
  • 1,783
  • 7
  • 31
  • 43
  • Thank you for your answer. My question was probably not clear enough what I want to test. I what to test if the API was called with the correct data. The handling of the request is done within the code to be tested and I have no access to the return value of `request.put`. – Michael_Scharf Feb 16 '20 at 16:17