Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ability to simulate HTTP response latency #155

Closed
lachlan-eagling opened this issue Jan 14, 2021 · 2 comments
Closed

Ability to simulate HTTP response latency #155

lachlan-eagling opened this issue Jan 14, 2021 · 2 comments

Comments

@lachlan-eagling
Copy link

Hi @jamielennox,

Is there currently anyway to simulate latency on a mocked http response with requests-mock? I am trying to implement some unit tests for request timeouts but having some difficulty in mocking/simulating request latency.

Would be happy to work on this and open a PR if it was something you were open to having added, I was thinking it would be cool to have an additional kwarg for register_uri.

Example:

with self.assertRaises(requests.exceptions.Timeout), requests_mock.Mocker() as m:
    # Simulate a 500ms delay on HTTP response.
    m.register_uri("GET", "https://httpbin.org/get", text="foo", latency=500)
    requests.get("https://httpbin.org/get")
    ...
@jamielennox
Copy link
Owner

Kind of, though in the unit test you've used as an example it's not going to show much.

basically just do:

   m.get('https://httpbin.org/get', exc=requests.Timeout) 

and then your code should ensure that it's doing the right thing on exception handling rather than try and actually time things out.

@jamielennox
Copy link
Owner

Was just looking through old tickets and I still think this is a bad idea to do in unit testing, so probably not something i want to add to the library. However if you (or future people reading this bug) are absolutely convinced you want to do this it's pretty easy to do manually.

import time

import requests
import requests_mock

def delayed_response(timeout, **kwargs):
    time.sleep(timeout)
    return kwargs

with requests_mock.mock() as m:
    m.get("https://httpbin.org/get", **delayed_response(5, text="foo"))
    requests.get("https://httpbin.org/get")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants