How to use TempDirectory class of Microsoft.Playwright.Tests package

Best Playwright-dotnet code snippet using Microsoft.Playwright.Tests.TempDirectory

BrowserTypeConnectTests.cs

Source:BrowserTypeConnectTests.cs Github

copy

Full Screen

...290        }291        [PlaywrightTest("browsertype-connect.spec.ts", "should saveAs videos from remote browser")]292        public async Task ShouldSaveAsVideosFromRemoteBrowser()293        {294            using var tempDirectory = new TempDirectory();295            var videoPath = tempDirectory.Path;296            var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);297            var context = await browser.NewContextAsync(new()298            {299                RecordVideoDir = videoPath,300                RecordVideoSize = new() { Height = 320, Width = 240 }301            });302            var page = await context.NewPageAsync();303            await page.EvaluateAsync("() => document.body.style.backgroundColor = 'red'");304            await Task.Delay(1000);305            await context.CloseAsync();306            var videoSavePath = tempDirectory.Path + "my-video.webm";307            await page.Video.SaveAsAsync(videoSavePath);308            Assert.That(videoSavePath, Does.Exist);309            var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(async () => await page.Video.PathAsync());310            StringAssert.Contains("Path is not available when connecting remotely. Use SaveAsAsync() to save a local copy", exception.Message);311        }312        [PlaywrightTest("browsertype-connect.spec.ts", "should save download")]313        public async Task ShouldSaveDownload()314        {315            Server.SetRoute("/download", context =>316            {317                context.Response.Headers["Content-Type"] = "application/octet-stream";318                context.Response.Headers["Content-Disposition"] = "attachment";319                return context.Response.WriteAsync("Hello world");320            });321            var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);322            var page = await browser.NewPageAsync(new() { AcceptDownloads = true });323            await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");324            var downloadTask = page.WaitForDownloadAsync();325            await TaskUtils.WhenAll(326                downloadTask,327                page.ClickAsync("a"));328            using var tmpDir = new TempDirectory();329            string userPath = Path.Combine(tmpDir.Path, "these", "are", "directories", "download.txt");330            var download = downloadTask.Result;331            await download.SaveAsAsync(userPath);332            Assert.True(new FileInfo(userPath).Exists);333            Assert.AreEqual("Hello world", File.ReadAllText(userPath));334            var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => download.PathAsync());335            Assert.AreEqual("Path is not available when connecting remotely. Use SaveAsAsync() to save a local copy.", exception.Message);336            await browser.CloseAsync();337        }338        [PlaywrightTest("browsertype-connect.spec.ts", "should error when saving download after deletion")]339        public async Task ShouldErrorWhenSavingDownloadAfterDeletion()340        {341            Server.SetRoute("/download", context =>342            {343                context.Response.Headers["Content-Type"] = "application/octet-stream";344                context.Response.Headers["Content-Disposition"] = "attachment";345                return context.Response.WriteAsync("Hello world");346            });347            var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);348            var page = await browser.NewPageAsync(new() { AcceptDownloads = true });349            await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");350            var downloadTask = page.WaitForDownloadAsync();351            await TaskUtils.WhenAll(352                downloadTask,353                page.ClickAsync("a"));354            using var tmpDir = new TempDirectory();355            string userPath = Path.Combine(tmpDir.Path, "download.txt");356            var download = downloadTask.Result;357            await download.DeleteAsync();358            var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => download.SaveAsAsync(userPath));359            StringAssert.Contains("Target page, context or browser has been closed", exception.Message);360            await browser.CloseAsync();361        }362        [PlaywrightTest("browsertype-connect.spec.ts", "should save har")]363        public async Task ShouldSaveHar()364        {365            using var tempDirectory = new TempDirectory();366            var harPath = tempDirectory.Path + "/test.har";367            var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);368            var context = await browser.NewContextAsync(new()369            {370                RecordHarPath = harPath371            });372            var page = await context.NewPageAsync();373            await page.GotoAsync(Server.EmptyPage);374            await context.CloseAsync();375            await browser.CloseAsync();376            Assert.That(harPath, Does.Exist);377            var logString = System.IO.File.ReadAllText(harPath);378            StringAssert.Contains(Server.EmptyPage, logString);379        }380        [PlaywrightTest("browsertype-connect.spec.ts", "should record trace with sources")]381        public async Task ShouldRecordContextTraces()382        {383            using var tempDirectory = new TempDirectory();384            var tracePath = tempDirectory.Path + "/trace.zip";385            var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);386            var context = await browser.NewContextAsync();387            var page = await context.NewPageAsync();388            await context.Tracing.StartAsync(new() { Sources = true });389            await page.GotoAsync(Server.EmptyPage);390            await page.SetContentAsync("<button>Click</button>");391            await page.ClickAsync("button");392            await context.Tracing.StopAsync(new TracingStopOptions { Path = tracePath });393            await browser.CloseAsync();394            Assert.That(tracePath, Does.Exist);395            ZipFile.ExtractToDirectory(tracePath, tempDirectory.Path);396            Assert.That(tempDirectory.Path + "/trace.trace", Does.Exist);397            Assert.That(tempDirectory.Path + "/trace.network", Does.Exist);398            Assert.AreEqual(1, Directory.GetFiles(Path.Join(tempDirectory.Path, "resources"), "*.txt").Length);399        }400        [PlaywrightTest("browsertype-connect.spec.ts", "should upload large file")]401        [Skip(SkipAttribute.Targets.Firefox, SkipAttribute.Targets.Webkit)]402        public async Task ShouldUploadLargeFile()403        {404            var browser = await BrowserType.ConnectAsync(_remoteServer.WSEndpoint);405            var context = await browser.NewContextAsync();406            var page = await context.NewPageAsync();407            await page.GotoAsync(Server.Prefix + "/input/fileupload.html");408            using var tmpDir = new TempDirectory();409            var filePath = Path.Combine(tmpDir.Path, "200MB");410            using (var stream = File.OpenWrite(filePath))411            {412                var str = new string('a', 4 * 1024);413                for (var i = 0; i < 50 * 1024; i++)414                {415                    await stream.WriteAsync(Encoding.UTF8.GetBytes(str));416                }417            }418            var input = page.Locator("input[type=file]");419            var events = await input.EvaluateHandleAsync(@"e => {420                const events = [];421                e.addEventListener('input', () => events.push('input'));422                e.addEventListener('change', () => events.push('change'));...

Full Screen

Full Screen

DownloadTests.cs

Source:DownloadTests.cs Github

copy

Full Screen

...103            var download = await page.RunAndWaitForDownloadAsync(async () =>104            {105                await page.ClickAsync("a");106            });107            using var tmpDir = new TempDirectory();108            string userPath = Path.Combine(tmpDir.Path, "download.txt");109            await download.SaveAsAsync(userPath);110            Assert.True(new FileInfo(userPath).Exists);111            Assert.AreEqual("Hello world", File.ReadAllText(userPath));112            await page.CloseAsync();113        }114        [PlaywrightTest("download.spec.ts", "should save to user-specified path without updating original path")]115        public async Task ShouldSaveToUserSpecifiedPathWithoutUpdatingOriginalPath()116        {117            var page = await Browser.NewPageAsync(new() { AcceptDownloads = true });118            await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");119            var download = await page.RunAndWaitForDownloadAsync(async () =>120            {121                await page.ClickAsync("a");122            });123            using var tmpDir = new TempDirectory();124            string userPath = Path.Combine(tmpDir.Path, "download.txt");125            await download.SaveAsAsync(userPath);126            Assert.True(new FileInfo(userPath).Exists);127            Assert.AreEqual("Hello world", File.ReadAllText(userPath));128            string originalPath = await download.PathAsync();129            Assert.True(new FileInfo(originalPath).Exists);130            Assert.AreEqual("Hello world", File.ReadAllText(originalPath));131            await page.CloseAsync();132        }133        [PlaywrightTest("download.spec.ts", "should save to two different paths with multiple saveAs calls")]134        public async Task ShouldSaveToTwoDifferentPathsWithMultipleSaveAsCalls()135        {136            var page = await Browser.NewPageAsync(new() { AcceptDownloads = true });137            await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");138            var download = await page.RunAndWaitForDownloadAsync(async () =>139            {140                await page.ClickAsync("a");141            });142            using var tmpDir = new TempDirectory();143            string userPath = Path.Combine(tmpDir.Path, "download.txt");144            await download.SaveAsAsync(userPath);145            Assert.True(new FileInfo(userPath).Exists);146            Assert.AreEqual("Hello world", File.ReadAllText(userPath));147            string anotherUserPath = Path.Combine(tmpDir.Path, "download (2).txt");148            await download.SaveAsAsync(anotherUserPath);149            Assert.True(new FileInfo(anotherUserPath).Exists);150            Assert.AreEqual("Hello world", File.ReadAllText(anotherUserPath));151            await page.CloseAsync();152        }153        [PlaywrightTest("download.spec.ts", "should save to overwritten filepath")]154        public async Task ShouldSaveToOverwrittenFilepath()155        {156            var page = await Browser.NewPageAsync(new() { AcceptDownloads = true });157            await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");158            var downloadTask = page.WaitForDownloadAsync();159            await TaskUtils.WhenAll(160                downloadTask,161                page.ClickAsync("a"));162            using var tmpDir = new TempDirectory();163            string userPath = Path.Combine(tmpDir.Path, "download.txt");164            var download = downloadTask.Result;165            await download.SaveAsAsync(userPath);166            Assert.AreEqual(1, new DirectoryInfo(tmpDir.Path).GetFiles().Length);167            await download.SaveAsAsync(userPath);168            Assert.AreEqual(1, new DirectoryInfo(tmpDir.Path).GetFiles().Length);169            await page.CloseAsync();170        }171        [PlaywrightTest("download.spec.ts", "should create subdirectories when saving to non-existent user-specified path")]172        public async Task ShouldCreateSubdirectoriesWhenSavingToNonExistentUserSpecifiedPath()173        {174            var page = await Browser.NewPageAsync(new() { AcceptDownloads = true });175            await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");176            var downloadTask = page.WaitForDownloadAsync();177            await TaskUtils.WhenAll(178                downloadTask,179                page.ClickAsync("a"));180            using var tmpDir = new TempDirectory();181            string userPath = Path.Combine(tmpDir.Path, "these", "are", "directories", "download.txt");182            var download = downloadTask.Result;183            await download.SaveAsAsync(userPath);184            Assert.True(new FileInfo(userPath).Exists);185            Assert.AreEqual("Hello world", File.ReadAllText(userPath));186            await page.CloseAsync();187        }188        [PlaywrightTest("download.spec.ts", "should error when saving with downloads disabled")]189        public async Task ShouldErrorWhenSavingWithDownloadsDisabled()190        {191            var page = await Browser.NewPageAsync(new() { AcceptDownloads = false });192            await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");193            var downloadTask = page.WaitForDownloadAsync();194            await TaskUtils.WhenAll(195                downloadTask,196                page.ClickAsync("a"));197            using var tmpDir = new TempDirectory();198            string userPath = Path.Combine(tmpDir.Path, "download.txt");199            var download = downloadTask.Result;200            var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => download.SaveAsAsync(userPath));201            StringAssert.Contains("Pass { acceptDownloads: true } when you are creating your browser context", exception.Message);202        }203        [PlaywrightTest("download.spec.ts", "should error when saving after deletion")]204        public async Task ShouldErrorWhenSavingAfterDeletion()205        {206            var page = await Browser.NewPageAsync(new() { AcceptDownloads = true });207            await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");208            var downloadTask = page.WaitForDownloadAsync();209            await TaskUtils.WhenAll(210                downloadTask,211                page.ClickAsync("a"));212            using var tmpDir = new TempDirectory();213            string userPath = Path.Combine(tmpDir.Path, "download.txt");214            var download = downloadTask.Result;215            await download.DeleteAsync();216            var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => download.SaveAsAsync(userPath));217            StringAssert.Contains("Target page, context or browser has been closed", exception.Message);218        }219        [PlaywrightTest("download.spec.ts", "should report non-navigation downloads")]220        public async Task ShouldReportNonNavigationDownloads()221        {222            Server.SetRoute("/download", context =>223            {224                context.Response.Headers["Content-Type"] = "application/octet-stream";225                return context.Response.WriteAsync("Hello world");226            });227            var page = await Browser.NewPageAsync(new() { AcceptDownloads = true });228            await page.GotoAsync(Server.EmptyPage);229            await page.SetContentAsync($"<a download=\"file.txt\" href=\"{Server.Prefix}/download\">download</a>");230            var downloadTask = page.WaitForDownloadAsync();231            await TaskUtils.WhenAll(232                downloadTask,233                page.ClickAsync("a"));234            var download = downloadTask.Result;235            Assert.AreEqual("file.txt", download.SuggestedFilename);236            string path = await download.PathAsync();237            Assert.True(new FileInfo(path).Exists);238            Assert.AreEqual("Hello world", File.ReadAllText(path));239            await page.CloseAsync();240        }241        [PlaywrightTest("download.spec.ts", "should report download path within page.on('download', …) handler for Files")]242        public async Task ShouldReportDownloadPathWithinPageOnDownloadHandlerForFiles()243        {244            var downloadPathTcs = new TaskCompletionSource<string>();245            var page = await Browser.NewPageAsync(new() { AcceptDownloads = true });246            page.Download += async (_, e) =>247            {248                downloadPathTcs.TrySetResult(await e.PathAsync());249            };250            await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");251            await page.ClickAsync("a");252            string path = await downloadPathTcs.Task;253            Assert.AreEqual("Hello world", File.ReadAllText(path));254            await page.CloseAsync();255        }256        [PlaywrightTest("download.spec.ts", "should report download path within page.on('download', …) handler for Blobs")]257        public async Task ShouldReportDownloadPathWithinPageOnDownloadHandlerForBlobs()258        {259            var downloadPathTcs = new TaskCompletionSource<string>();260            var page = await Browser.NewPageAsync(new() { AcceptDownloads = true });261            page.Download += async (_, e) =>262            {263                downloadPathTcs.TrySetResult(await e.PathAsync());264            };265            await page.GotoAsync(Server.Prefix + "/download-blob.html");266            await page.ClickAsync("a");267            string path = await downloadPathTcs.Task;268            Assert.AreEqual("Hello world", File.ReadAllText(path));269            await page.CloseAsync();270        }271        [PlaywrightTest("download.spec.ts", "should report alt-click downloads")]272        [Skip(SkipAttribute.Targets.Firefox, SkipAttribute.Targets.Webkit)]273        public async Task ShouldReportAltClickDownloads()274        {275            Server.SetRoute("/download", context =>276            {277                context.Response.Headers["Content-Type"] = "application/octet-stream";278                return context.Response.WriteAsync("Hello world");279            });280            var page = await Browser.NewPageAsync(new() { AcceptDownloads = true });281            await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");282            var downloadTask = page.WaitForDownloadAsync();283            await TaskUtils.WhenAll(284                downloadTask,285                page.ClickAsync("a", new() { Modifiers = new[] { KeyboardModifier.Alt } }));286            var download = downloadTask.Result;287            string path = await download.PathAsync();288            Assert.True(new FileInfo(path).Exists);289            Assert.AreEqual("Hello world", File.ReadAllText(path));290        }291        [PlaywrightTest("download.spec.ts", "should report new window downloads")]292        public async Task ShouldReportNewWindowDownloads()293        {294            var page = await Browser.NewPageAsync(new() { AcceptDownloads = true });295            await page.SetContentAsync($"<a target=_blank href=\"{Server.Prefix}/download\">download</a>");296            var downloadTask = page.WaitForDownloadAsync();297            await TaskUtils.WhenAll(298                downloadTask,299                page.ClickAsync("a"));300            var download = downloadTask.Result;301            string path = await download.PathAsync();302            Assert.True(new FileInfo(path).Exists);303            Assert.AreEqual("Hello world", File.ReadAllText(path));304        }305        [PlaywrightTest("download.spec.ts", "should delete file")]306        public async Task ShouldDeleteFile()307        {308            var page = await Browser.NewPageAsync(new() { AcceptDownloads = true });309            await page.SetContentAsync($"<a target=_blank href=\"{Server.Prefix}/download\">download</a>");310            var downloadTask = page.WaitForDownloadAsync();311            await TaskUtils.WhenAll(312                downloadTask,313                page.ClickAsync("a"));314            var download = downloadTask.Result;315            string path = await download.PathAsync();316            Assert.True(new FileInfo(path).Exists);317            await download.DeleteAsync();318            Assert.False(new FileInfo(path).Exists);319            await page.CloseAsync();320        }321        [PlaywrightTest("download.spec.ts", "should expose stream")]322        public async Task ShouldExposeStream()323        {324            var page = await Browser.NewPageAsync(new() { AcceptDownloads = true });325            await page.SetContentAsync($"<a target=_blank href=\"{Server.Prefix}/downloadLarge\">download</a>");326            var downloadTask = page.WaitForDownloadAsync();327            await TaskUtils.WhenAll(328                downloadTask,329                page.ClickAsync("a"));330            var download = downloadTask.Result;331            var expected = string.Empty;332            for (var i = 0; i < 10_000; i++)333            {334                expected += $"a{i}";335            }336            using (var stream = await download.CreateReadStreamAsync())337            {338                Assert.AreEqual(expected, await new StreamReader(stream).ReadToEndAsync());339            }340            await page.CloseAsync();341        }342        [PlaywrightTest("download.spec.ts", "should delete downloads on context destruction")]343        public async Task ShouldDeleteDownloadsOnContextDestruction()344        {345            var page = await Browser.NewPageAsync(new() { AcceptDownloads = true });346            await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");347            var download1Task = page.WaitForDownloadAsync();348            await TaskUtils.WhenAll(349                download1Task,350                page.ClickAsync("a"));351            var download2Task = page.WaitForDownloadAsync();352            await TaskUtils.WhenAll(353                download2Task,354                page.ClickAsync("a"));355            string path1 = await download1Task.Result.PathAsync();356            string path2 = await download2Task.Result.PathAsync();357            Assert.True(new FileInfo(path1).Exists);358            Assert.True(new FileInfo(path2).Exists);359            await page.Context.CloseAsync();360            Assert.False(new FileInfo(path1).Exists);361            Assert.False(new FileInfo(path2).Exists);362        }363        [PlaywrightTest("download.spec.ts", "should delete downloads on browser gone")]364        public async Task ShouldDeleteDownloadsOnBrowserGone()365        {366            var browser = await BrowserType.LaunchAsync();367            var page = await browser.NewPageAsync(new() { AcceptDownloads = true });368            await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");369            var download1Task = page.WaitForDownloadAsync();370            await TaskUtils.WhenAll(371                download1Task,372                page.ClickAsync("a"));373            var download2Task = page.WaitForDownloadAsync();374            await TaskUtils.WhenAll(375                download2Task,376                page.ClickAsync("a"));377            string path1 = await download1Task.Result.PathAsync();378            string path2 = await download2Task.Result.PathAsync();379            Assert.True(new FileInfo(path1).Exists);380            Assert.True(new FileInfo(path2).Exists);381            await browser.CloseAsync();382            Assert.False(new FileInfo(path1).Exists);383            Assert.False(new FileInfo(path2).Exists);384            Assert.False(new FileInfo(Path.Combine(path1, "..")).Exists);385        }386        [PlaywrightTest("download.spec.ts", "should be able to cancel pending downloads")]387        public async Task ShouldBeAbleToCancelPendingDownload()388        {389            var browser = await BrowserType.LaunchAsync();390            var page = await browser.NewPageAsync(new() { AcceptDownloads = true });391            await page.SetContentAsync($"<a href=\"{Server.Prefix}/downloadWithDelay\">download</a>");392            var download = await page.RunAndWaitForDownloadAsync(() => page.ClickAsync("a"));393            await download.CancelAsync();394            var failure = await download.FailureAsync();395            Assert.AreEqual("canceled", failure);396            await page.CloseAsync();397        }398        [PlaywrightTest("download.spec.ts", "should not fail explicitly to cancel a download even if that is already finished")]399        public async Task ShouldNotFailWhenCancellingACompletedDownload()400        {401            var browser = await BrowserType.LaunchAsync();402            var page = await browser.NewPageAsync(new() { AcceptDownloads = true });403            await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");404            var download = await page.RunAndWaitForDownloadAsync(() => page.ClickAsync("a"));405            using var tmpDir = new TempDirectory();406            string userPath = Path.Combine(tmpDir.Path, "download.txt");407            await download.SaveAsAsync(userPath);408            Assert.IsTrue(File.Exists(userPath));409            await download.CancelAsync();410            var failure = await download.FailureAsync();411            Assert.IsNull(failure);412            await page.CloseAsync();413        }414        [PlaywrightTest("download.spec.ts", "should report downloads with interception")]415        public async Task ShouldReportDownloadsWithInterception()416        {417            var browser = await BrowserType.LaunchAsync();418            var page = await browser.NewPageAsync(new() { AcceptDownloads = true });419            await page.RouteAsync("*", r => r.ContinueAsync());...

Full Screen

Full Screen

DefaultBrowsercontext2Tests.cs

Source:DefaultBrowsercontext2Tests.cs Github

copy

Full Screen

...170        }171        [PlaywrightTest("defaultbrowsercontext-2.spec.ts", "should restore state from userDataDir")]172        public async Task ShouldRestoreStateFromUserDataDir()173        {174            using var userDataDir = new TempDirectory();175            await using (var browserContext = await BrowserType.LaunchPersistentContextAsync(userDataDir.Path))176            {177                var page = await browserContext.NewPageAsync();178                await page.GotoAsync(Server.EmptyPage);179                await page.EvaluateAsync("() => localStorage.hey = 'hello'");180            }181            await using (var browserContext2 = await BrowserType.LaunchPersistentContextAsync(userDataDir.Path))182            {183                var page = await browserContext2.NewPageAsync();184                await page.GotoAsync(Server.EmptyPage);185                Assert.AreEqual("hello", await page.EvaluateAsync<string>("() => localStorage.hey"));186            }187            using var userDataDir2 = new TempDirectory();188            await using (var browserContext2 = await BrowserType.LaunchPersistentContextAsync(userDataDir2.Path))189            {190                var page = await browserContext2.NewPageAsync();191                await page.GotoAsync(Server.EmptyPage);192                Assert.That("hello", Is.Not.EqualTo(await page.EvaluateAsync<string>("() => localStorage.hey")));193            }194        }195        [PlaywrightTest("defaultbrowsercontext-2.spec.ts", "should restore cookies from userDataDir")]196        [Skip(SkipAttribute.Targets.Chromium | SkipAttribute.Targets.Windows)]197        public async Task ShouldRestoreCookiesFromUserDataDir()198        {199            using var userDataDir = new TempDirectory();200            await using (var browserContext = await BrowserType.LaunchPersistentContextAsync(userDataDir.Path))201            {202                var page = await browserContext.NewPageAsync();203                await page.GotoAsync(Server.EmptyPage);204                string documentCookie = await page.EvaluateAsync<string>(@"() => {205                    document.cookie = 'doSomethingOnlyOnce=true; expires=Fri, 31 Dec 9999 23:59:59 GMT';206                    return document.cookie;207                }");208                Assert.AreEqual("doSomethingOnlyOnce=true", documentCookie);209            }210            await using (var browserContext2 = await BrowserType.LaunchPersistentContextAsync(userDataDir.Path))211            {212                var page = await browserContext2.NewPageAsync();213                await page.GotoAsync(Server.EmptyPage);214                Assert.AreEqual("doSomethingOnlyOnce=true", await page.EvaluateAsync<string>("() => document.cookie"));215            }216            using var userDataDir2 = new TempDirectory();217            await using (var browserContext2 = await BrowserType.LaunchPersistentContextAsync(userDataDir2.Path))218            {219                var page = await browserContext2.NewPageAsync();220                await page.GotoAsync(Server.EmptyPage);221                Assert.That("doSomethingOnlyOnce=true", Is.Not.EqualTo(await page.EvaluateAsync<string>("() => document.cookie")));222            }223        }224        [PlaywrightTest("defaultbrowsercontext-2.spec.ts", "should have default URL when launching browser")]225        public async Task ShouldHaveDefaultURLWhenLaunchingBrowser()226        {227            var (tmp, context, page) = await LaunchAsync();228            string[] urls = context.Pages.Select(p => p.Url).ToArray();229            Assert.AreEqual(new[] { "about:blank" }, urls);230            await context.DisposeAsync();231            tmp.Dispose();232        }233        [PlaywrightTest("defaultbrowsercontext-2.spec.ts", "should throw if page argument is passed")]234        [Skip(SkipAttribute.Targets.Firefox)]235        public async Task ShouldThrowIfPageArgumentIsPassed()236        {237            using var tmp = new TempDirectory();238            var args = new[] { Server.EmptyPage };239            await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() =>240                BrowserType.LaunchPersistentContextAsync(tmp.Path, new() { Args = args }));241        }242        [PlaywrightTest("defaultbrowsercontext-2.spec.ts", "should fire close event for a persistent context")]243        public async Task ShouldFireCloseEventForAPersistentContext()244        {245            var (tmp, context, _) = await LaunchAsync();246            bool closed = false;247            context.Close += (_, _) => closed = true;248            await context.CloseAsync();249            Assert.True(closed);250            await context.DisposeAsync();251            tmp.Dispose();252        }253        [PlaywrightTest("defaultbrowsercontext-2.spec.ts", "should respect selectors")]254        public async Task ShouldRespectSelectors()255        {256            var (tmp, context, page) = await LaunchAsync();257            const string defaultContextCSS = @"({258                create(root, target) {},259                query(root, selector) {260                    return root.querySelector(selector);261                },262                queryAll(root, selector) {263                    return Array.from(root.querySelectorAll(selector));264                }265            })";266            await TestUtils.RegisterEngineAsync(Playwright, "defaultContextCSS", defaultContextCSS);267            await page.SetContentAsync("<div>hello</div>");268            Assert.AreEqual("hello", await page.InnerHTMLAsync("css=div"));269            Assert.AreEqual("hello", await page.InnerHTMLAsync("defaultContextCSS=div"));270            await context.DisposeAsync();271            tmp.Dispose();272        }273        private async Task<(TempDirectory tmp, IBrowserContext context, IPage page)> LaunchAsync(BrowserTypeLaunchPersistentContextOptions options = null)274        {275            var tmp = new TempDirectory();276            var context = await BrowserType.LaunchPersistentContextAsync(tmp.Path, options);277            var page = context.Pages.First();278            return (tmp, context, page);279        }280    }281}...

