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

test case for dynamic rate limit added #66

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions docs/examples.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,20 @@ The tests show a lot of different use cases that are not all covered here.
return PlainTextResponse("I'm unlimited")
```

## Dynamically change the rate limit

```python
def dynamic_limit():
# do anything you want here
return "1/minute"

@app.route("/homepage")
@limiter.limit(dynamic_limit)
async def homepage(request: Request):
return PlainTextResponse("test")
```


## Disable the limiter entirely

You might want to disable the limiter, for instance for testing, etc...
Expand Down
50 changes: 50 additions & 0 deletions tests/test_fastapi_extension.py
Original file line number Diff line number Diff line change
Expand Up @@ -264,3 +264,53 @@ def t3(request: Request):
for i in range(0, 10):
response = client.get("/t3")
assert response.status_code == 200

def test_rate_limit_at_app_level(self):
app, limiter = self.build_fastapi_app(key_func=get_ipaddr, application_limits=["5/minute"])

@app.get("/t1")
async def t1(request: Request):
return PlainTextResponse("test")

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

def test_dynamic_rate_limit(self):

RATE_LIMIT = "5/minute"

def get_rate_limit() -> str:
return RATE_LIMIT

app, limiter = self.build_fastapi_app(key_func=get_ipaddr)

@app.get("/t1")
@limiter.limit(get_rate_limit)
async def t1(request: Request):
return PlainTextResponse("test")

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

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

def test_single_decorator_for_exempt(self):
app, limiter = self.build_fastapi_app(key_func=get_ipaddr, application_limits=["10/minute"])

@app.get("/t1")
@limiter.limit('exempt')
async def t1(request: Request):
return PlainTextResponse("test")

client = TestClient(app)

for i in range(0, 20):
response = client.get("/t1")
assert response.status_code == 200