How to use PixelMatch method of Microsoft.Playwright.Tests.ScreenshotHelper class

Best Playwright-dotnet code snippet using Microsoft.Playwright.Tests.ScreenshotHelper.PixelMatch

ElementHandleScreenshotTests.cs

Source:ElementHandleScreenshotTests.cs Github

copy

Full Screen

...40 await Page.GotoAsync(Server.Prefix + "/grid.html");41 await Page.EvaluateAsync("window.scrollBy(50, 100)");42 var elementHandle = await Page.QuerySelectorAsync(".box:nth-of-type(3)");43 byte[] screenshot = await elementHandle.ScreenshotAsync();44 Assert.True(ScreenshotHelper.PixelMatch("screenshot-element-bounding-box.png", screenshot));45 }46 [PlaywrightTest("elementhandle-screenshot.spec.ts", "should take into account padding and border")]47 public async Task ShouldTakeIntoAccountPaddingAndBorder()48 {49 await Page.SetViewportSizeAsync(500, 500);50 await Page.SetContentAsync(@"51 <div style=""height: 14px"">oooo</div>52 <style>div {53 border: 2px solid blue;54 background: green;55 width: 50px;56 height: 50px;57 }58 </style>59 <div id=""d""></div>");60 var elementHandle = await Page.QuerySelectorAsync("div#d");61 byte[] screenshot = await elementHandle.ScreenshotAsync();62 Assert.True(ScreenshotHelper.PixelMatch("screenshot-element-padding-border.png", screenshot));63 }64 [PlaywrightTest("elementhandle-screenshot.spec.ts", "should capture full element when larger than viewport in parallel")]65 public async Task ShouldCaptureFullElementWhenLargerThanViewportInParallel()66 {67 await Page.SetViewportSizeAsync(500, 500);68 await Page.SetContentAsync(@"69 <div style=""height: 14px"">oooo</div>70 <style>71 div.to-screenshot {72 border: 1px solid blue;73 width: 600px;74 height: 600px;75 margin-left: 50px;76 }77 ::-webkit-scrollbar{78 display: none;79 }80 </style>81 <div class=""to-screenshot""></div>82 <div class=""to-screenshot""></div>83 <div class=""to-screenshot""></div>84 ");85 var elementHandles = await Page.QuerySelectorAllAsync("div.to-screenshot");86 var screenshotTasks = elementHandles.Select(e => e.ScreenshotAsync()).ToArray();87 await TaskUtils.WhenAll(screenshotTasks);88 Assert.True(ScreenshotHelper.PixelMatch("screenshot-element-larger-than-viewport.png", screenshotTasks.ElementAt(2).Result));89 }90 [PlaywrightTest("elementhandle-screenshot.spec.ts", "should capture full element when larger than viewport")]91 public async Task ShouldCaptureFullElementWhenLargerThanViewport()92 {93 await Page.SetViewportSizeAsync(500, 500);94 await Page.SetContentAsync(@"95 <div style=""height: 14px"">oooo</div>96 <style>97 div.to-screenshot {98 border: 1px solid blue;99 width: 600px;100 height: 600px;101 margin-left: 50px;102 }103 ::-webkit-scrollbar{104 display: none;105 }106 </style>107 <div class=""to-screenshot""></div>108 <div class=""to-screenshot""></div>109 <div class=""to-screenshot""></div>");110 var elementHandle = await Page.QuerySelectorAsync("div.to-screenshot");111 byte[] screenshot = await elementHandle.ScreenshotAsync();112 Assert.True(ScreenshotHelper.PixelMatch("screenshot-element-larger-than-viewport.png", screenshot));113 await TestUtils.VerifyViewportAsync(Page, 500, 500);114 }115 [PlaywrightTest("elementhandle-screenshot.spec.ts", "should scroll element into view")]116 public async Task ShouldScrollElementIntoView()117 {118 await Page.SetViewportSizeAsync(500, 500);119 await Page.SetContentAsync(@"120 <div style=""height: 14px"">oooo</div>121 <style>div.above {122 border: 2px solid blue;123 background: red;124 height: 1500px;125 }126 div.to-screenshot {127 border: 2px solid blue;128 background: green;129 width: 50px;130 height: 50px;131 }132 </style>133 <div class=""above""></div>134 <div class=""to-screenshot""></div>");135 var elementHandle = await Page.QuerySelectorAsync("div.to-screenshot");136 byte[] screenshot = await elementHandle.ScreenshotAsync();137 Assert.True(ScreenshotHelper.PixelMatch("screenshot-element-scrolled-into-view.png", screenshot));138 }139 [PlaywrightTest("elementhandle-screenshot.spec.ts", "should scroll 15000px into view")]140 public async Task ShouldScroll15000pxIntoView()141 {142 await Page.SetViewportSizeAsync(500, 500);143 await Page.SetContentAsync(@"144 <div style=""height: 14px"">oooo</div>145 <style>div.above {146 border: 2px solid blue;147 background: red;148 height: 15000px;149 }150 div.to-screenshot {151 border: 2px solid blue;152 background: green;153 width: 50px;154 height: 50px;155 }156 </style>157 <div class=""above""></div>158 <div class=""to-screenshot""></div>");159 var elementHandle = await Page.QuerySelectorAsync("div.to-screenshot");160 byte[] screenshot = await elementHandle.ScreenshotAsync();161 Assert.True(ScreenshotHelper.PixelMatch("screenshot-element-scrolled-into-view.png", screenshot));162 }163 [PlaywrightTest("elementhandle-screenshot.spec.ts", "should work with a rotated element")]164 public async Task ShouldWorkWithARotatedElement()165 {166 await Page.SetViewportSizeAsync(500, 500);167 await Page.SetContentAsync(@"168 <div style='position: absolute;169 top: 100px;170 left: 100px;171 width: 100px;172 height: 100px;173 background: green;174 transform: rotateZ(200deg); '>&nbsp;</div>175 ");176 var elementHandle = await Page.QuerySelectorAsync("div");177 byte[] screenshot = await elementHandle.ScreenshotAsync();178 Assert.True(ScreenshotHelper.PixelMatch("screenshot-element-rotate.png", screenshot));179 }180 [PlaywrightTest("elementhandle-screenshot.spec.ts", "should fail to screenshot a detached element")]181 public async Task ShouldFailToScreenshotADetachedElement()182 {183 await Page.SetContentAsync("<h1>remove this</h1>");184 var elementHandle = await Page.QuerySelectorAsync("h1");185 await Page.EvaluateAsync("element => element.remove()", elementHandle);186 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => elementHandle.ScreenshotAsync());187 StringAssert.Contains("Element is not attached to the DOM", exception.Message);188 }189 [PlaywrightTest("elementhandle-screenshot.spec.ts", "should timeout waiting for visible")]190 public async Task ShouldTimeoutWaitingForVisible()191 {192 await Page.SetContentAsync(@"<div style='width: 50px; height: 0'></div>");193 var elementHandle = await Page.QuerySelectorAsync("div");194 var exception = await PlaywrightAssert.ThrowsAsync<TimeoutException>(() => elementHandle.ScreenshotAsync(new() { Timeout = 3000 }));195 StringAssert.Contains("Timeout 3000ms exceeded", exception.Message);196 StringAssert.Contains("element is not visible", exception.Message);197 }198 [PlaywrightTest("elementhandle-screenshot.spec.ts", "should wait for visible")]199 public async Task ShouldWaitForVisible()200 {201 await Page.SetViewportSizeAsync(500, 500);202 await Page.GotoAsync(Server.Prefix + "/grid.html");203 await Page.EvaluateAsync("() => window.scrollBy(50, 100)");204 var elementHandle = await Page.QuerySelectorAsync(".box:nth-of-type(3)");205 await elementHandle.EvaluateAsync("e => e.style.visibility = 'hidden'");206 var task = elementHandle.ScreenshotAsync();207 for (int i = 0; i < 10; i++)208 {209 await Page.EvaluateAsync("() => new Promise(f => requestAnimationFrame(f))");210 }211 Assert.False(task.IsCompleted);212 await elementHandle.EvaluateAsync("e => e.style.visibility = 'visible'");213 byte[] screenshot = await task;214 Assert.True(ScreenshotHelper.PixelMatch("screenshot-element-bounding-box.png", screenshot));215 }216 [PlaywrightTest("elementhandle-screenshot.spec.ts", "should work for an element with fractional dimensions")]217 public async Task ShouldWorkForAnElementWithFractionalDimensions()218 {219 await Page.SetContentAsync("<div style=\"width:48.51px;height:19.8px;border:1px solid black;\"></div>");220 var elementHandle = await Page.QuerySelectorAsync("div");221 byte[] screenshot = await elementHandle.ScreenshotAsync();222 Assert.True(ScreenshotHelper.PixelMatch("screenshot-element-fractional.png", screenshot));223 }224 [PlaywrightTest("elementhandle-screenshot.spec.ts", "should work with a mobile viewport")]225 [Skip(SkipAttribute.Targets.Firefox)]226 public async Task ShouldWorkWithAMobileViewport()227 {228 await using var context = await Browser.NewContextAsync(new()229 {230 ViewportSize = new()231 {232 Width = 320,233 Height = 480,234 },235 IsMobile = true,236 });237 var page = await context.NewPageAsync();238 await page.GotoAsync(Server.Prefix + "/grid.html");239 await page.EvaluateAsync("() => window.scrollBy(50, 100)");240 var elementHandle = await page.QuerySelectorAsync(".box:nth-of-type(3)");241 byte[] screenshot = await elementHandle.ScreenshotAsync();242 Assert.True(ScreenshotHelper.PixelMatch("screenshot-element-mobile.png", screenshot));243 }244 [PlaywrightTest("elementhandle-screenshot.spec.ts", "should work with device scale factor")]245 [Skip(SkipAttribute.Targets.Firefox)]246 public async Task ShouldWorkWithDeviceScaleFactor()247 {248 await using var context = await Browser.NewContextAsync(new()249 {250 ViewportSize = new()251 {252 Width = 320,253 Height = 480,254 },255 DeviceScaleFactor = 2,256 });257 var page = await context.NewPageAsync();258 await page.GotoAsync(Server.Prefix + "/grid.html");259 await page.EvaluateAsync("() => window.scrollBy(50, 100)");260 var elementHandle = await page.QuerySelectorAsync(".box:nth-of-type(3)");261 byte[] screenshot = await elementHandle.ScreenshotAsync();262 Assert.True(ScreenshotHelper.PixelMatch("screenshot-element-mobile-dsf.png", screenshot));263 }264 [PlaywrightTest("elementhandle-screenshot.spec.ts", "should work for an element with an offset")]265 public async Task ShouldWorkForAnElementWithAnOffset()266 {267 await Page.SetContentAsync("<div style=\"position:absolute; top: 10.3px; left: 20.4px;width:50.3px;height:20.2px;border:1px solid black;\"></div>");268 var elementHandle = await Page.QuerySelectorAsync("div");269 byte[] screenshot = await elementHandle.ScreenshotAsync();270 Assert.True(ScreenshotHelper.PixelMatch("screenshot-element-fractional-offset.png", screenshot));271 }272 [PlaywrightTest("elementhandle-screenshot.spec.ts", "should take screenshots when default viewport is null")]273 public async Task ShouldTakeScreenshotsWhenDefaultViewportIsNull()274 {275 await using var context = await Browser.NewContextAsync(new()276 {277 ViewportSize = ViewportSize.NoViewport278 });279 var page = await context.NewPageAsync();280 await page.SetContentAsync("<div style='height: 10000px; background: red'></div>");281 var windowSize = await page.EvaluateAsync<ViewportSize>("() => ({ width: window.innerWidth * window.devicePixelRatio, height: window.innerHeight * window.devicePixelRatio })");282 var sizeBefore = await page.EvaluateAsync<ViewportSize>("() => ({ width: document.body.offsetWidth, height: document.body.offsetHeight })");283 byte[] screenshot = await page.ScreenshotAsync();284 Assert.NotNull(screenshot);285 var decoded = Image.Load(screenshot);286 Assert.AreEqual(windowSize.Width, decoded.Width);287 Assert.AreEqual(windowSize.Height, decoded.Height);288 var sizeAfter = await page.EvaluateAsync<ViewportSize>("() => ({ width: document.body.offsetWidth, height: document.body.offsetHeight })");289 Assert.AreEqual(sizeBefore.Width, sizeAfter.Width);290 Assert.AreEqual(sizeBefore.Height, sizeAfter.Height);291 }292 [PlaywrightTest("elementhandle-screenshot.spec.ts", "should take fullPage screenshots when default viewport is null")]293 public async Task ShouldTakeFullPageScreenshotsWhenDefaultViewportIsNull()294 {295 await using var context = await Browser.NewContextAsync(new()296 {297 ViewportSize = ViewportSize.NoViewport298 });299 var page = await context.NewPageAsync();300 await page.GotoAsync(Server.Prefix + "/grid.html");301 var sizeBefore = await page.EvaluateAsync<ViewportSize>("() => ({ width: document.body.offsetWidth, height: document.body.offsetHeight })");302 byte[] screenshot = await page.ScreenshotAsync(new() { FullPage = true });303 Assert.NotNull(screenshot);304 var sizeAfter = await page.EvaluateAsync<ViewportSize>("() => ({ width: document.body.offsetWidth, height: document.body.offsetHeight })");305 Assert.AreEqual(sizeBefore.Width, sizeAfter.Width);306 Assert.AreEqual(sizeBefore.Height, sizeAfter.Height);307 }308 [PlaywrightTest("elementhandle-screenshot.spec.ts", "should restore default viewport after fullPage screenshot")]309 public async Task ShouldRestoreDefaultViewportAfterFullPageScreenshot()310 {311 await using var context = await Browser.NewContextAsync(new()312 {313 ViewportSize = new() { Width = 456, Height = 789 },314 });315 var page = await context.NewPageAsync();316 await TestUtils.VerifyViewportAsync(page, 456, 789);317 byte[] screenshot = await page.ScreenshotAsync(new() { FullPage = true });318 Assert.NotNull(screenshot);319 await TestUtils.VerifyViewportAsync(page, 456, 789);320 }321 [PlaywrightTest("elementhandle-screenshot.spec.ts", "should take element screenshot when default viewport is null and restore back")]322 public async Task ShouldTakeElementScreenshotWhenDefaultViewportIsNullAndRestoreBack()323 {324 await using var context = await Browser.NewContextAsync(new()325 {326 ViewportSize = ViewportSize.NoViewport,327 });328 var page = await context.NewPageAsync();329 await page.SetContentAsync(@"330 <div style=""height: 14px"">oooo</div>331 <style>332 div.to-screenshot {333 border: 1px solid blue;334 width: 600px;335 height: 600px;336 margin-left: 50px;337 }338 ::-webkit-scrollbar{339 display: none;340 }341 </style>342 <div class=""to-screenshot""></div>343 <div class=""to-screenshot""></div>344 <div class=""to-screenshot""></div>");345 var sizeBefore = await page.EvaluateAsync<ViewportSize>("() => ({ width: document.body.offsetWidth, height: document.body.offsetHeight })");346 var elementHandle = await page.QuerySelectorAsync("div.to-screenshot");347 byte[] screenshot = await elementHandle.ScreenshotAsync();348 Assert.NotNull(screenshot);349 var sizeAfter = await page.EvaluateAsync<ViewportSize>("() => ({ width: document.body.offsetWidth, height: document.body.offsetHeight })");350 Assert.AreEqual(sizeBefore.Width, sizeAfter.Width);351 Assert.AreEqual(sizeBefore.Height, sizeAfter.Height);352 }353 [PlaywrightTest("elementhandle-screenshot.spec.ts", "should take screenshot of disabled button")]354 public async Task ShouldTakeScreenshotOfDisabledButton()355 {356 await Page.SetViewportSizeAsync(500, 500);357 await Page.SetContentAsync("<button disabled>Click me</button>");358 var button = await Page.QuerySelectorAsync("button");359 byte[] screenshot = await button.ScreenshotAsync();360 Assert.NotNull(screenshot);361 }362 [PlaywrightTest("elementhandle-screenshot.spec.ts", "path option should create subdirectories")]363 public async Task PathOptionShouldCreateSubdirectories()364 {365 await Page.SetViewportSizeAsync(500, 500);366 await Page.GotoAsync(Server.Prefix + "/grid.html");367 await Page.EvaluateAsync("() => window.scrollBy(50, 100)");368 var elementHandle = await Page.QuerySelectorAsync(".box:nth-of-type(3)");369 using var tmpDir = new TempDirectory();370 string outputPath = Path.Combine(tmpDir.Path, "these", "are", "directories", "screenshot.png");371 await elementHandle.ScreenshotAsync(new() { Path = outputPath });372 Assert.True(ScreenshotHelper.PixelMatch("screenshot-element-bounding-box.png", outputPath));373 }374 }375}...

Full Screen

Full Screen

PageScreenshotTests.cs

Source:PageScreenshotTests.cs Github

copy

Full Screen

...38 {39 await Page.SetViewportSizeAsync(500, 500);40 await Page.GotoAsync(Server.Prefix + "/grid.html");41 byte[] screenshot = await Page.ScreenshotAsync();42 Assert.True(ScreenshotHelper.PixelMatch("screenshot-sanity.png", screenshot));43 }44 [PlaywrightTest("page-screenshot.spec.ts", "should clip rect")]45 public async Task ShouldClipRect()46 {47 await Page.SetViewportSizeAsync(500, 500);48 await Page.GotoAsync(Server.Prefix + "/grid.html");49 byte[] screenshot = await Page.ScreenshotAsync(new()50 {51 Clip = new()52 {53 X = 50,54 Y = 100,55 Width = 150,56 Height = 10057 }58 }59 );60 Assert.True(ScreenshotHelper.PixelMatch("screenshot-clip-rect.png", screenshot));61 }62 [PlaywrightTest("page-screenshot.spec.ts", "should clip rect with fullPage")]63 public async Task ShouldClipRectWithFullPage()64 {65 await Page.SetViewportSizeAsync(500, 500);66 await Page.GotoAsync(Server.Prefix + "/grid.html");67 await Page.EvaluateAsync("() => window.scrollBy(150, 200)");68 byte[] screenshot = await Page.ScreenshotAsync(new()69 {70 FullPage = true,71 Clip = new()72 {73 X = 50,74 Y = 100,75 Width = 150,76 Height = 100,77 }78 });79 Assert.True(ScreenshotHelper.PixelMatch("screenshot-clip-rect.png", screenshot));80 }81 [PlaywrightTest("page-screenshot.spec.ts", "should clip elements to the viewport")]82 public async Task ShouldClipElementsToTheViewport()83 {84 await Page.SetViewportSizeAsync(500, 500);85 await Page.GotoAsync(Server.Prefix + "/grid.html");86 byte[] screenshot = await Page.ScreenshotAsync(new()87 {88 Clip = new()89 {90 X = 50,91 Y = 450,92 Width = 1000,93 Height = 100,94 }95 });96 Assert.True(ScreenshotHelper.PixelMatch("screenshot-offscreen-clip.png", screenshot));97 }98 [PlaywrightTest("page-screenshot.spec.ts", "should throw on clip outside the viewport")]99 public async Task ShouldThrowOnClipOutsideTheViewport()100 {101 await Page.SetViewportSizeAsync(500, 500);102 await Page.GotoAsync(Server.Prefix + "/grid.html");103 var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => Page.ScreenshotAsync(new()104 {105 Clip = new()106 {107 X = 50,108 Y = 650,109 Width = 100,110 Height = 100,111 }112 }));113 StringAssert.Contains("Clipped area is either empty or outside the resulting image", exception.Message);114 }115 [PlaywrightTest("page-screenshot.spec.ts", "should run in parallel")]116 public async Task ShouldRunInParallel()117 {118 await Page.SetViewportSizeAsync(500, 500);119 await Page.GotoAsync(Server.Prefix + "/grid.html");120 var tasks = new List<Task<byte[]>>();121 for (int i = 0; i < 3; ++i)122 {123 tasks.Add(Page.ScreenshotAsync(new()124 {125 Clip = new()126 {127 X = 50 * i,128 Y = 0,129 Width = 50,130 Height = 50131 }132 }));133 }134 await TaskUtils.WhenAll(tasks);135 Assert.True(ScreenshotHelper.PixelMatch("grid-cell-1.png", tasks[0].Result));136 }137 [PlaywrightTest("page-screenshot.spec.ts", "should take fullPage screenshots")]138 public async Task ShouldTakeFullPageScreenshots()139 {140 await Page.SetViewportSizeAsync(500, 500);141 await Page.GotoAsync(Server.Prefix + "/grid.html");142 byte[] screenshot = await Page.ScreenshotAsync(new() { FullPage = true });143 Assert.True(ScreenshotHelper.PixelMatch("screenshot-grid-fullpage.png", screenshot));144 }145 [PlaywrightTest("page-screenshot.spec.ts", "should restore viewport after fullPage screenshot")]146 public async Task ShouldRestoreViewportAfterFullPageScreenshot()147 {148 await Page.SetViewportSizeAsync(500, 500);149 await Page.GotoAsync(Server.Prefix + "/grid.html");150 await Page.ScreenshotAsync(new() { FullPage = true });151 Assert.AreEqual(500, Page.ViewportSize.Width);152 Assert.AreEqual(500, Page.ViewportSize.Height);153 }154 [PlaywrightTest("page-screenshot.spec.ts", "should run in parallel in multiple pages")]155 public async Task ShouldRunInParallelInMultiplePages()156 {157 int n = 5;158 var pageTasks = new List<Task<IPage>>();159 for (int i = 0; i < n; i++)160 {161 async Task<IPage> Func()162 {163 var page = await Context.NewPageAsync();164 await page.GotoAsync(Server.Prefix + "/grid.html");165 return page;166 }167 pageTasks.Add(Func());168 }169 await TaskUtils.WhenAll(pageTasks);170 var screenshotTasks = new List<Task<byte[]>>();171 for (int i = 0; i < n; i++)172 {173 screenshotTasks.Add(pageTasks[i].Result.ScreenshotAsync(new()174 {175 Clip = new()176 {177 X = 50 * (i % 2),178 Y = 0,179 Width = 50,180 Height = 50181 }182 }));183 }184 await TaskUtils.WhenAll(screenshotTasks);185 for (int i = 0; i < n; i++)186 {187 Assert.True(ScreenshotHelper.PixelMatch($"grid-cell-{i % 2}.png", screenshotTasks[i].Result));188 }189 var closeTasks = new List<Task>();190 for (int i = 0; i < n; i++)191 {192 closeTasks.Add(pageTasks[i].Result.CloseAsync());193 }194 await TaskUtils.WhenAll(closeTasks);195 }196 [PlaywrightTest("page-screenshot.spec.ts", "should allow transparency")]197 [Skip(SkipAttribute.Targets.Firefox)]198 public async Task ShouldAllowTransparency()199 {200 await Page.SetViewportSizeAsync(50, 150);201 await Page.GotoAsync(Server.EmptyPage);202 byte[] screenshot = await Page.ScreenshotAsync(new() { OmitBackground = true });203 Assert.True(ScreenshotHelper.PixelMatch("transparent.png", screenshot));204 }205 [PlaywrightTest("page-screenshot.spec.ts", "should render white background on jpeg file")]206 public async Task ShouldRenderWhiteBackgroundOnJpegFile()207 {208 await Page.SetViewportSizeAsync(100, 100);209 await Page.GotoAsync(Server.EmptyPage);210 byte[] screenshot = await Page.ScreenshotAsync(new()211 {212 OmitBackground = true,213 Type = ScreenshotType.Jpeg,214 });215 Assert.True(ScreenshotHelper.PixelMatch("white.jpg", screenshot));216 }217 [PlaywrightTest("page-screenshot.spec.ts", "should work with odd clip size on Retina displays")]218 public async Task ShouldWorkWithOddClipSizeOnRetinaDisplays()219 {220 byte[] screenshot = await Page.ScreenshotAsync(new()221 {222 Clip = new()223 {224 X = 0,225 Y = 0,226 Width = 11,227 Height = 11228 }229 });230 Assert.True(ScreenshotHelper.PixelMatch("screenshot-clip-odd-size.png", screenshot));231 }232 [PlaywrightTest("page-screenshot.spec.ts", "should work with a mobile viewport")]233 [Skip(SkipAttribute.Targets.Firefox)]234 public async Task ShouldWorkWithAMobileViewport()235 {236 await using var context = await Browser.NewContextAsync(new()237 {238 ViewportSize = new()239 {240 Width = 320,241 Height = 480,242 },243 IsMobile = true,244 });245 var page = await context.NewPageAsync();246 await page.GotoAsync(Server.Prefix + "/overflow.html");247 byte[] screenshot = await page.ScreenshotAsync();248 Assert.True(ScreenshotHelper.PixelMatch("screenshot-mobile.png", screenshot));249 }250 [PlaywrightTest("page-screenshot.spec.ts", "should work with a mobile viewport and clip")]251 [Skip(SkipAttribute.Targets.Firefox)]252 public async Task ShouldWorkWithAMobileViewportAndClip()253 {254 await using var context = await Browser.NewContextAsync(new()255 {256 ViewportSize = new()257 {258 Width = 320,259 Height = 480,260 },261 IsMobile = true,262 });263 var page = await context.NewPageAsync();264 await page.GotoAsync(Server.Prefix + "/overflow.html");265 byte[] screenshot = await page.ScreenshotAsync(new()266 {267 Clip = new()268 {269 X = 10,270 Y = 10,271 Width = 100,272 Height = 150273 }274 });275 Assert.True(ScreenshotHelper.PixelMatch("screenshot-mobile-clip.png", screenshot));276 }277 [PlaywrightTest("page-screenshot.spec.ts", "should work with a mobile viewport and fullPage")]278 [Skip(SkipAttribute.Targets.Firefox)]279 public async Task ShouldWorkWithAMobileViewportAndFullPage()280 {281 await using var context = await Browser.NewContextAsync(new()282 {283 ViewportSize = new()284 {285 Width = 320,286 Height = 480,287 },288 IsMobile = true,289 });290 var page = await context.NewPageAsync();291 await page.GotoAsync(Server.Prefix + "/overflow-large.html");292 byte[] screenshot = await page.ScreenshotAsync(new() { FullPage = true });293 Assert.True(ScreenshotHelper.PixelMatch("screenshot-mobile-fullpage.png", screenshot));294 }295 [PlaywrightTest("page-screenshot.spec.ts", "should work for canvas")]296 public async Task ShouldWorkForCanvas()297 {298 await Page.SetViewportSizeAsync(500, 500);299 await Page.GotoAsync(Server.Prefix + "/screenshots/canvas.html");300 byte[] screenshot = await Page.ScreenshotAsync();301 Assert.True(ScreenshotHelper.PixelMatch("screenshot-canvas.png", screenshot));302 }303 [PlaywrightTest("page-screenshot.spec.ts", "should work for webgl")]304 [Skip(SkipAttribute.Targets.Firefox, SkipAttribute.Targets.Webkit)]305 public async Task ShouldWorkForWebgl()306 {307 await Page.SetViewportSizeAsync(640, 480);308 await Page.GotoAsync(Server.Prefix + "/screenshots/webgl.html");309 byte[] screenshot = await Page.ScreenshotAsync();310 Assert.True(ScreenshotHelper.PixelMatch("screenshot-webgl.png", screenshot));311 }312 [PlaywrightTest("page-screenshot.spec.ts", "should work for translateZ")]313 public async Task ShouldWorkForTranslateZ()314 {315 await Page.SetViewportSizeAsync(500, 500);316 await Page.GotoAsync(Server.Prefix + "/screenshots/translateZ.html");317 byte[] screenshot = await Page.ScreenshotAsync();318 Assert.True(ScreenshotHelper.PixelMatch("screenshot-translateZ.png", screenshot));319 }320 [PlaywrightTest("page-screenshot.spec.ts", "should work while navigating")]321 public async Task ShouldWorkWhileNavigating()322 {323 await Page.SetViewportSizeAsync(500, 500);324 await Page.GotoAsync(Server.Prefix + "/redirectloop1.html");325 for (int i = 0; i < 10; ++i)326 {327 try328 {329 await Page.ScreenshotAsync();330 }331 catch (Exception ex) when (ex.Message.Contains("Cannot take a screenshot while page is navigating"))332 {333 }334 }335 }336 [PlaywrightTest("page-screenshot.spec.ts", "should work with device scale factor")]337 public async Task ShouldWorkWithDeviceScaleFactor()338 {339 await using var context = await Browser.NewContextAsync(new()340 {341 ViewportSize = new()342 {343 Width = 320,344 Height = 480,345 },346 DeviceScaleFactor = 2,347 });348 var page = await context.NewPageAsync();349 await page.GotoAsync(Server.Prefix + "/grid.html");350 byte[] screenshot = await page.ScreenshotAsync();351 Assert.True(ScreenshotHelper.PixelMatch("screenshot-device-scale-factor.png", screenshot));352 }353 [PlaywrightTest("page-screenshot.spec.ts", "should work with iframe in shadow")]354 public async Task ShouldWorkWithiFrameInShadow()355 {356 await using var context = await Browser.NewContextAsync(new()357 {358 ViewportSize = new()359 {360 Width = 500,361 Height = 500,362 },363 });364 var page = await context.NewPageAsync();365 await page.GotoAsync(Server.Prefix + "/grid-iframe-in-shadow.html");366 byte[] screenshot = await page.ScreenshotAsync();367 Assert.True(ScreenshotHelper.PixelMatch("screenshot-iframe.png", screenshot));368 }369 [PlaywrightTest("page-screenshot.spec.ts", "path option should work")]370 public async Task PathOptionShouldWork()371 {372 await Page.SetViewportSizeAsync(500, 500);373 await Page.GotoAsync(Server.Prefix + "/grid.html");374 using var tmpDir = new TempDirectory();375 string outputPath = Path.Combine(tmpDir.Path, "screenshot.png");376 await Page.ScreenshotAsync(new() { Path = outputPath });377 Assert.True(ScreenshotHelper.PixelMatch("screenshot-sanity.png", outputPath));378 }379 [PlaywrightTest("page-screenshot.spec.ts", "path option should create subdirectories")]380 public async Task PathOptionShouldCreateSubdirectories()381 {382 await Page.SetViewportSizeAsync(500, 500);383 await Page.GotoAsync(Server.Prefix + "/grid.html");384 using var tmpDir = new TempDirectory();385 string outputPath = Path.Combine(tmpDir.Path, "these", "are", "directories", "screenshot.png");386 await Page.ScreenshotAsync(new() { Path = outputPath });387 Assert.True(ScreenshotHelper.PixelMatch("screenshot-sanity.png", outputPath));388 }389 [PlaywrightTest("page-screenshot.spec.ts", "path option should detect joeg")]390 public async Task PathOptionShouldDetectJpeg()391 {392 await Page.SetViewportSizeAsync(100, 100);393 await Page.GotoAsync(Server.EmptyPage);394 using var tmpDir = new TempDirectory();395 string outputPath = Path.Combine(tmpDir.Path, "screenshot.jpg");396 await Page.ScreenshotAsync(new() { Path = outputPath, OmitBackground = true });397 Assert.True(ScreenshotHelper.PixelMatch("white.jpg", outputPath));398 }399 [PlaywrightTest("page-screenshot.spec.ts", "path option should throw for unsupported mime type")]400 public async Task PathOptionShouldThrowForUnsupportedMimeType()401 {402 var exception = await PlaywrightAssert.ThrowsAsync<ArgumentException>(() => Page.ScreenshotAsync(new() { Path = "file.txt" }));403 StringAssert.Contains("path: unsupported mime type \"text/plain\"", exception.Message);404 }405 }406}...

