Skip to content

Commit 3cd3104

Browse files
committed
add test for file upload via form
1 parent 241b10b commit 3cd3104

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

requirements/test-env.txt

+3
Original file line numberDiff line numberDiff line change
@@ -9,3 +9,6 @@ playwright
99

1010
# I'm not quite sure why this needs to be installed for tests with Sanic to pass
1111
sanic-testing
12+
13+
# required to test uploading form data with starlette
14+
python-multipart

tests/test_client.py

+52
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,17 @@
11
import asyncio
22
from contextlib import AsyncExitStack
33
from pathlib import Path
4+
from tempfile import NamedTemporaryFile
45

56
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
611

712
import idom
13+
from idom import html
14+
from idom.backend import starlette as starlette_backend
815
from idom.backend.utils import find_available_port
916
from idom.testing import BackendFixture, DisplayFixture
1017
from tests.tooling.common import DEFAULT_TYPE_DELAY
@@ -125,3 +132,48 @@ async def handle_change(event):
125132
await inp.type("hello", delay=DEFAULT_TYPE_DELAY)
126133

127134
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

Comments
 (0)