| 1 | from django.core.files.uploadedfile import SimpleUploadedFile |
| 2 | |
| 3 | from ninja import File, Form, NinjaAPI, UploadedFile |
| 4 | from ninja.testing import TestClient |
| 5 | |
| 6 | api = NinjaAPI() |
| 7 | |
| 8 | |
| 9 | @api.post("/str_and_file") |
| 10 | def str_and_file( |
| 11 | request, |
| 12 | title: str = Form(...), |
| 13 | description: str = Form(""), |
| 14 | file: UploadedFile = File(...), |
| 15 | ): |
| 16 | return {"title": title, "data": file.read().decode()} |
| 17 | |
| 18 | |
| 19 | client = TestClient(api) |
| 20 | |
| 21 | |
| 22 | def test_files(): |
| 23 | file = SimpleUploadedFile("test.txt", b"data123") |
| 24 | response = client.post( |
| 25 | "/str_and_file", |
| 26 | FILES={"file": file}, |
| 27 | POST={"title": "hello"}, |
| 28 | ) |
| 29 | assert response.status_code == 200 |
| 30 | assert response.json() == {"title": "hello", "data": "data123"} |
| 31 | |
| 32 | schema = api.get_openapi_schema()["paths"]["/api/str_and_file"] |
| 33 | r_body = schema["post"]["requestBody"] |
| 34 | |
| 35 | assert r_body == { |
| 36 | "content": { |
| 37 | "multipart/form-data": { |
| 38 | "schema": { |
| 39 | "title": "MultiPartBodyParams", |
| 40 | "type": "object", |
| 41 | "properties": { |
| 42 | "title": {"title": "Title", "type": "string"}, |
| 43 | "description": { |
| 44 | "title": "Description", |
| 45 | "default": "", |
| 46 | "type": "string", |
| 47 | }, |
| 48 | "file": { |
| 49 | "title": "File", |
| 50 | "type": "string", |
| 51 | "format": "binary", |
| 52 | }, |
| 53 | }, |
| 54 | "required": ["title", "file"], |
| 55 | } |
| 56 | } |
| 57 | }, |
| 58 | "required": True, |
| 59 | } |