|
1 | 1 | import asyncio
|
2 | 2 | from contextlib import AsyncExitStack
|
3 | 3 | from pathlib import Path
|
| 4 | +from tempfile import NamedTemporaryFile |
4 | 5 |
|
5 | 6 | from playwright.async_api import Browser
|
| 7 | +from starlette.applications import Starlette |
| 8 | +from starlette.datastructures import UploadFile |
| 9 | +from starlette.requests import Request |
| 10 | +from starlette.responses import Response |
6 | 11 |
|
7 | 12 | import idom
|
| 13 | +from idom import html |
| 14 | +from idom.backend import starlette as starlette_backend |
8 | 15 | from idom.backend.utils import find_available_port
|
9 | 16 | from idom.testing import BackendFixture, DisplayFixture
|
10 | 17 | from tests.tooling.common import DEFAULT_TYPE_DELAY
|
@@ -125,3 +132,48 @@ async def handle_change(event):
|
125 | 132 | await inp.type("hello", delay=DEFAULT_TYPE_DELAY)
|
126 | 133 |
|
127 | 134 | assert (await inp.evaluate("node => node.value")) == "hello"
|
| 135 | + |
| 136 | + |
| 137 | +async def test_form_upload_file(page): |
| 138 | + file_content = asyncio.Future() |
| 139 | + |
| 140 | + async def handle_file_upload(request: Request) -> Response: |
| 141 | + form = await request.form() |
| 142 | + file: UploadFile = form.get("file") |
| 143 | + file_content.set_result((await file.read()).decode("utf-8")) |
| 144 | + return Response() |
| 145 | + |
| 146 | + app = Starlette() |
| 147 | + app.add_route("/file-upload", handle_file_upload, methods=["POST"]) |
| 148 | + |
| 149 | + @idom.component |
| 150 | + def CheckUploadFile(): |
| 151 | + return html.form( |
| 152 | + { |
| 153 | + "enctype": "multipart/form-data", |
| 154 | + "action": "/file-upload", |
| 155 | + "method": "POST", |
| 156 | + }, |
| 157 | + html.input({"type": "file", "name": "file", "id": "file-input"}), |
| 158 | + html.input({"type": "submit", "id": "form-submit"}), |
| 159 | + ) |
| 160 | + |
| 161 | + async with AsyncExitStack() as es: |
| 162 | + file = Path(es.enter_context(NamedTemporaryFile()).name) |
| 163 | + |
| 164 | + expected_file_content = "Hello, World!" |
| 165 | + file.write_text(expected_file_content) |
| 166 | + |
| 167 | + server = await es.enter_async_context( |
| 168 | + BackendFixture(app=app, implementation=starlette_backend) |
| 169 | + ) |
| 170 | + display = await es.enter_async_context(DisplayFixture(server, driver=page)) |
| 171 | + |
| 172 | + await display.show(CheckUploadFile) |
| 173 | + |
| 174 | + file_input = await display.page.wait_for_selector("#file-input") |
| 175 | + await file_input.set_input_files(file) |
| 176 | + |
| 177 | + await (await display.page.wait_for_selector("#form-submit")).click() |
| 178 | + |
| 179 | + assert (await asyncio.wait_for(file_content, 5)) == expected_file_content |
0 commit comments