Full Screen

Full Screen

TracingTests.cs

Source:TracingTests.cs Github

copy

Full Screen

...53            await page.Mouse.DblClickAsync(20, 30);54            await page.Keyboard.InsertTextAsync("abc");55            await page.WaitForTimeoutAsync(2000); // Give it some time to produce screenshots.56            await page.CloseAsync();57            using var tmp = new TempDirectory();58            var tracePath = Path.Combine(tmp.Path, "trace.zip");59            await Context.Tracing.StopAsync(new() { Path = tracePath });60            var (events, resources) = ParseTrace(tracePath);61            CollectionAssert.IsNotEmpty(events);62            Assert.AreEqual("context-options", events[0].Type);63            string[] actualActionApiNames = GetActions(events);64            string[] expectedActionApiNames = new string[] { "BrowserContext.NewPageAsync", "Page.GotoAsync", "Page.SetContentAsync", "Page.ClickAsync", "Mouse.MoveAsync", "Mouse.DblClickAsync", "Keyboard.InsertTextAsync", "Page.WaitForTimeoutAsync", "Page.CloseAsync", "Tracing.StopAsync" };65            Assert.AreEqual(expectedActionApiNames, actualActionApiNames);66            Assert.GreaterOrEqual(events.Where(e => e.Metadata?.ApiName == "Page.GotoAsync").Count(), 1);67            Assert.GreaterOrEqual(events.Where(e => e.Metadata?.ApiName == "Page.SetContentAsync").Count(), 1);68            Assert.GreaterOrEqual(events.Where(e => e.Metadata?.ApiName == "Page.ClickAsync").Count(), 1);69            Assert.GreaterOrEqual(events.Where(e => e.Metadata?.ApiName == "Mouse.MoveAsync").Count(), 1);70            Assert.GreaterOrEqual(events.Where(e => e.Metadata?.ApiName == "Mouse.DblClickAsync").Count(), 1);71            Assert.GreaterOrEqual(events.Where(e => e.Metadata?.ApiName == "Keyboard.InsertTextAsync").Count(), 1);72            Assert.GreaterOrEqual(events.Where(e => e.Metadata?.ApiName == "Page.CloseAsync").Count(), 1);73            Assert.GreaterOrEqual(events.Where(x => x.Type == "frame-snapshot").Count(), 1);74            Assert.GreaterOrEqual(events.Where(x => x.Type == "screencast-frame").Count(), 1);75            Assert.GreaterOrEqual(events.Where(x => x.Type == "resource-snapshot").Count(), 1);76        }77        [PlaywrightTest("tracing.spec.ts", "should collect two traces")]78        public async Task ShouldCollectTwoTraces()79        {80            var page = await Context.NewPageAsync();81            await Context.Tracing.StartAsync(new() { Screenshots = true, Snapshots = true });82            await page.GotoAsync(Server.EmptyPage);83            await page.SetContentAsync("<button>Click</button>");84            await page.ClickAsync("\"Click\"");85            using var tmp = new TempDirectory();86            var trace1Path = Path.Combine(tmp.Path, "trace1.zip");87            await Context.Tracing.StopAsync(new() { Path = trace1Path });88            await Context.Tracing.StartAsync(new() { Screenshots = true, Snapshots = true });89            await page.DblClickAsync("\"Click\"");90            await page.CloseAsync();91            var trace2Path = Path.Combine(tmp.Path, "trace2.zip");92            await Context.Tracing.StopAsync(new() { Path = trace2Path });93            {94                var (events, resources) = ParseTrace(trace1Path);95                Assert.AreEqual("context-options", events[0].Type);96                Assert.GreaterOrEqual(events.Where(x => x.Metadata?.ApiName == "Page.GotoAsync").Count(), 1);97                Assert.GreaterOrEqual(events.Where(x => x.Metadata?.ApiName == "Page.SetContentAsync").Count(), 1);98                Assert.GreaterOrEqual(events.Where(x => x.Metadata?.ApiName == "Page.ClickAsync").Count(), 1);99                Assert.AreEqual(0, events.Where(x => x.Metadata?.ApiName == "Page.CloseAsync").Count());100                Assert.AreEqual(0, events.Where(x => x.Metadata?.ApiName == "Page.DblClickAsync").Count());101            }102            {103                var (events, resources) = ParseTrace(trace2Path);104                Assert.AreEqual("context-options", events[0].Type);105                Assert.AreEqual(0, events.Where(x => x.Metadata?.ApiName == "Page.GottoAsync").Count());106                Assert.AreEqual(0, events.Where(x => x.Metadata?.ApiName == "Page.SetContentAsync").Count());107                Assert.AreEqual(0, events.Where(x => x.Metadata?.ApiName == "Page.ClickAsync").Count());108                Assert.GreaterOrEqual(events.Where(x => x.Metadata?.ApiName == "Page.CloseAsync").Count(), 1);109                Assert.GreaterOrEqual(events.Where(x => x.Metadata?.ApiName == "Page.DblClickAsync").Count(), 1);110            }111        }112        [PlaywrightTest("tracing.spec.ts", "should collect sources")]113        public async Task ShouldCollectSources()114        {115            await Context.Tracing.StartAsync(new()116            {117                Sources = true,118            });119            var page = await Context.NewPageAsync();120            await page.GotoAsync(Server.Prefix + "/empty.html");121            await page.SetContentAsync("<button>Click</button>");122            await page.ClickAsync("\"Click\"");123            await page.CloseAsync();124            using var tmp = new TempDirectory();125            var tracePath = Path.Combine(tmp.Path, "trace.zip");126            await Context.Tracing.StopAsync(new() { Path = tracePath });127            var (events, resources) = ParseTrace(tracePath);128            var sourceNames = resources.Keys.Where(key => key.EndsWith(".txt")).ToArray();129            Assert.AreEqual(sourceNames.Count(), 1);130            var sourceTraceFileContent = resources[sourceNames[0]];131            var currentFileContent = File.ReadAllText(new StackTrace(true).GetFrame(0).GetFileName());132            Assert.AreEqual(sourceTraceFileContent, currentFileContent);133        }134        [PlaywrightTest("tracing.spec.ts", "should not throw when stopping without start but not exporting")]135        public async Task ShouldNotThrowWhenStoppingWithoutStartButNotExporting()136        {137            await Context.Tracing.StopAsync();138        }139        [PlaywrightTest("tracing.spec.ts", "should not throw when stopping without passing a trace file")]140        public async Task ShouldNotThrowWhenStoppingWithoutPath()141        {142            await Context.Tracing.StartAsync(new()143            {144                Snapshots = true,145            });146            await Context.Tracing.StopAsync();147        }148        [PlaywrightTest()]149        public async Task ShouldSendDotNetApiNames()150        {151            await Context.Tracing.StartAsync(new()152            {153                Screenshots = true,154                Snapshots = true155            });156            var page = await Context.NewPageAsync();157            await page.GotoAsync(Server.EmptyPage);158            await page.SetContentAsync("<a target=_blank rel=noopener href=\"/one-style.html\">yo</a>");159            var page1 = await Context.RunAndWaitForPageAsync(() => page.ClickAsync("a"));160            Assert.AreEqual(42, await page1.EvaluateAsync<int>("1 + 41"));161            using var tmp = new TempDirectory();162            var tracePath = Path.Combine(tmp.Path, "trace.zip");163            await Context.Tracing.StopAsync(new() { Path = tracePath });164            var (events, resources) = ParseTrace(tracePath);165            CollectionAssert.IsNotEmpty(events);166            string[] actualActionApiNames = GetActions(events);167            string[] expectedActionApiNames = new string[] { "BrowserContext.NewPageAsync", "Page.GotoAsync", "Page.SetContentAsync", "BrowserContext.RunAndWaitForPageAsync", "Page.ClickAsync", "Page.EvaluateAsync", "Tracing.StopAsync" };168            Assert.AreEqual(expectedActionApiNames.Count(), actualActionApiNames.Count());169            Assert.AreEqual(expectedActionApiNames, actualActionApiNames);170        }171        private static (IReadOnlyList<TraceEventEntry> Events, Dictionary<string, byte[]> Resources) ParseTrace(string path)172        {173            Dictionary<string, byte[]> resources = new();174            using var archive = ZipFile.OpenRead(path);175            foreach (var entry in archive.Entries)...

