Skip to content

Conversation

@colidyre
Copy link

@colidyre colidyre commented Aug 24, 2025

There are some problematic cases in the tests. For example this code:

for i in range(0, 10):
    response = client.get("/t1")
    assert response.status_code == 200 if i < 5 else 429

(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 to assert "foobar", which is always True. This means that checking for a response status code like assert status_code == 200 if i < 5 else 429 will be evaluated to assert status_code == 200 for i < 5, but also to assert 429 (which will be evaluated to True in all circumstances) for i >= 5 and not assert 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_code is really 429 for all cases before and after the fix.

Side note:

In cases like assert response.headers.get("Retry-After") if i < 5 else True or similar I assume that the else True case 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:

for i in range(0,10):
    response = client.get("/t1")
    if i < 5:
        assert ...

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.

@colidyre colidyre changed the title Fix if/else scope in assert statements Fix: if/else scope in assert statements Aug 24, 2025
A statement like `assert x == 1 if False else "foobar"` will
be evaluated to assert "foobar", which is always True. This
means that checking for a response status code like
`assert status_code == 200 if i < 5 else 429` will be evaluated
to `assert status_code == 200` for i < 5, but also to
`assert 429` for i >= 5 and not `assert 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.
@colidyre colidyre force-pushed the fix_if_constraints_in_tests branch from c41ad61 to 88befd0 Compare August 24, 2025 11:41
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

Successfully merging this pull request may close these issues.

1 participant