|
4 | 4 | import typing |
5 | 5 | from contextlib import nullcontext as does_not_raise |
6 | 6 | from pathlib import Path |
| 7 | +from secrets import token_bytes |
7 | 8 |
|
8 | 9 | import pytest |
9 | 10 |
|
@@ -127,6 +128,14 @@ async def app(scope: Scope, receive: Receive, send: Send) -> None: |
127 | 128 | return app |
128 | 129 |
|
129 | 130 |
|
| 131 | +def make_app_max_file_size(max_file_size: int) -> ASGIApp: |
| 132 | + async def app(scope: Scope, receive: Receive, send: Send) -> None: |
| 133 | + request = Request(scope, receive) |
| 134 | + await request.form(max_file_size=max_file_size) |
| 135 | + |
| 136 | + return app |
| 137 | + |
| 138 | + |
130 | 139 | def test_multipart_request_data(tmpdir: Path, test_client_factory: TestClientFactory) -> None: |
131 | 140 | client = test_client_factory(app) |
132 | 141 | response = client.post("/", data={"some": "data"}, files=FORCE_MULTIPART) |
@@ -580,6 +589,30 @@ def test_too_many_files_and_fields_raise( |
580 | 589 | assert res.text == "Too many files. Maximum number of files is 1000." |
581 | 590 |
|
582 | 591 |
|
| 592 | +@pytest.mark.parametrize( |
| 593 | + "app,expectation", |
| 594 | + [ |
| 595 | + (make_app_max_file_size(1024), pytest.raises(MultiPartException)), |
| 596 | + (Starlette(routes=[Mount("/", app=make_app_max_file_size(1024))]), does_not_raise()), |
| 597 | + ], |
| 598 | +) |
| 599 | +def test_max_part_file_size_raise( |
| 600 | + tmpdir: Path, |
| 601 | + app: ASGIApp, |
| 602 | + expectation: typing.ContextManager[Exception], |
| 603 | + test_client_factory: TestClientFactory, |
| 604 | +) -> None: |
| 605 | + path = os.path.join(tmpdir, "test.txt") |
| 606 | + with open(path, "wb") as file: |
| 607 | + file.write(token_bytes(1024 + 1)) |
| 608 | + |
| 609 | + client = test_client_factory(app) |
| 610 | + with open(path, "rb") as f, expectation: |
| 611 | + response = client.post("/", files={"test": f}) |
| 612 | + assert response.status_code == 400 |
| 613 | + assert response.text == "File exceeds maximum size of 1024 bytes." |
| 614 | + |
| 615 | + |
583 | 616 | @pytest.mark.parametrize( |
584 | 617 | "app,expectation", |
585 | 618 | [ |
|
0 commit comments