How to use Setup method of Microsoft.Playwright.Tests.DownloadTests class

Best Playwright-dotnet code snippet using Microsoft.Playwright.Tests.DownloadTests.Setup

Run Playwright-dotnet automation tests on LambdaTest cloud grid

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

DownloadTests.cs

Source: DownloadTests.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.IO;
26using System.Threading.Tasks;
27using Microsoft.AspNetCore.Http;
28using Microsoft.Playwright.NUnit;
29using NUnit.Framework;
30
31namespace Microsoft.Playwright.Tests
32{
33    ///<playwright-file>download.spec.ts</playwright-file>
34    public class DownloadTests : PageTestEx
35    {
36        [SetUp]
37        public void Setup()
38        {
39            Server.SetRoute("/download", context =>
40            {
41                context.Response.Headers["Content-Type"] = "application/octet-stream";
42                context.Response.Headers["Content-Disposition"] = "attachment";
43                return context.Response.WriteAsync("Hello world");
44            });
45
46            Server.SetRoute("/downloadWithFilename", context =>
47            {
48                context.Response.Headers["Content-Type"] = "application/octet-stream";
49                context.Response.Headers["Content-Disposition"] = "attachment; filename=file.txt";
50                return context.Response.WriteAsync("Hello world");
51            });
52
53            Server.SetRoute("/downloadWithDelay", async context =>
54            {
55                context.Response.Headers["Content-Type"] = "application/octet-stream";
56                context.Response.Headers["Content-Disposition"] = "attachment;";
57                // Chromium requires a large enough payload to trigger the download event soon enough
58                await context.Response.WriteAsync("a".PadLeft(4096, 'a'));
59                await Task.Delay(3000);
60                await context.Response.WriteAsync("foo hello world");
61            });
62
63            Server.SetRoute("/downloadLarge", context =>
64            {
65                context.Response.Headers["Content-Type"] = "application/octet-stream";
66                context.Response.Headers["Content-Disposition"] = "attachment";
67                var payload = string.Empty;
68                for (var i = 0; i < 10_000; i++)
69                {
70                    payload += $"a{i}";
71                }
72                return context.Response.WriteAsync(payload);
73            });
74        }
75
76        [PlaywrightTest("download.spec.ts", "should report downloads with acceptDownloads: false")]
77        public async Task ShouldReportDownloadsWithAcceptDownloadsFalse()
78        {
79            await Page.SetContentAsync($"<a href=\"{Server.Prefix}/downloadWithFilename\">download</a>");
80            var downloadTask = Page.WaitForDownloadAsync();
81
82            await TaskUtils.WhenAll(
83                downloadTask,
84                Page.ClickAsync("a"));
85
86            var download = downloadTask.Result;
87            Assert.AreEqual($"{Server.Prefix}/downloadWithFilename", download.Url);
88            Assert.AreEqual("file.txt", download.SuggestedFilename);
89
90            string path = await download.PathAsync();
91            Assert.True(new FileInfo(path).Exists);
92            Assert.AreEqual("Hello world", File.ReadAllText(path));
93        }
94
95        [PlaywrightTest("download.spec.ts", "should report downloads with acceptDownloads: true")]
96        public async Task ShouldReportDownloadsWithAcceptDownloadsTrue()
97        {
98            var page = await Browser.NewPageAsync(new() { AcceptDownloads = true });
99            await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");
100            var download = await page.RunAndWaitForDownloadAsync(async () =>
101            {
102                await page.ClickAsync("a");
103            });
104            string path = await download.PathAsync();
105
106            Assert.True(new FileInfo(path).Exists);
107            Assert.AreEqual("Hello world", File.ReadAllText(path));
108        }
109
110        [PlaywrightTest("download.spec.ts", "should save to user-specified path")]
111        public async Task ShouldSaveToUserSpecifiedPath()
112        {
113            var page = await Browser.NewPageAsync(new() { AcceptDownloads = true });
114            await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");
115            var download = await page.RunAndWaitForDownloadAsync(async () =>
116            {
117                await page.ClickAsync("a");
118            });
119
120            using var tmpDir = new TempDirectory();
121            string userPath = Path.Combine(tmpDir.Path, "download.txt");
122            await download.SaveAsAsync(userPath);
123
124            Assert.True(new FileInfo(userPath).Exists);
125            Assert.AreEqual("Hello world", File.ReadAllText(userPath));
126            await page.CloseAsync();
127        }
128
129        [PlaywrightTest("download.spec.ts", "should save to user-specified path without updating original path")]
130        public async Task ShouldSaveToUserSpecifiedPathWithoutUpdatingOriginalPath()
131        {
132            var page = await Browser.NewPageAsync(new() { AcceptDownloads = true });
133            await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");
134
135            var download = await page.RunAndWaitForDownloadAsync(async () =>
136            {
137                await page.ClickAsync("a");
138            });
139
140            using var tmpDir = new TempDirectory();
141            string userPath = Path.Combine(tmpDir.Path, "download.txt");
142            await download.SaveAsAsync(userPath);
143
144            Assert.True(new FileInfo(userPath).Exists);
145            Assert.AreEqual("Hello world", File.ReadAllText(userPath));
146
147            string originalPath = await download.PathAsync();
148            Assert.True(new FileInfo(originalPath).Exists);
149            Assert.AreEqual("Hello world", File.ReadAllText(originalPath));
150
151            await page.CloseAsync();
152        }
153
154        [PlaywrightTest("download.spec.ts", "should save to two different paths with multiple saveAs calls")]
155        public async Task ShouldSaveToTwoDifferentPathsWithMultipleSaveAsCalls()
156        {
157            var page = await Browser.NewPageAsync(new() { AcceptDownloads = true });
158            await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");
159
160            var download = await page.RunAndWaitForDownloadAsync(async () =>
161            {
162                await page.ClickAsync("a");
163            });
164
165            using var tmpDir = new TempDirectory();
166            string userPath = Path.Combine(tmpDir.Path, "download.txt");
167            await download.SaveAsAsync(userPath);
168            Assert.True(new FileInfo(userPath).Exists);
169            Assert.AreEqual("Hello world", File.ReadAllText(userPath));
170
171            string anotherUserPath = Path.Combine(tmpDir.Path, "download (2).txt");
172            await download.SaveAsAsync(anotherUserPath);
173            Assert.True(new FileInfo(anotherUserPath).Exists);
174            Assert.AreEqual("Hello world", File.ReadAllText(anotherUserPath));
175
176            await page.CloseAsync();
177        }
178
179        [PlaywrightTest("download.spec.ts", "should save to overwritten filepath")]
180        public async Task ShouldSaveToOverwrittenFilepath()
181        {
182            var page = await Browser.NewPageAsync(new() { AcceptDownloads = true });
183            await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");
184            var downloadTask = page.WaitForDownloadAsync();
185
186            await TaskUtils.WhenAll(
187                downloadTask,
188                page.ClickAsync("a"));
189
190            using var tmpDir = new TempDirectory();
191            string userPath = Path.Combine(tmpDir.Path, "download.txt");
192            var download = downloadTask.Result;
193            await download.SaveAsAsync(userPath);
194            Assert.AreEqual(1, new DirectoryInfo(tmpDir.Path).GetFiles().Length);
195            await download.SaveAsAsync(userPath);
196            Assert.AreEqual(1, new DirectoryInfo(tmpDir.Path).GetFiles().Length);
197
198            await page.CloseAsync();
199        }
200
201        [PlaywrightTest("download.spec.ts", "should create subdirectories when saving to non-existent user-specified path")]
202        public async Task ShouldCreateSubdirectoriesWhenSavingToNonExistentUserSpecifiedPath()
203        {
204            var page = await Browser.NewPageAsync(new() { AcceptDownloads = true });
205            await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");
206            var downloadTask = page.WaitForDownloadAsync();
207
208            await TaskUtils.WhenAll(
209                downloadTask,
210                page.ClickAsync("a"));
211
212            using var tmpDir = new TempDirectory();
213            string userPath = Path.Combine(tmpDir.Path, "these", "are", "directories", "download.txt");
214            var download = downloadTask.Result;
215            await download.SaveAsAsync(userPath);
216            Assert.True(new FileInfo(userPath).Exists);
217            Assert.AreEqual("Hello world", File.ReadAllText(userPath));
218
219            await page.CloseAsync();
220        }
221
222        [PlaywrightTest("download.spec.ts", "should error when saving with downloads disabled")]
223        public async Task ShouldErrorWhenSavingWithDownloadsDisabled()
224        {
225            var page = await Browser.NewPageAsync(new() { AcceptDownloads = false });
226            await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");
227            var downloadTask = page.WaitForDownloadAsync();
228
229            await TaskUtils.WhenAll(
230                downloadTask,
231                page.ClickAsync("a"));
232
233            using var tmpDir = new TempDirectory();
234            string userPath = Path.Combine(tmpDir.Path, "download.txt");
235            var download = downloadTask.Result;
236
237            var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => download.SaveAsAsync(userPath));
238            StringAssert.Contains("Pass { acceptDownloads: true } when you are creating your browser context", exception.Message);
239        }
240
241        [PlaywrightTest("download.spec.ts", "should error when saving after deletion")]
242        public async Task ShouldErrorWhenSavingAfterDeletion()
243        {
244            var page = await Browser.NewPageAsync(new() { AcceptDownloads = true });
245            await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");
246            var downloadTask = page.WaitForDownloadAsync();
247
248            await TaskUtils.WhenAll(
249                downloadTask,
250                page.ClickAsync("a"));
251
252            using var tmpDir = new TempDirectory();
253            string userPath = Path.Combine(tmpDir.Path, "download.txt");
254            var download = downloadTask.Result;
255            await download.DeleteAsync();
256            var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => download.SaveAsAsync(userPath));
257            StringAssert.Contains("Target page, context or browser has been closed", exception.Message);
258        }
259
260        [PlaywrightTest("download.spec.ts", "should report non-navigation downloads")]
261        public async Task ShouldReportNonNavigationDownloads()
262        {
263            Server.SetRoute("/download", context =>
264            {
265                context.Response.Headers["Content-Type"] = "application/octet-stream";
266                return context.Response.WriteAsync("Hello world");
267            });
268
269            var page = await Browser.NewPageAsync(new() { AcceptDownloads = true });
270            await page.GotoAsync(Server.EmptyPage);
271            await page.SetContentAsync($"<a download=\"file.txt\" href=\"{Server.Prefix}/download\">download</a>");
272            var downloadTask = page.WaitForDownloadAsync();
273
274            await TaskUtils.WhenAll(
275                downloadTask,
276                page.ClickAsync("a"));
277
278            var download = downloadTask.Result;
279            Assert.AreEqual("file.txt", download.SuggestedFilename);
280            string path = await download.PathAsync();
281
282            Assert.True(new FileInfo(path).Exists);
283            Assert.AreEqual("Hello world", File.ReadAllText(path));
284            await page.CloseAsync();
285        }
286
287        [PlaywrightTest("download.spec.ts", "should report download path within page.on('download', …) handler for Files")]
288        public async Task ShouldReportDownloadPathWithinPageOnDownloadHandlerForFiles()
289        {
290            var downloadPathTcs = new TaskCompletionSource<string>();
291            var page = await Browser.NewPageAsync(new() { AcceptDownloads = true });
292            page.Download += async (_, e) =>
293            {
294                downloadPathTcs.TrySetResult(await e.PathAsync());
295            };
296
297            await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");
298            await page.ClickAsync("a");
299            string path = await downloadPathTcs.Task;
300
301            Assert.AreEqual("Hello world", File.ReadAllText(path));
302            await page.CloseAsync();
303        }
304
305        [PlaywrightTest("download.spec.ts", "should report download path within page.on('download', …) handler for Blobs")]
306        public async Task ShouldReportDownloadPathWithinPageOnDownloadHandlerForBlobs()
307        {
308            var downloadPathTcs = new TaskCompletionSource<string>();
309            var page = await Browser.NewPageAsync(new() { AcceptDownloads = true });
310            page.Download += async (_, e) =>
311            {
312                downloadPathTcs.TrySetResult(await e.PathAsync());
313            };
314
315            await page.GotoAsync(Server.Prefix + "/download-blob.html");
316            await page.ClickAsync("a");
317            string path = await downloadPathTcs.Task;
318
319            Assert.AreEqual("Hello world", File.ReadAllText(path));
320            await page.CloseAsync();
321        }
322
323        [PlaywrightTest("download.spec.ts", "should report alt-click downloads")]
324        [Skip(SkipAttribute.Targets.Firefox, SkipAttribute.Targets.Webkit)]
325        public async Task ShouldReportAltClickDownloads()
326        {
327            Server.SetRoute("/download", context =>
328            {
329                context.Response.Headers["Content-Type"] = "application/octet-stream";
330                return context.Response.WriteAsync("Hello world");
331            });
332
333            var page = await Browser.NewPageAsync(new() { AcceptDownloads = true });
334            await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");
335            var downloadTask = page.WaitForDownloadAsync();
336
337            await TaskUtils.WhenAll(
338                downloadTask,
339                page.ClickAsync("a", new() { Modifiers = new[] { KeyboardModifier.Alt } }));
340
341            var download = downloadTask.Result;
342            string path = await download.PathAsync();
343
344            Assert.True(new FileInfo(path).Exists);
345            Assert.AreEqual("Hello world", File.ReadAllText(path));
346        }
347
348        [PlaywrightTest("download.spec.ts", "should report new window downloads")]
349        public async Task ShouldReportNewWindowDownloads()
350        {
351            var page = await Browser.NewPageAsync(new() { AcceptDownloads = true });
352            await page.SetContentAsync($"<a target=_blank href=\"{Server.Prefix}/download\">download</a>");
353            var downloadTask = page.WaitForDownloadAsync();
354
355            await TaskUtils.WhenAll(
356                downloadTask,
357                page.ClickAsync("a"));
358
359            var download = downloadTask.Result;
360            string path = await download.PathAsync();
361
362            Assert.True(new FileInfo(path).Exists);
363            Assert.AreEqual("Hello world", File.ReadAllText(path));
364        }
365
366        [PlaywrightTest("download.spec.ts", "should delete file")]
367        public async Task ShouldDeleteFile()
368        {
369            var page = await Browser.NewPageAsync(new() { AcceptDownloads = true });
370            await page.SetContentAsync($"<a target=_blank href=\"{Server.Prefix}/download\">download</a>");
371            var downloadTask = page.WaitForDownloadAsync();
372
373            await TaskUtils.WhenAll(
374                downloadTask,
375                page.ClickAsync("a"));
376
377            var download = downloadTask.Result;
378            string path = await download.PathAsync();
379
380            Assert.True(new FileInfo(path).Exists);
381            await download.DeleteAsync();
382            Assert.False(new FileInfo(path).Exists);
383            await page.CloseAsync();
384        }
385
386        [PlaywrightTest("download.spec.ts", "should expose stream")]
387        public async Task ShouldExposeStream()
388        {
389            var page = await Browser.NewPageAsync(new() { AcceptDownloads = true });
390            await page.SetContentAsync($"<a target=_blank href=\"{Server.Prefix}/downloadLarge\">download</a>");
391            var downloadTask = page.WaitForDownloadAsync();
392
393            await TaskUtils.WhenAll(
394                downloadTask,
395                page.ClickAsync("a"));
396
397            var download = downloadTask.Result;
398            var expected = string.Empty;
399            for (var i = 0; i < 10_000; i++)
400            {
401                expected += $"a{i}";
402            }
403            using (var stream = await download.CreateReadStreamAsync())
404            {
405                Assert.AreEqual(expected, await new StreamReader(stream).ReadToEndAsync());
406            }
407
408            await page.CloseAsync();
409        }
410
411        [PlaywrightTest("download.spec.ts", "should delete downloads on context destruction")]
412        public async Task ShouldDeleteDownloadsOnContextDestruction()
413        {
414            var page = await Browser.NewPageAsync(new() { AcceptDownloads = true });
415            await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");
416            var download1Task = page.WaitForDownloadAsync();
417
418            await TaskUtils.WhenAll(
419                download1Task,
420                page.ClickAsync("a"));
421
422            var download2Task = page.WaitForDownloadAsync();
423
424            await TaskUtils.WhenAll(
425                download2Task,
426                page.ClickAsync("a"));
427
428            string path1 = await download1Task.Result.PathAsync();
429            string path2 = await download2Task.Result.PathAsync();
430            Assert.True(new FileInfo(path1).Exists);
431            Assert.True(new FileInfo(path2).Exists);
432            await page.Context.CloseAsync();
433            Assert.False(new FileInfo(path1).Exists);
434            Assert.False(new FileInfo(path2).Exists);
435        }
436
437        [PlaywrightTest("download.spec.ts", "should delete downloads on browser gone")]
438        public async Task ShouldDeleteDownloadsOnBrowserGone()
439        {
440            var browser = await BrowserType.LaunchAsync();
441            var page = await browser.NewPageAsync(new() { AcceptDownloads = true });
442            await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");
443            var download1Task = page.WaitForDownloadAsync();
444
445            await TaskUtils.WhenAll(
446                download1Task,
447                page.ClickAsync("a"));
448
449            var download2Task = page.WaitForDownloadAsync();
450
451            await TaskUtils.WhenAll(
452                download2Task,
453                page.ClickAsync("a"));
454
455            string path1 = await download1Task.Result.PathAsync();
456            string path2 = await download2Task.Result.PathAsync();
457            Assert.True(new FileInfo(path1).Exists);
458            Assert.True(new FileInfo(path2).Exists);
459            await browser.CloseAsync();
460            Assert.False(new FileInfo(path1).Exists);
461            Assert.False(new FileInfo(path2).Exists);
462            Assert.False(new FileInfo(Path.Combine(path1, "..")).Exists);
463        }
464
465        [PlaywrightTest("download.spec.ts", "should be able to cancel pending downloads")]
466        public async Task ShouldBeAbleToCancelPendingDownload()
467        {
468            var browser = await BrowserType.LaunchAsync();
469            var page = await browser.NewPageAsync(new() { AcceptDownloads = true });
470            await page.SetContentAsync($"<a href=\"{Server.Prefix}/downloadWithDelay\">download</a>");
471
472            var download = await page.RunAndWaitForDownloadAsync(() => page.ClickAsync("a"));
473            await download.CancelAsync();
474
475            var failure = await download.FailureAsync();
476            Assert.AreEqual("canceled", failure);
477
478            await page.CloseAsync();
479        }
480
481        [PlaywrightTest("download.spec.ts", "should not fail explicitly to cancel a download even if that is already finished")]
482        public async Task ShouldNotFailWhenCancellingACompletedDownload()
483        {
484            var browser = await BrowserType.LaunchAsync();
485            var page = await browser.NewPageAsync(new() { AcceptDownloads = true });
486            await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");
487            var download = await page.RunAndWaitForDownloadAsync(() => page.ClickAsync("a"));
488
489            using var tmpDir = new TempDirectory();
490            string userPath = Path.Combine(tmpDir.Path, "download.txt");
491            await download.SaveAsAsync(userPath);
492
493            Assert.IsTrue(File.Exists(userPath));
494
495            await download.CancelAsync();
496
497            var failure = await download.FailureAsync();
498            Assert.IsNull(failure);
499
500            await page.CloseAsync();
501        }
502
503
504        [PlaywrightTest("download.spec.ts", "should report downloads with interception")]
505        public async Task ShouldReportDownloadsWithInterception()
506        {
507            var browser = await BrowserType.LaunchAsync();
508            var page = await browser.NewPageAsync(new() { AcceptDownloads = true });
509            await page.RouteAsync("*", r => r.ContinueAsync());
510            await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");
511            var download = await page.RunAndWaitForDownloadAsync(() => page.ClickAsync("a"));
512
513            var path = await download.PathAsync();
514            Assert.IsTrue(File.Exists(path));
515
516            await page.CloseAsync();
517        }
518
519    }
520}
521
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)