Fix: if/else scope in assert statements #240
Open
+25
−25
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There are some problematic cases in the tests. For example this code:
(see: https://github.com/laurentS/slowapi/blob/master/tests/test_fastapi_extension.py#L23)
means probably check if the status_code is 200 for the first 5 requests, but the following requests should have the status code 429 (too many requests). This looks right at the first glance, but sadly this is not true:
A statement like
assert x == 1 if False else "foobar"will be evaluated toassert "foobar", which is alwaysTrue. This means that checking for a response status code likeassert status_code == 200 if i < 5 else 429will be evaluated toassert status_code == 200fori < 5, but also toassert 429(which will be evaluated toTruein all circumstances) fori >= 5and notassert status_code == 429(which will really check for status code 429).The fix is to get the right scope for the if/else condition by using parentheses, so that the right response status code will be checked if
i >= 5.Luckily, the tests are still green. So there is no impact and the
status_codeis really429for all cases before and after the fix.Side note:
In cases like
assert response.headers.get("Retry-After") if i < 5 else Trueor similar I assume that theelse Truecase means simply skip the test after 5 requests by saying that the test is successful. A better understanding is imo given, if you're not using inline if/else statements and instead using constructs like this:or maybe even better to only iterate 5 times by doing
for i in range(0, 5):and skip the if part completely.But I would be happy if you accept my PR and do the proposed refactoring in another PR instead.