How to use ShouldDetectMimeType method of Microsoft.Playwright.Tests.PageSetInputFilesTests class

Best Playwright-dotnet code snippet using Microsoft.Playwright.Tests.PageSetInputFilesTests.ShouldDetectMimeType

Run Playwright-dotnet automation tests on LambdaTest cloud grid

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

PageSetInputFilesTests.cs

Source: PageSetInputFilesTests.cs Github

copy
1/*
2 * MIT License
3 *
4 * Copyright (c) Microsoft Corporation.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 * SOFTWARE.
23 */
24
25using System;
26using System.Collections.Generic;
27using System.IO;
28using System.Linq;
29using System.Text;
30using System.Threading.Tasks;
31using Microsoft.Playwright.NUnit;
32using NUnit.Framework;
33
34namespace Microsoft.Playwright.Tests
35{
36    ///<playwright-file>page-set-input-files.spec.ts</playwright-file>
37    public class PageSetInputFilesTests : PageTestEx
38    {
39        [PlaywrightTest("page-set-input-files.spec.ts", "should upload the file")]
40        public async Task ShouldUploadTheFile()
41        {
42            await Page.GotoAsync(Server.Prefix + "/input/fileupload.html");
43            string filePath = Path.Combine(Directory.GetCurrentDirectory(), "Assets", TestConstants.FileToUpload);
44            var input = await Page.QuerySelectorAsync("input");
45            await input.SetInputFilesAsync(filePath);
46            Assert.AreEqual("file-to-upload.txt", await Page.EvaluateAsync<string>("e => e.files[0].name", input));
47            Assert.AreEqual("contents of the file", await Page.EvaluateAsync<string>(@"e => {
48                var reader = new FileReader();
49                var promise = new Promise(fulfill => reader.onload = fulfill);
50                reader.readAsText(e.files[0]);
51                return promise.then(() => reader.result);
52            }", input));
53        }
54
55        [PlaywrightTest("page-set-input-files.spec.ts", "should work")]
56        public async Task ShouldWork()
57        {
58            await Page.SetContentAsync("<input type=file>");
59            string filePath = Path.Combine(Directory.GetCurrentDirectory(), "Assets", TestConstants.FileToUpload);
60            await Page.SetInputFilesAsync("input", filePath);
61
62            Assert.AreEqual(1, await Page.EvalOnSelectorAsync<int>("input", "e => e.files.length"));
63            Assert.AreEqual("file-to-upload.txt", await Page.EvalOnSelectorAsync<string>("input", "e => e.files[0].name"));
64        }
65
66        [PlaywrightTest("page-set-input-files.spec.ts", "should set from memory")]
67        public async Task ShouldSetFromMemory()
68        {
69            await Page.SetContentAsync("<input type=file>");
70
71            await Page.SetInputFilesAsync("input", new FilePayload
72            {
73                Name = "test.txt",
74                MimeType = "text/plain",
75                Buffer = Encoding.UTF8.GetBytes("this is a test"),
76            });
77
78            Assert.AreEqual(1, await Page.EvalOnSelectorAsync<int>("input", "e => e.files.length"));
79            Assert.AreEqual("test.txt", await Page.EvalOnSelectorAsync<string>("input", "e => e.files[0].name"));
80        }
81
82        [PlaywrightTest("page-set-input-files.spec.ts", "should emit event once")]
83        public async Task ShouldEmitEventOnce()
84        {
85            await Page.SetContentAsync("<input type=file>");
86            var chooserTsc = new TaskCompletionSource<IElementHandle>();
87            void EventHandler(object sender, IFileChooser e)
88            {
89                chooserTsc.SetResult(e.Element);
90                Page.FileChooser -= EventHandler;
91            }
92            Page.FileChooser += EventHandler;
93            var chooser = await TaskUtils.WhenAll(
94                chooserTsc.Task,
95                Page.ClickAsync("input")
96            );
97            Assert.NotNull(chooser);
98        }
99
100        [PlaywrightTest("page-set-input-files.spec.ts", "should emit event on/off")]
101        [Ignore("We don't need to test this")]
102        public void ShouldEmitEventOnOff()
103        {
104        }
105
106        [PlaywrightTest("page-set-input-files.spec.ts", "should emit addListener/removeListener")]
107        [Ignore("We don't need to test this")]
108        public void ShouldEmitEventAddListenerRemoveListener()
109        {
110        }
111
112        [PlaywrightTest("page-set-input-files.spec.ts", "should work when file input is attached to DOM")]
113        public async Task ShouldWorkWhenFileInputIsAttachedToDOM()
114        {
115            await Page.SetContentAsync("<input type=file>");
116            var chooser = await TaskUtils.WhenAll(
117                Page.WaitForFileChooserAsync(),
118                Page.ClickAsync("input")
119            );
120            Assert.NotNull(chooser?.Element);
121        }
122
123        [PlaywrightTest("page-set-input-files.spec.ts", "should work when file input is not attached to DOM")]
124        public async Task ShouldWorkWhenFileInputIsNotAttachedToDOM()
125        {
126            var (chooser, _) = await TaskUtils.WhenAll(
127                Page.WaitForFileChooserAsync(),
128                Page.EvaluateAsync(@"() => {
129                    var el = document.createElement('input');
130                    el.type = 'file';
131                    el.click();
132                }")
133            );
134            Assert.NotNull(chooser?.Element);
135        }
136
137
138        [PlaywrightTest("page-set-input-files.spec.ts", "should work with CSP")]
139        public async Task ShouldWorkWithCSP()
140        {
141            Server.SetCSP("/empty.html", "default-src \"none\"");
142            await Page.GotoAsync(Server.EmptyPage);
143            await Page.SetContentAsync("<input type=file>");
144
145            await Page.SetInputFilesAsync("input", Path.Combine(Directory.GetCurrentDirectory(), "Assets", TestConstants.FileToUpload));
146            Assert.AreEqual(1, await Page.EvalOnSelectorAsync<int>("input", "input => input.files.length"));
147            Assert.AreEqual("file-to-upload.txt", await Page.EvalOnSelectorAsync<string>("input", "input => input.files[0].name"));
148        }
149
150        [PlaywrightTest("page-set-input-files.spec.ts", "should respect timeout")]
151        public Task ShouldRespectTimeout()
152        {
153            return PlaywrightAssert.ThrowsAsync<TimeoutException>(()
154             => Page.WaitForFileChooserAsync(new() { Timeout = 1 }));
155        }
156
157        [PlaywrightTest("page-set-input-files.spec.ts", "should respect default timeout when there is no custom timeout")]
158        public Task ShouldRespectDefaultTimeoutWhenThereIsNoCustomTimeout()
159        {
160            Page.SetDefaultTimeout(1);
161            return PlaywrightAssert.ThrowsAsync<TimeoutException>(() => Page.WaitForFileChooserAsync());
162        }
163
164        [PlaywrightTest("page-set-input-files.spec.ts", "should prioritize exact timeout over default timeout")]
165        public Task ShouldPrioritizeExactTimeoutOverDefaultTimeout()
166        {
167            Page.SetDefaultTimeout(0);
168            return PlaywrightAssert.ThrowsAsync<TimeoutException>(() => Page.WaitForFileChooserAsync(new() { Timeout = 1 }));
169        }
170
171        [PlaywrightTest("page-set-input-files.spec.ts", "should work with no timeout")]
172        public async Task ShouldWorkWithNoTimeout()
173        {
174            var (chooser, _) = await TaskUtils.WhenAll(
175                Page.WaitForFileChooserAsync(new() { Timeout = 0 }),
176                Page.EvaluateAsync(@"() => setTimeout(() => {
177                    var el = document.createElement('input');
178                    el.type = 'file';
179                    el.click();
180                }, 50)")
181            );
182            Assert.NotNull(chooser?.Element);
183        }
184
185        [PlaywrightTest("page-set-input-files.spec.ts", "should return the same file chooser when there are many watchdogs simultaneously")]
186        public async Task ShouldReturnTheSameFileChooserWhenThereAreManyWatchdogsSimultaneously()
187        {
188            await Page.SetContentAsync("<input type=file>");
189            var (fileChooser1, fileChooser2, _) = await TaskUtils.WhenAll(
190                Page.WaitForFileChooserAsync(),
191                Page.WaitForFileChooserAsync(),
192                Page.EvalOnSelectorAsync("input", "input => input.click()")
193            );
194            Assert.AreEqual(fileChooser1, fileChooser2);
195        }
196
197        [PlaywrightTest("page-set-input-files.spec.ts", "should accept single file")]
198        public async Task ShouldAcceptSingleFile()
199        {
200            await Page.SetContentAsync("<input type=file oninput='javascript:console.timeStamp()'>");
201            var fileChooser = await Page.RunAndWaitForFileChooserAsync(async () =>
202            {
203                await Page.ClickAsync("input");
204            });
205
206            Assert.AreEqual(Page, fileChooser.Page);
207            Assert.NotNull(fileChooser.Element);
208            await fileChooser.SetFilesAsync(TestConstants.FileToUpload);
209            Assert.AreEqual(1, await Page.EvalOnSelectorAsync<int>("input", "input => input.files.length"));
210            Assert.AreEqual("file-to-upload.txt", await Page.EvalOnSelectorAsync<string>("input", "input => input.files[0].name"));
211        }
212
213        [PlaywrightTest("page-set-input-files.spec.ts", "should detect mime type")]
214        public async Task ShouldDetectMimeType()
215        {
216            var files = new List<(string name, string mime, byte[] content)>();
217
218            Server.SetRoute("/upload", context =>
219            {
220                files.AddRange(context.Request.Form.Files.Select(f =>
221                {
222                    using var ms = new MemoryStream();
223                    f.CopyTo(ms);
224                    return (f.FileName, f.ContentType, ms.ToArray());
225                }));
226                return Task.CompletedTask;
227            });
228
229            await Page.GotoAsync(Server.EmptyPage);
230            await Page.SetContentAsync(@"
231                <form action=""/upload"" method=""post"" enctype=""multipart/form-data"">
232                    <input type=""file"" name=""file1"">
233                    <input type=""file"" name=""file2"">
234                    <input type=""submit"" value=""Submit"">
235                </form>
236            ");
237
238            await (await Page.QuerySelectorAsync("input[name=file1]")).SetInputFilesAsync(TestUtils.GetAsset("file-to-upload.txt"));
239            await (await Page.QuerySelectorAsync("input[name=file2]")).SetInputFilesAsync(TestUtils.GetAsset("pptr.png"));
240
241            await TaskUtils.WhenAll(
242               Page.ClickAsync("input[type=submit]"),
243               Server.WaitForRequest("/upload")
244            );
245
246            Assert.AreEqual("file-to-upload.txt", files[0].name);
247            Assert.AreEqual("text/plain", files[0].mime);
248            Assert.AreEqual(File.ReadAllBytes(TestUtils.GetAsset("file-to-upload.txt")), files[0].content);
249
250            Assert.AreEqual("pptr.png", files[1].name);
251            Assert.AreEqual("image/png", files[1].mime);
252            Assert.AreEqual(File.ReadAllBytes(TestUtils.GetAsset("pptr.png")), files[1].content);
253        }
254
255        [PlaywrightTest("page-set-input-files.spec.ts", "should be able to read selected file")]
256        public async Task ShouldBeAbleToReadSelectedFile()
257        {
258            await Page.SetContentAsync("<input type=file>");
259            _ = Page.WaitForFileChooserAsync()
260                .ContinueWith(task => task.Result.SetFilesAsync(TestConstants.FileToUpload));
261            Assert.AreEqual("contents of the file", await Page.EvalOnSelectorAsync<string>("input", @"async picker => {
262                picker.click();
263                await new Promise(x => picker.oninput = x);
264                const reader = new FileReader();
265                const promise = new Promise(fulfill => reader.onload = fulfill);
266                reader.readAsText(picker.files[0]);
267                return promise.then(() => reader.result);
268            }"));
269        }
270
271        [PlaywrightTest("page-set-input-files.spec.ts", "should be able to reset selected files with empty file list")]
272        public async Task ShouldBeAbleToResetSelectedFilesWithEmptyFileList()
273        {
274            await Page.SetContentAsync("<input type=file>");
275            _ = Page.WaitForFileChooserAsync()
276                .ContinueWith(task => task.Result.SetFilesAsync(TestConstants.FileToUpload));
277            Assert.AreEqual(1, await Page.EvalOnSelectorAsync<int>("input", @"async picker => {
278                picker.click();
279                await new Promise(x => picker.oninput = x);
280                return picker.files.length;
281            }"));
282            _ = Page.WaitForFileChooserAsync()
283                .ContinueWith(task => task.Result.Element.SetInputFilesAsync(new string[] { }));
284            Assert.AreEqual(0, await Page.EvalOnSelectorAsync<int>("input", @"async picker => {
285                picker.click();
286                await new Promise(x => picker.oninput = x);
287                return picker.files.length;
288            }"));
289        }
290
291        [PlaywrightTest("page-set-input-files.spec.ts", "should not accept multiple files for single-file input")]
292        public async Task ShouldNotAcceptMultipleFilesForSingleFileInput()
293        {
294            await Page.SetContentAsync("<input type=file>");
295            var fileChooser = await TaskUtils.WhenAll(
296               Page.WaitForFileChooserAsync(),
297               Page.ClickAsync("input")
298            );
299            await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() =>
300                fileChooser.SetFilesAsync(new string[]
301                {
302                    TestUtils.GetAsset(TestConstants.FileToUpload),
303                    TestUtils.GetAsset("pptr.png"),
304                }));
305        }
306
307        [PlaywrightTest("page-set-input-files.spec.ts", "should emit input and change events")]
308        public async Task ShouldEmitInputAndChangeEvents()
309        {
310            var events = new List<string>();
311            await Page.ExposeFunctionAsync("eventHandled", (string e) => events.Add(e));
312
313            await Page.SetContentAsync(@"
314                 <input id=input type=file></input>
315                <script>
316                  input.addEventListener('input', e => eventHandled(e.type));
317                  input.addEventListener('change', e => eventHandled(e.type));
318                </script>
319            ");
320
321            await (await Page.QuerySelectorAsync("input")).SetInputFilesAsync(TestUtils.GetAsset("file-to-upload.txt"));
322            Assert.AreEqual(2, events.Count);
323            Assert.AreEqual("input", events[0]);
324            Assert.AreEqual("change", events[1]);
325        }
326
327        [PlaywrightTest("page-set-input-files.spec.ts", "should work for single file pick")]
328        public async Task ShouldWorkForSingleFilePick()
329        {
330            await Page.SetContentAsync("<input type=file>");
331            var waitTask = Page.WaitForFileChooserAsync();
332
333            var fileChooser = await TaskUtils.WhenAll(
334               waitTask,
335               Page.ClickAsync("input")
336            );
337            Assert.False(fileChooser.IsMultiple);
338        }
339
340        [PlaywrightTest("page-set-input-files.spec.ts", @"should work for ""multiple""")]
341        public async Task ShouldWorkForMultiple()
342        {
343            await Page.SetContentAsync("<input multiple type=file>");
344            var fileChooser = await TaskUtils.WhenAll(
345               Page.WaitForFileChooserAsync(),
346               Page.ClickAsync("input")
347            );
348            Assert.True(fileChooser.IsMultiple);
349        }
350
351        [PlaywrightTest("page-set-input-files.spec.ts", @"should work for ""webkitdirectory""")]
352        public async Task ShouldWorkForWebkitdirectory()
353        {
354            await Page.SetContentAsync("<input multiple webkitdirectory type=file>");
355            var fileChooser = await TaskUtils.WhenAll(
356               Page.WaitForFileChooserAsync(),
357               Page.ClickAsync("input")
358            );
359            Assert.True(fileChooser.IsMultiple);
360        }
361
362        [PlaywrightTest("page-set-input-files.spec.ts", "should upload large file")]
363        [Skip(SkipAttribute.Targets.Firefox, SkipAttribute.Targets.Webkit)]
364        public async Task ShouldUploadLargeFile()
365        {
366            await Page.GotoAsync(Server.Prefix + "/input/fileupload.html");
367            using var tmpDir = new TempDirectory();
368            var filePath = Path.Combine(tmpDir.Path, "200MB");
369            using (var stream = File.OpenWrite(filePath))
370            {
371                var str = new string('a', 4 * 1024);
372                for (var i = 0; i < 50 * 1024; i++)
373                {
374                    await stream.WriteAsync(Encoding.UTF8.GetBytes(str));
375                }
376            }
377            var input = Page.Locator("input[type=file]");
378            var events = await input.EvaluateHandleAsync(@"e => {
379                const events = [];
380                e.addEventListener('input', () => events.push('input'));
381                e.addEventListener('change', () => events.push('change'));
382                return events;
383            }");
384            await input.SetInputFilesAsync(filePath);
385            Assert.AreEqual(await input.EvaluateAsync<string>("e => e.files[0].name"), "200MB");
386            Assert.AreEqual(await events.EvaluateAsync<string[]>("e => e"), new[] { "input", "change" });
387
388            var (file0Name, file0Size) = await TaskUtils.WhenAll(
389               Server.WaitForRequest("/upload", request => (request.Form.Files[0].FileName, request.Form.Files[0].Length)),
390               Page.ClickAsync("input[type=submit]")
391            );
392            Assert.AreEqual("200MB", file0Name);
393            Assert.AreEqual(200 * 1024 * 1024, file0Size);
394        }
395    }
396}
397
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
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)