2

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)
    # ...
Rodrigo
  • 135
  • 4
  • 45
  • 107
  • 1
    Could you provide a more complete example? I'm having some trouble understanding how you are using this. A single file script demonstrating the observed behavior and a comment about the expected behavior would be ideal. – Dalton Pearson Apr 09 '21 at 14:36

2 Answers2

4

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.

Blop
  • 473
  • 2
  • 6
4

In my case, the problem was in mock:// URL schema, as it's present in the requests-mock samples

session.get('mock://test.com/path')

But requests library skips query arguments for non "http" URLs. Here is the comment from the source code

# Don't do any URL preparation for non-HTTP schemes like `mailto`,
# `data` etc to work around exceptions from `url_parse`, which
# handles RFC 3986 only.
if ':' in url and not url.lower().startswith('http'):
    self.url = url
    return
Serhii Kostel
  • 176
  • 1
  • 3