Full Screen

Full Screen

HeadfulTests.cs

Source:HeadfulTests.cs Github

copy

Full Screen

...33    {34        [PlaywrightTest("headful.spec.ts", "should have default url when launching browser")]35        public async Task ShouldHaveDefaultUrlWhenLaunchingBrowser()36        {37            using var tempDir = new TempDirectory();38            await using var browserContext = await LaunchPersistentHeaded(tempDir.Path);39            string[] pages = browserContext.Pages.Select(page => page.Url).ToArray();40            Assert.AreEqual(new[] { "about:blank" }, pages);41        }42        [PlaywrightTest("headful.spec.ts", "headless should be able to read cookies written by headful")]43        [Ignore("Flaky")]44        public async Task HeadlessShouldBeAbleToReadCookiesWrittenByHeadful()45        {46            using var userDataDir = new TempDirectory();47            // Write a cookie in headful chrome            48            await using var headfulContext = await LaunchPersistentHeaded(userDataDir.Path);49            var headfulPage = await headfulContext.NewPageAsync();50            await headfulPage.GotoAsync(Server.EmptyPage);51            await headfulPage.EvaluateAsync("() => document.cookie = 'foo=true; expires=Fri, 31 Dec 9999 23:59:59 GMT'");52            await headfulContext.CloseAsync();53            var headlessContext = await LaunchPersistentHeaded(userDataDir.Path);54            var headlessPage = await headlessContext.NewPageAsync();55            await headlessPage.GotoAsync(Server.EmptyPage);56            string cookie = await headlessPage.EvaluateAsync<string>("() => document.cookie");57            await headlessContext.CloseAsync();58            Assert.AreEqual("foo=true", cookie);59        }60        [PlaywrightTest("headful.spec.ts", "should close browser with beforeunload page")]61        public async Task ShouldCloseBrowserWithBeforeunloadPage()62        {63            using var userDataDir = new TempDirectory();64            await using var browserContext = await LaunchPersistentHeaded(userDataDir.Path);65            var page = await browserContext.NewPageAsync();66            await page.GotoAsync(Server.Prefix + "/beforeunload.html");67            // We have to interact with a page so that 'beforeunload' handlers fire.68            await page.ClickAsync("body");69        }70        [PlaywrightTest("headful.spec.ts", "should not crash when creating second context")]71        public async Task ShouldNotCrashWhenCreatingSecondContext()72        {73            await using var browser = await LaunchHeaded();74            await using (var browserContext = await browser.NewContextAsync())75            {76                await browserContext.NewPageAsync();77            }...

Full Screen

Full Screen

DownloadsPathTests.cs

Source:DownloadsPathTests.cs Github

copy

Full Screen

...30{31    public class DownloadsPathTests : PlaywrightTestEx32    {33        private IBrowser _browser { get; set; }34        private TempDirectory _tmp = null;35        [PlaywrightTest("downloads-path.spec.ts", "should keep downloadsPath folder")]36        public async Task ShouldKeepDownloadsPathFolder()37        {38            var page = await _browser.NewPageAsync(new() { AcceptDownloads = false });39            await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");40            var downloadTask = page.WaitForDownloadAsync();41            await TaskUtils.WhenAll(42                downloadTask,43                page.ClickAsync("a"));44            var download = downloadTask.Result;45            Assert.AreEqual($"{Server.Prefix}/download", download.Url);46            Assert.AreEqual("file.txt", download.SuggestedFilename);47            await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => download.PathAsync());48            await page.CloseAsync();49            await _browser.CloseAsync();50            Assert.True(new DirectoryInfo(_tmp.Path).Exists);51        }52        [PlaywrightTest("downloads-path.spec.ts", "should delete downloads when context closes")]53        public async Task ShouldDeleteDownloadsWhenContextCloses()54        {55            var page = await _browser.NewPageAsync(new() { AcceptDownloads = true });56            await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");57            var downloadTask = page.WaitForDownloadAsync();58            await TaskUtils.WhenAll(59                downloadTask,60                page.ClickAsync("a"));61            var download = downloadTask.Result;62            string path = await download.PathAsync();63            Assert.True(new FileInfo(path).Exists);64            await page.CloseAsync();65            Assert.False(new FileInfo(path).Exists);66        }67        [PlaywrightTest("downloads-path.spec.ts", "should report downloads in downloadsPath folder")]68        public async Task ShouldReportDownloadsInDownloadsPathFolder()69        {70            var page = await _browser.NewPageAsync(new() { AcceptDownloads = true });71            await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");72            var downloadTask = page.WaitForDownloadAsync();73            await TaskUtils.WhenAll(74                downloadTask,75                page.ClickAsync("a"));76            var download = downloadTask.Result;77            string path = await download.PathAsync();78            Assert.That(path, Does.StartWith(_tmp.Path));79            await page.CloseAsync();80        }81        [PlaywrightTest("downloads-path.spec.ts", "should report downloads in downloadsPath folder with a relative path")]82        public async Task ShouldReportDownloadsInDownloadsPathFolderWithARelativePath()83        {84            var browser = await Playwright[TestConstants.BrowserName]85                .LaunchAsync(new()86                {87                    DownloadsPath = "."88                });89            var page = await browser.NewPageAsync(new()90            {91                AcceptDownloads = true92            });93            await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");94            var download = await page.RunAndWaitForDownloadAsync(() => page.ClickAsync("a"));95            string path = await download.PathAsync();96            Assert.That(path, Does.StartWith(Directory.GetCurrentDirectory()));97            await page.CloseAsync();98        }99        [PlaywrightTest("downloads-path.spec.ts", "should accept downloads in persistent context")]100        public async Task ShouldAcceptDownloadsInPersistentContext()101        {102            var userProfile = new TempDirectory();103            var browser = await Playwright[TestConstants.BrowserName]104                .LaunchPersistentContextAsync(userProfile.Path, new()105                {106                    AcceptDownloads = true,107                    DownloadsPath = _tmp.Path108                });109            var page = await browser.NewPageAsync();110            await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");111            var download = await page.RunAndWaitForDownloadAsync(() => page.ClickAsync("a"));112            Assert.AreEqual($"{Server.Prefix}/download", download.Url);113            Assert.AreEqual("file.txt", download.SuggestedFilename);114            Assert.That(await download.PathAsync(), Does.StartWith(_tmp.Path));115            await page.CloseAsync();116        }117        [PlaywrightTest("downloads-path.spec.ts", "should delete downloads when persistent context closes")]118        public async Task ShouldDeleteDownloadsWhenPersistentContextCloses()119        {120            var userProfile = new TempDirectory();121            var browser = await Playwright[TestConstants.BrowserName]122                .LaunchPersistentContextAsync(userProfile.Path, new()123                {124                    AcceptDownloads = true,125                    DownloadsPath = _tmp.Path126                });127            var page = await browser.NewPageAsync();128            await page.SetContentAsync($"<a href=\"{Server.Prefix}/download\">download</a>");129            var download = await page.RunAndWaitForDownloadAsync(() => page.ClickAsync("a"));130            var path = await download.PathAsync();131            Assert.IsTrue(File.Exists(path));132            await browser.CloseAsync();133            Assert.IsFalse(File.Exists(path));134        }...

Full Screen

Full Screen

ScreencastTests.cs

Source:ScreencastTests.cs Github

copy

Full Screen

...40            StringAssert.Contains("\"RecordVideoSize\" option requires \"RecordVideoDir\" to be specified", exception.Message);41        }42        public async Task ShouldWorkWithoutASize()43        {44            using var tempDirectory = new TempDirectory();45            var context = await Browser.NewContextAsync(new()46            {47                RecordVideoDir = tempDirectory.Path48            });49            var page = await context.NewPageAsync();50            await page.EvaluateAsync("() => document.body.style.backgroundColor = 'red'");51            await Task.Delay(1000);52            await context.CloseAsync();53            Assert.IsNotEmpty(new DirectoryInfo(tempDirectory.Path).GetFiles("*.webm"));54        }55        [PlaywrightTest("screencast.spec.ts", "should capture static page")]56        [Skip(SkipAttribute.Targets.Webkit | SkipAttribute.Targets.Windows)]57        public async Task ShouldCaptureStaticPage()58        {59            using var tempDirectory = new TempDirectory();60            var context = await Browser.NewContextAsync(new()61            {62                RecordVideoDir = tempDirectory.Path,63                RecordVideoSize = new() { Height = 100, Width = 100 }64            });65            var page = await context.NewPageAsync();66            await page.EvaluateAsync("() => document.body.style.backgroundColor = 'red'");67            await Task.Delay(1000);68            await context.CloseAsync();69            Assert.IsNotEmpty(new DirectoryInfo(tempDirectory.Path).GetFiles("*.webm"));70        }71        [PlaywrightTest("screencast.spec.ts", "should expose video path")]72        public async Task ShouldExposeVideoPath()73        {74            using var tempDirectory = new TempDirectory();75            var context = await Browser.NewContextAsync(new()76            {77                RecordVideoDir = tempDirectory.Path,78                RecordVideoSize = new() { Height = 100, Width = 100 }79            });80            var page = await context.NewPageAsync();81            await page.EvaluateAsync("() => document.body.style.backgroundColor = 'red'");82            string path = await page.Video.PathAsync();83            StringAssert.Contains(tempDirectory.Path, path);84            await context.CloseAsync();85            Assert.True(new FileInfo(path).Exists);86        }87        [PlaywrightTest("screencast.spec.ts", "should expose video path blank page")]88        public async Task ShouldExposeVideoPathBlankPage()89        {90            using var tempDirectory = new TempDirectory();91            var context = await Browser.NewContextAsync(new()92            {93                RecordVideoDir = tempDirectory.Path,94                RecordVideoSize = new() { Height = 100, Width = 100 }95            });96            var page = await context.NewPageAsync();97            string path = await page.Video.PathAsync();98            StringAssert.Contains(tempDirectory.Path, path);99            await context.CloseAsync();100            Assert.True(new FileInfo(path).Exists);101        }102        [PlaywrightTest("screencast.spec.ts", "should expose video path blank popup")]103        [Ignore("We don't need to test video details")]104        public void ShouldExposeVideoPathBlankPopup()105        {106        }107        [PlaywrightTest("screencast.spec.ts", "should capture navigation")]108        [Ignore("We don't need to test video details")]109        public void ShouldCaptureNavigation()110        {111        }112        [PlaywrightTest("screencast.spec.ts", "should capture css transformation")]113        [Ignore("We don't need to test video details")]114        public void ShouldCaptureCssTransformation()115        {116        }117        [PlaywrightTest("screencast.spec.ts", "should work for popups")]118        [Ignore("We don't need to test video details")]119        public void ShouldWorkForPopups()120        {121        }122        [PlaywrightTest("screencast.spec.ts", "should scale frames down to the requested size")]123        [Ignore("We don't need to test video details")]124        public void ShouldScaleFramesDownToTheRequestedSize()125        {126        }127        [PlaywrightTest("screencast.spec.ts", "should use viewport as default size")]128        [Ignore("We don't need to test video details")]129        public void ShouldUseViewportAsDefaultSize()130        {131        }132        [PlaywrightTest("screencast.spec.ts", "should be 1280x720 by default")]133        [Ignore("We don't need to test video details")]134        public void ShouldBe1280x720ByDefault()135        {136        }137        [PlaywrightTest("screencast.spec.ts", "should capture static page in persistent context")]138        [Skip(SkipAttribute.Targets.Webkit, SkipAttribute.Targets.Firefox)]139        public async Task ShouldCaptureStaticPageInPersistentContext()140        {141            using var userDirectory = new TempDirectory();142            using var tempDirectory = new TempDirectory();143            var context = await BrowserType.LaunchPersistentContextAsync(userDirectory.Path, new()144            {145                RecordVideoDir = tempDirectory.Path,146                RecordVideoSize = new() { Height = 100, Width = 100 },147            });148            var page = await context.NewPageAsync();149            await page.EvaluateAsync("() => document.body.style.backgroundColor = 'red'");150            await Task.Delay(1000);151            await context.CloseAsync();152            Assert.IsNotEmpty(new DirectoryInfo(tempDirectory.Path).GetFiles("*.webm"));153        }154    }155}...

