Search code examples
pythonpython-requestsrequests-mock

Check query string on the request using requests_mock


How to check if a request mocked by requests_mock added some query parameters to a URL?

I have a function func thats do a HTTP POST on the url with some query string on the URL and I want to check if was called with this query string.

This is my attempt, but fails.

query is a empty string and qs is a empty dict.

I have sure that my func is appending the query string on the request.

with requests_mock.Mocker() as mock:
    mock.post(url, text=xml)

    func() # This function will call url + query string

    history = mock.request_history[0]

    assert history.method == "POST" # OK
    assert history.query is None # Returns an empty string, AssertionError: assert '' is None
    assert history.qs is None # Returns an empty dict, assert {} is None 

My func

def credilink():
    url = settings["url"]
    params = settings["params"]
    params["CC"] = query

    response = requests.post(url, params=params)
    # ...

Solution

  • I tried to reproduce your problem and was unable to...

    Here is the code I'm running:

    import requests
    import requests_mock
    
    url = "http://example.com"
    settings = dict(url=url, params=dict(a=1))
    query = "some-query"
    xml = "some-xml"
    
    
    def credilink():
        url = settings["url"]
        params = settings["params"]
        params["CC"] = query
    
        response = requests.post(url, params=params)
        return response.text
        # ...
    
    
    def test():
        with requests_mock.Mocker() as mock:
            mock.post(url, text=xml)
    
            data = credilink()  # This function will call url + query string
    
            history = mock.request_history[0]
    
            assert history.method == "POST"  # OK
            assert history.qs == dict(a=['1'], cc=[query])
            assert history.query == f"a=1&cc={query}"
            assert data == xml
    

    The assertions pass in this snippet. Maybe it's some version problem? I used requests==2.25.1 and requests-mock==1.8.0.