Full Screen

Full Screen

PageRequestFulfillTests.cs

Source:PageRequestFulfillTests.cs Github

copy

Full Screen

...91 document.body.appendChild(img);92 return new Promise(fulfill => img.onload = fulfill);93 }", Server.Prefix);94 var img = await Page.QuerySelectorAsync("img");95 Assert.True(ScreenshotHelper.PixelMatch("mock-binary-response.png", await img.ScreenshotAsync()));96 }97 [PlaywrightTest("page-request-fulfill.spec.ts", "should allow mocking svg with charset")]98 [Ignore("We need screenshots for this")]99 public void ShouldAllowMockingSvgWithCharset()100 {101 }102 [PlaywrightTest("page-request-fulfill.spec.ts", "should work with file path")]103 [Ignore("We need screenshots for this")]104 public async Task ShouldWorkWithFilePath()105 {106 await Page.RouteAsync("**/*", (route) =>107 {108 route.FulfillAsync(new()109 {110 ContentType = "shouldBeIgnored",111 Path = TestUtils.GetAsset("pptr.png"),112 });113 });114 await Page.EvaluateAsync(@"PREFIX => {115 const img = document.createElement('img');116 img.src = PREFIX + '/does-not-exist.png';117 document.body.appendChild(img);118 return new Promise(fulfill => img.onload = fulfill);119 }", Server.Prefix);120 var img = await Page.QuerySelectorAsync("img");121 Assert.True(ScreenshotHelper.PixelMatch("mock-binary-response.png", await img.ScreenshotAsync()));122 }123 [PlaywrightTest("page-request-fulfill.spec.ts", "should stringify intercepted request response headers")]124 public async Task ShouldStringifyInterceptedRequestResponseHeaders()125 {126 await Page.RouteAsync("**/*", (route) =>127 {128 route.FulfillAsync(new()129 {130 Status = (int)HttpStatusCode.OK,131 Headers = new Dictionary<string, string>132 {133 ["foo"] = "true"134 },135 Body = "Yo, page!",...