Full Screen

Full Screen

HARTests.cs

Source:HARTests.cs Github

copy

Full Screen

...41        }42        [PlaywrightTest("har.spec.ts", "should have pages in persistent context")]43        public async Task ShouldWorkWithPersistentContext()44        {45            using var harFolder = new TempDirectory();46            var harPath = Path.Combine(harFolder.Path, "har.json");47            using var userDataDir = new TempDirectory();48            var browserContext = await BrowserType.LaunchPersistentContextAsync(userDataDir.Path, new()49            {50                RecordHarPath = harPath,51            });52            var page = browserContext.Pages[0];53            await page.GotoAsync("data:text/html,<title>Hello</title>");54            // For data: load comes before domcontentloaded...55            await page.WaitForLoadStateAsync(LoadState.DOMContentLoaded);56            await browserContext.CloseAsync();57            var content = await File.ReadAllTextAsync(harPath);58            var log = JsonSerializer.Deserialize<dynamic>(content);59            Assert.AreEqual(1, log.GetProperty("log").GetProperty("pages").GetArrayLength());60            var pageEntry = log.GetProperty("log").GetProperty("pages")[0];61            Assert.AreEqual("Hello", pageEntry.GetProperty("title").ToString());62        }63        private async Task<(IPage, IBrowserContext, System.Func<Task<dynamic>>)> PageWithHAR()64        {65            var tmp = new TempDirectory();66            var harPath = Path.Combine(tmp.Path, "har.json");67            IBrowserContext context = await Browser.NewContextAsync(new() { RecordHarPath = harPath, IgnoreHTTPSErrors = true });68            IPage page = await context.NewPageAsync();69            async Task<dynamic> getContent()70            {71                await context.CloseAsync();72                var content = await File.ReadAllTextAsync(harPath);73                tmp.Dispose();74                return JsonSerializer.Deserialize<dynamic>(content);75            };76            return (page, context, getContent);77        }78    }79}...

Full Screen

Full Screen

TempDirectory

Using AI Code Generation

copy

Full Screen

1using Microsoft.Playwright.Tests;2using System;3{4    {5        static void Main(string[] args)6        {7            using var tempDirectory = new TempDirectory();8            Console.WriteLine(tempDirectory.Path);9        }10    }11}

Full Screen

Full Screen

TempDirectory

Using AI Code Generation

copy

Full Screen

1using Microsoft.Playwright.Tests;2using System;3using System.IO;4using System.Threading.Tasks;5{6    {7        static async Task Main(string[] args)8        {9            using var tmp = new TempDirectory();10            var path = tmp.Path;11            Console.WriteLine("Path is: " + path);12            File.Create(Path.Combine(path, "file.txt"));13            Console.WriteLine("File is created");14            tmp.Dispose();15            Console.WriteLine("Path is deleted");16            Console.ReadLine();17        }18    }19}

Full Screen

Full Screen

TempDirectory

Using AI Code Generation

copy

Full Screen

1using Microsoft.Playwright.Tests;2using System;3using System.IO;4{5    {6        static void Main(string[] args)7        {8            var tempDir = new TempDirectory();9            Console.WriteLine($"Temp Directory: {tempDir.Path}");10            var tempFile = Path.Combine(tempDir.Path, "tempFile.txt");11            File.WriteAllText(tempFile, "Hello World!");12            Console.WriteLine($"Temp File: {tempFile}");13            Console.WriteLine($"Temp File Content: {File.ReadAllText(tempFile)}");14            tempDir.Dispose();15            Console.WriteLine($"Temp Directory exists: {Directory.Exists(tempDir.Path)}");16        }17    }18}

Full Screen

Full Screen

TempDirectory

Using AI Code Generation

copy

Full Screen

1using Microsoft.Playwright.Tests;2using System;3using System.IO;4{5    {6        static void Main(string[] args)7        {8            var tempDirectory = new TempDirectory();9            var tempDirectoryPath = tempDirectory.Path;10            Console.WriteLine("Temp Directory Path: " + tempDirectoryPath);11            Console.WriteLine("Temp Directory Exists: " + Directory.Exists(tempDirectoryPath));12            Console.WriteLine("Press any key to exit");13            Console.ReadKey();14        }15    }16}

Full Screen

Full Screen

TempDirectory

Using AI Code Generation

copy

Full Screen

1using Microsoft.Playwright.Tests;2using System.IO;3using System.Threading.Tasks;4{5    static async Task Main(string[] args)6    {7        string tempPath = Path.Combine(TempDirectory.Create(), "test.txt");8        File.WriteAllText(tempPath, "Hello World!");9        await Task.Delay(1000);10    }11}

Full Screen

Full Screen

Playwright tutorial

LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright-dotnet automation tests on LambdaTest cloud grid

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

Most used methods in TempDirectory

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful