|
| 1 | +import pytest |
| 2 | +from aiohttp import web |
| 3 | +from pydantic import BaseModel |
| 4 | + |
| 5 | +from aiohttp_deps import Depends, Form |
| 6 | +from tests.conftest import ClientGenerator |
| 7 | + |
| 8 | + |
| 9 | +class InputSchema(BaseModel): |
| 10 | + id: int |
| 11 | + file: web.FileField |
| 12 | + |
| 13 | + class Config: |
| 14 | + arbitrary_types_allowed = True |
| 15 | + |
| 16 | + |
| 17 | +@pytest.mark.anyio |
| 18 | +async def test_form_dependency( |
| 19 | + my_app: web.Application, |
| 20 | + aiohttp_client: ClientGenerator, |
| 21 | +): |
| 22 | + async def handler(my_form: InputSchema = Depends(Form())): |
| 23 | + return web.Response(body=my_form.file.file.read()) |
| 24 | + |
| 25 | + my_app.router.add_post("/", handler) |
| 26 | + |
| 27 | + file_data = b"bytes" |
| 28 | + client = await aiohttp_client(my_app) |
| 29 | + resp = await client.post( |
| 30 | + "/", |
| 31 | + data={"id": "1", "file": b"bytes"}, |
| 32 | + ) |
| 33 | + assert resp.status == 200 |
| 34 | + assert await resp.content.read() == file_data |
| 35 | + |
| 36 | + |
| 37 | +@pytest.mark.anyio |
| 38 | +async def test_form_empty( |
| 39 | + my_app: web.Application, |
| 40 | + aiohttp_client: ClientGenerator, |
| 41 | +): |
| 42 | + async def handler(_: InputSchema = Depends(Form())): |
| 43 | + """Nothing.""" |
| 44 | + |
| 45 | + my_app.router.add_post("/", handler) |
| 46 | + |
| 47 | + client = await aiohttp_client(my_app) |
| 48 | + resp = await client.post( |
| 49 | + "/", |
| 50 | + ) |
| 51 | + assert resp.status == 400 |
| 52 | + |
| 53 | + |
| 54 | +@pytest.mark.anyio |
| 55 | +async def test_form_incorrect_data( |
| 56 | + my_app: web.Application, |
| 57 | + aiohttp_client: ClientGenerator, |
| 58 | +): |
| 59 | + async def handler(_: InputSchema = Depends(Form())): |
| 60 | + """Nothing.""" |
| 61 | + |
| 62 | + my_app.router.add_post("/", handler) |
| 63 | + |
| 64 | + client = await aiohttp_client(my_app) |
| 65 | + resp = await client.post("/", data={"id": "meme", "file": b""}) |
| 66 | + assert resp.status == 400 |
| 67 | + |
| 68 | + |
| 69 | +@pytest.mark.anyio |
| 70 | +async def test_form_untyped( |
| 71 | + my_app: web.Application, |
| 72 | + aiohttp_client: ClientGenerator, |
| 73 | +): |
| 74 | + async def handler(form=Depends(Form())): |
| 75 | + return web.Response(body=form["file"].file.read()) |
| 76 | + |
| 77 | + my_app.router.add_post("/", handler) |
| 78 | + |
| 79 | + form_data = b"meme" |
| 80 | + client = await aiohttp_client(my_app) |
| 81 | + resp = await client.post("/", data={"id": "meme", "file": form_data}) |
| 82 | + assert resp.status == 200 |
| 83 | + assert await resp.content.read() == form_data |
0 commit comments