How to use test_should_accept_single_file method in Playwright Python

Best Python code snippet using playwright-python

Run Playwright Python automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

test_input.py

Source: test_input.py Github

copy
1# Copyright (c) Microsoft Corporation.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15import asyncio
16import os
17
18import pytest
19
20from playwright._impl._path_utils import get_file_dirname
21from playwright.async_api import Page
22
23_dirname = get_file_dirname()
24FILE_TO_UPLOAD = _dirname / ".." / "assets/file-to-upload.txt"
25
26
27async def test_should_upload_the_file(page, server):
28    await page.goto(server.PREFIX + "/input/fileupload.html")
29    file_path = os.path.relpath(FILE_TO_UPLOAD, os.getcwd())
30    input = await page.query_selector("input")
31    await input.set_input_files(file_path)
32    assert await page.evaluate("e => e.files[0].name", input) == "file-to-upload.txt"
33    assert (
34        await page.evaluate(
35            """e => {
36        reader = new FileReader()
37        promise = new Promise(fulfill => reader.onload = fulfill)
38        reader.readAsText(e.files[0])
39        return promise.then(() => reader.result)
40    }""",
41            input,
42        )
43        == "contents of the file\n"
44    )
45
46
47async def test_should_work(page, assetdir):
48    await page.set_content("<input type=file>")
49    await page.set_input_files("input", assetdir / "file-to-upload.txt")
50    assert await page.eval_on_selector("input", "input => input.files.length") == 1
51    assert (
52        await page.eval_on_selector("input", "input => input.files[0].name")
53        == "file-to-upload.txt"
54    )
55
56
57async def test_should_set_from_memory(page):
58    await page.set_content("<input type=file>")
59    await page.set_input_files(
60        "input",
61        files=[
62            {"name": "test.txt", "mimeType": "text/plain", "buffer": b"this is a test"}
63        ],
64    )
65    assert await page.eval_on_selector("input", "input => input.files.length") == 1
66    assert (
67        await page.eval_on_selector("input", "input => input.files[0].name")
68        == "test.txt"
69    )
70
71
72async def test_should_emit_event(page: Page):
73    await page.set_content("<input type=file>")
74    fc_done: asyncio.Future = asyncio.Future()
75    page.once("filechooser", lambda file_chooser: fc_done.set_result(file_chooser))
76    await page.click("input")
77    file_chooser = await fc_done
78    assert file_chooser
79
80
81async def test_should_work_when_file_input_is_attached_to_dom(page: Page):
82    await page.set_content("<input type=file>")
83    async with page.expect_file_chooser() as fc_info:
84        await page.click("input")
85    file_chooser = await fc_info.value
86    assert file_chooser
87
88
89async def test_should_work_when_file_input_is_not_attached_to_DOM(page):
90    async with page.expect_file_chooser() as fc_info:
91        await page.evaluate(
92            """() => {
93                el = document.createElement('input')
94                el.type = 'file'
95                el.click()
96            }"""
97        )
98    file_chooser = await fc_info.value
99    assert file_chooser
100
101
102async def test_should_return_the_same_file_chooser_when_there_are_many_watchdogs_simultaneously(
103    page: Page,
104):
105    await page.set_content("<input type=file>")
106    results = await asyncio.gather(
107        page.wait_for_event("filechooser"),
108        page.wait_for_event("filechooser"),
109        page.eval_on_selector("input", "input => input.click()"),
110    )
111    assert results[0] == results[1]
112
113
114async def test_should_accept_single_file(page: Page):
115    await page.set_content('<input type=file oninput="javascript:console.timeStamp()">')
116    async with page.expect_file_chooser() as fc_info:
117        await page.click("input")
118    file_chooser = await fc_info.value
119    assert file_chooser.page == page
120    assert file_chooser.element
121    await file_chooser.set_files(FILE_TO_UPLOAD)
122    assert await page.eval_on_selector("input", "input => input.files.length") == 1
123    assert (
124        await page.eval_on_selector("input", "input => input.files[0].name")
125        == "file-to-upload.txt"
126    )
127
128
129async def test_should_be_able_to_read_selected_file(page: Page):
130    page.once(
131        "filechooser", lambda file_chooser: file_chooser.set_files(FILE_TO_UPLOAD)
132    )
133    await page.set_content("<input type=file>")
134    content = await page.eval_on_selector(
135        "input",
136        """async picker => {
137            picker.click();
138            await new Promise(x => picker.oninput = x);
139            const reader = new FileReader();
140            const promise = new Promise(fulfill => reader.onload = fulfill);
141            reader.readAsText(picker.files[0]);
142            return promise.then(() => reader.result);
143        }""",
144    )
145    assert content == "contents of the file\n"
146
147
148async def test_should_be_able_to_reset_selected_files_with_empty_file_list(
149    page: Page, server
150):
151    await page.set_content("<input type=file>")
152    page.once(
153        "filechooser", lambda file_chooser: file_chooser.set_files(FILE_TO_UPLOAD)
154    )
155    file_length = 0
156    async with page.expect_file_chooser():
157        file_length = await page.eval_on_selector(
158            "input",
159            """async picker => {
160                picker.click();
161                await new Promise(x => picker.oninput = x);
162                return picker.files.length;
163            }""",
164        )
165    assert file_length == 1
166
167    page.once("filechooser", lambda file_chooser: file_chooser.set_files([]))
168    async with page.expect_file_chooser():
169        file_length = await page.eval_on_selector(
170            "input",
171            """async picker => {
172                picker.click();
173                await new Promise(x => picker.oninput = x);
174                return picker.files.length;
175            }""",
176        )
177    assert file_length == 0
178
179
180async def test_should_not_accept_multiple_files_for_single_file_input(
181    page, server, assetdir
182):
183    await page.set_content("<input type=file>")
184    async with page.expect_file_chooser() as fc_info:
185        await page.click("input")
186    file_chooser = await fc_info.value
187    with pytest.raises(Exception) as exc_info:
188        await file_chooser.set_files(
189            [
190                os.path.realpath(assetdir / "file-to-upload.txt"),
191                os.path.realpath(assetdir / "pptr.png"),
192            ]
193        )
194    assert exc_info.value
195
196
197async def test_should_emit_input_and_change_events(page):
198    events = []
199    await page.expose_function("eventHandled", lambda e: events.append(e))
200    await page.set_content(
201        """
202            <input id=input type=file></input>
203            <script>
204            input.addEventListener('input', e => eventHandled({ type: e.type }))
205            input.addEventListener('change', e => eventHandled({ type: e.type }))
206            </script>
207        """
208    )
209    await (await page.query_selector("input")).set_input_files(FILE_TO_UPLOAD)
210    assert len(events) == 2
211    assert events[0]["type"] == "input"
212    assert events[1]["type"] == "change"
213
214
215async def test_should_work_for_single_file_pick(page):
216    await page.set_content("<input type=file>")
217    async with page.expect_file_chooser() as fc_info:
218        await page.click("input")
219    file_chooser = await fc_info.value
220    assert file_chooser.is_multiple() is False
221
222
223async def test_should_work_for_multiple(page):
224    await page.set_content("<input multiple type=file>")
225    async with page.expect_file_chooser() as fc_info:
226        await page.click("input")
227    file_chooser = await fc_info.value
228    assert file_chooser.is_multiple()
229
230
231async def test_should_work_for_webkitdirectory(page):
232    await page.set_content("<input multiple webkitdirectory type=file>")
233    async with page.expect_file_chooser() as fc_info:
234        await page.click("input")
235    file_chooser = await fc_info.value
236    assert file_chooser.is_multiple()
237
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run Python Tests on LambdaTest Cloud Grid

Execute automation tests with Playwright Python on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)