|
3 | 3 | from typing import List, Union
|
4 | 4 |
|
5 | 5 | import pytest
|
6 |
| -from ellar.common import File, Form, ModuleRouter, UploadFile, serialize_object |
| 6 | +from ellar.common import File, Form, ModuleRouter, UploadFile, post, serialize_object |
7 | 7 | from ellar.openapi import OpenAPIDocumentBuilder
|
8 | 8 | from ellar.testing import Test
|
9 | 9 | from starlette.formparsers import UploadFile as StarletteUploadFile
|
@@ -373,3 +373,55 @@ def test_multipart_multi_field_app_reads_body(tmpdir):
|
373 | 373 | "/multiple", data={"test1": "key pair"}, files=FORCE_MULTIPART
|
374 | 374 | )
|
375 | 375 | assert response.json() == {"test1": ["key pair"]}
|
| 376 | + |
| 377 | + |
| 378 | +def test_form_file_data_as_bytes(tmpdir): |
| 379 | + path = os.path.join(tmpdir, "test.txt") |
| 380 | + with open(path, "wb") as file: |
| 381 | + file.write(b"<file content>") |
| 382 | + |
| 383 | + @post("/form-bytes") |
| 384 | + async def form_file_as_bytes( |
| 385 | + ex_file: File[bytes], |
| 386 | + ): |
| 387 | + return { |
| 388 | + "file_size": len(ex_file), |
| 389 | + } |
| 390 | + |
| 391 | + new_tm = Test.create_test_module() |
| 392 | + new_tm.create_application().router.append(form_file_as_bytes) |
| 393 | + client = new_tm.get_test_client() |
| 394 | + |
| 395 | + with open(path, "rb") as f: |
| 396 | + response = client.post( |
| 397 | + "/form-bytes", files={"ex_file": ("test.txt", f, "text/plain")} |
| 398 | + ) |
| 399 | + assert response.json() == {"file_size": 14} |
| 400 | + |
| 401 | + |
| 402 | +def test_form_file_data_as_list_of_bytes(tmpdir): |
| 403 | + path = os.path.join(tmpdir, "test.txt") |
| 404 | + with open(path, "wb") as file: |
| 405 | + file.write(b"<file content>") |
| 406 | + |
| 407 | + @post("/form-bytes") |
| 408 | + async def form_file_as_bytes( |
| 409 | + ex_files: File[List[bytes]], |
| 410 | + ): |
| 411 | + return { |
| 412 | + "file_size": sum((len(ex_file) for ex_file in ex_files)), |
| 413 | + } |
| 414 | + |
| 415 | + new_tm = Test.create_test_module() |
| 416 | + new_tm.create_application().router.append(form_file_as_bytes) |
| 417 | + client = new_tm.get_test_client() |
| 418 | + |
| 419 | + with open(path, "rb") as f: |
| 420 | + response = client.post( |
| 421 | + "/form-bytes", |
| 422 | + files=[ |
| 423 | + ("ex_files", ("test.txt", f, "test/plain")), |
| 424 | + ("ex_files", ("test2.txt", f, "text/plain")), |
| 425 | + ], |
| 426 | + ) |
| 427 | + assert response.json() == {"file_size": 28} |
0 commit comments