Pass a list of Callable or a Generator to side_effect
See original GitHub issueI’m migrating from requests-mock. I have a mock that is supposed to return first a response with a delay, then the same response but instantly.
Using requests-mock, I had achieved with a list of response containing a callable :
def license_file_with_delay(request):
sleep(0.5)
return license_file_with_1_random_license_and_1_eval(request)
def test_should_mock_with_delay_first(requests-mock):
requests-mock.post("https://mocked-api/", [
{"json": license_file_with_delay},
{"json": license_file_with_1_random_license_and_1_eval},
])
I don’t find an easy way to achieve this using respx. I think a good way would be with a generator.
def return_values(request):
yield httpx.Response(200, json=license_file_with_delay),
while True:
yield httpx.Response(200, json=license_file_with_1_random_license_and_1_eval)
respx_mock.post("https://mocked-wallix-api/api/license/").mock(side_effect=return_values)
A generator would also allow to mimic the requests-mock behavior of always returning the last response of the list if the list is exhausted. Would it make sense to include this behavior ?
Issue Analytics
- State:
- Created 2 years ago
- Comments:5 (3 by maintainers)
Top Results From Across the Web
typing — Support for type hints — Python 3.11.1 documentation
Callable type; Callable[[int], str] is a function of (int) -> str. The subscription syntax must always be used with exactly two values: the...
Read more >Mock side effect only X number of times - Stack Overflow
Using mock's side_effect, I can fail it for a set number of executions and then passing None , clear the side effect. However,...
Read more >Functions - Python in a Nutshell [Book] - O'Reilly
In this example, f does mutate the list object that the caller passes to f as the second argument by calling the object's...
Read more >Callable generators (PEP 288: Generator Attributes, again) - Python
generators from outside (although it looks like it might be convenient in some cases), but being able to pass names into generators is...
Read more >How to Get the First Match From a Python List or Iterable
The simplest case is that you need to confirm that a particular item exists in the iterable. For example, you want to find...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
@AltarBeastiful #158 is now merged
Yeah, I think it’s a nice feature to add the
route
to the side effect kwargs…will look into it in the future.Currently though, my first suggestion is a fully working example using RESPX without any “hacks” 😉