Full Screen

Full Screen

ScreenshotHelper.cs

Source:ScreenshotHelper.cs Github

copy

Full Screen

...28namespace Microsoft.Playwright.Tests29{30 internal class ScreenshotHelper31 {32 internal static bool PixelMatch(string screenShotFile, string fileName)33 => PixelMatch(screenShotFile, File.ReadAllBytes(fileName));34 internal static bool PixelMatch(string screenShotFile, byte[] screenshot)35 {36 const int pixelThreshold = 10;37 const decimal totalTolerance = 0.05m;38 var baseImage = Image.Load<Rgb24>(Path.Combine(TestUtils.FindParentDirectory("Screenshots"), TestConstants.BrowserName, screenShotFile));39 var compareImage = Image.Load<Rgb24>(screenshot);40 //Just for debugging purpose41 compareImage.Save(Path.Combine(TestUtils.FindParentDirectory("Screenshots"), TestConstants.BrowserName, "test.png"));42 if (baseImage.Width != compareImage.Width || baseImage.Height != compareImage.Height)43 {44 return false;45 }46 int invalidPixelsCount = 0;47 for (int y = 0; y < baseImage.Height; y++)48 {...

Full Screen

Full Screen

PixelMatch

Using AI Code Generation

copy

Full Screen

1using Microsoft.Playwright;2using Microsoft.Playwright.Helpers;3using Microsoft.Playwright.Tests;4using System;5using System.IO;6using System.Threading.Tasks;7{8 {9 static async Task Main(string[] args)10 {11 using var playwright = await Playwright.CreateAsync();12 using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions13 {14 });15 using var context = await browser.NewContextAsync();16 var page = await context.NewPageAsync();17 var screenshot = await page.ScreenshotAsync();18 await File.WriteAllBytesAsync("google.png", screenshot);19 var screenshot1 = await page.ScreenshotAsync();20 await File.WriteAllBytesAsync("google1.png", screenshot1);21 var result = ScreenshotHelper.PixelMatch(screenshot, screenshot1);22 Console.WriteLine(result);23 }24 }25}

Full Screen

Full Screen

PixelMatch

Using AI Code Generation

copy

Full Screen

1using Microsoft.Playwright;2using System;3using System.IO;4using System.Linq;5using System.Reflection;6using System.Text.RegularExpressions;7using System.Threading.Tasks;8{9 {10 static async Task Main(string[] args)11 {12 var playwright = await Playwright.CreateAsync();13 var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions14 {15 });16 var context = await browser.NewContextAsync();17 var page = await context.NewPageAsync();18 await page.ScreenshotAsync(new PageScreenshotOptions { Path = "google.png" });19 await page.ScreenshotAsync(new PageScreenshotOptions { Path = "bing.png" });20 var result = ScreenshotHelper.PixelMatch("google.png", "bing.png", 0.1, out int diff);21 Console.WriteLine($"Result: {result}, Diff: {diff}");22 }23 }24}25using System;26using System.Drawing;27using System.Drawing.Imaging;28using System.IO;29using System.Linq;30using System.Reflection;31using System.Text.RegularExpressions;32using System.Threading.Tasks;33{34 {35 public static bool PixelMatch(string a, string b, double threshold, out int diff)36 {37 using var image1 = Image.FromFile(a);38 using var image2 = Image.FromFile(b);39 diff = 0;40 if (image1.Width != image2.Width || image1.Height != image2.Height)41 {42 return false;43 }44 var bitmap1 = new Bitmap(image1);45 var bitmap2 = new Bitmap(image2);46 for (var x = 0; x < image1.Width; x++)47 {48 for (var y = 0; y < image1.Height; y++)49 {50 var color1 = bitmap1.GetPixel(x, y);51 var color2 = bitmap2.GetPixel(x, y);52 if (color1.A == color2.A && color1.R == color2.R && color1.G == color2.G && color1.B == color2.B)53 {54 continue;55 }

Full Screen

Full Screen

PixelMatch

Using AI Code Generation

copy

Full Screen

1using Microsoft.Playwright;2using System;3using System.Threading.Tasks;4{5 {6 static async Task Main(string[] args)7 {8 await using var playwright = await Playwright.CreateAsync();9 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions10 {11 });12 var context = await browser.NewContextAsync();13 var page = await context.NewPageAsync();14 await page.ScreenshotAsync("google.png");15 var result = ScreenshotHelper.PixelMatch("google.png", "google.png");16 Console.WriteLine(result);17 }18 }19}20using Microsoft.Playwright;21using System;22using System.Threading.Tasks;23{24 {25 static async Task Main(string[] args)26 {27 await using var playwright = await Playwright.CreateAsync();28 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions29 {30 });31 var context = await browser.NewContextAsync();32 var page = await context.NewPageAsync();33 await page.ScreenshotAsync("google.png");34 var result = ScreenshotHelper.PixelMatch("google.png", "google.png");35 Console.WriteLine(result);36 }37 }38}39using Microsoft.Playwright;40using System;41using System.Threading.Tasks;42{43 {44 static async Task Main(string[] args)45 {46 await using var playwright = await Playwright.CreateAsync();47 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions48 {49 });50 var context = await browser.NewContextAsync();51 var page = await context.NewPageAsync();52 await page.ScreenshotAsync("google.png");

Full Screen

Full Screen

PixelMatch

Using AI Code Generation

copy

Full Screen

1using Microsoft.Playwright;2using Microsoft.Playwright.Tests;3using System;4using System.IO;5{6 {7 static void Main(string[] args)8 {9 var path = Directory.GetCurrentDirectory();10 var pathToImage1 = Path.Combine(path, "image1.png");11 var pathToImage2 = Path.Combine(path, "image2.png");12 var pathToImage3 = Path.Combine(path, "image3.png");13 var pathToImage4 = Path.Combine(path, "image4.png");14 var pathToImage5 = Path.Combine(path, "image5.png");15 var pathToImage6 = Path.Combine(path, "image6.png");16 var pathToImage7 = Path.Combine(path, "image7.png");17 var pathToImage8 = Path.Combine(path, "image8.png");18 var pathToImage9 = Path.Combine(path, "image9.png");19 var pathToImage10 = Path.Combine(path, "image10.png");20 var pathToImage11 = Path.Combine(path, "image11.png");21 var pathToImage12 = Path.Combine(path, "image12.png");22 var pathToImage13 = Path.Combine(path, "image13.png");23 var pathToImage14 = Path.Combine(path, "image14.png");24 var pathToImage15 = Path.Combine(path, "image15.png");25 var pathToImage16 = Path.Combine(path, "image16.png");26 var pathToImage17 = Path.Combine(path, "image17.png");27 var pathToImage18 = Path.Combine(path, "image18.png");28 var pathToImage19 = Path.Combine(path, "image19.png");29 var pathToImage20 = Path.Combine(path, "image20.png");30 var pathToImage21 = Path.Combine(path, "image21.png");31 var pathToImage22 = Path.Combine(path, "image22.png");32 var pathToImage23 = Path.Combine(path, "image23.png");33 var pathToImage24 = Path.Combine(path, "image24.png");34 var pathToImage25 = Path.Combine(path, "image25.png");35 var pathToImage26 = Path.Combine(path, "image26.png");36 var pathToImage27 = Path.Combine(path, "image27.png");

Full Screen

Full Screen

PixelMatch

Using AI Code Generation

copy

Full Screen

1using System;2using System.Collections.Generic;3using System.Drawing;4using System.Drawing.Imaging;5using System.IO;6using System.Linq;7using System.Text;8using System.Threading.Tasks;9{10 {11 public static bool PixelMatch(string file1, string file2, double threshold = 0.01)12 {13 using (var bitmap1 = new Bitmap(file1))14 using (var bitmap2 = new Bitmap(file2))15 {16 if (bitmap1.Width != bitmap2.Width || bitmap1.Height != bitmap2.Height)17 {18 return false;19 }20 int total = 0;21 int different = 0;22 for (int x = 0; x < bitmap1.Width; x++)23 {24 for (int y = 0; y < bitmap1.Height; y++)25 {26 total++;27 var color1 = bitmap1.GetPixel(x, y);28 var color2 = bitmap2.GetPixel(x, y);29 if (color1.A != color2.A || color1.R != color2.R || color1.G != color2.G || color1.B != color2.B)30 {31 different++;32 }33 }34 }35 return different / (double)total <= threshold;36 }37 }38 }39}

Full Screen

Full Screen

PixelMatch

Using AI Code Generation

copy

Full Screen

1using Microsoft.Playwright;2{3 {4 public static async Task Main(string[] args)5 {6 using var playwright = await Playwright.CreateAsync();7 await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions8 {9 });10 await using var context = await browser.NewContextAsync(new BrowserNewContextOptions11 {12 ViewportSize = new() { Width = 1920, Height = 1080 },13 });14 var page = await context.NewPageAsync();15 await page.ScreenshotAsync(new PageScreenshotOptions16 {17 });18 var result = ScreenshotHelper.PixelMatch("C:/Users/lenovo/Desktop/Playwright/PlaywrightTests/Screenshots/Actual/1.png", "C:/Users/lenovo/Desktop/Playwright/PlaywrightTests/Screenshots/Expected/1.png", 0.1);19 System.Console.WriteLine(result);20 }21 }22}23using System;24using System.Drawing;25using System.Drawing.Imaging;26using System.IO;27{28 {29 public static bool PixelMatch(string actualScreenshotPath, string expectedScreenshotPath, double threshold = 0.1)30 {31 if (!File.Exists(actualScreenshotPath))32 {33 throw new FileNotFoundException($"Actual screenshot file was not found at {actualScreenshotPath}");34 }35 if (!File.Exists(expectedScreenshotPath))36 {37 throw new FileNotFoundException($"Expected screenshot file was not found at {expectedScreenshotPath}");38 }39 using var actualScreenshot = new Bitmap(actualScreenshotPath);40 using var expectedScreenshot = new Bitmap(expectedScreenshotPath);41 if (actualScreenshot.Size != expectedScreenshot.Size)42 {43 throw new InvalidOperationException($"The images are different sizes. Actual:

Full Screen

Full Screen

PixelMatch

Using AI Code Generation

copy

Full Screen

1var image1 = "firstimage.png";2var image2 = "secondimage.png";3var result = ScreenshotHelper.PixelMatch(image1, image2);4Console.WriteLine(result);5Console.WriteLine("Press any key to exit");6Console.ReadLine();

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 method in ScreenshotHelper

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful