How to use PuppeteerTestAttribute class of PuppeteerSharp.Xunit package

Best Puppeteer-sharp code snippet using PuppeteerSharp.Xunit.PuppeteerTestAttribute

ScaffoldTest.cs

Source:ScaffoldTest.cs Github

copy

Full Screen

...90 var fileInfo = new FileInfo(options.SpecFile);91 var dotSeparator = fileInfo.Name.IndexOf('.');92 var name = _textInfo.ToTitleCase(fileInfo.Name.Substring(0, dotSeparator)) + "Tests";93 var targetClass = GenerateClass(options.Namespace, name, fileInfo.Name);94 FindTestsInFile(options.SpecFile, (describe, testName) => AddTest(targetClass, new PuppeteerTestAttribute(fileInfo.Name, describe, testName)));95 using var provider = CodeDomProvider.CreateProvider("CSharp");96 var codegenOptions = new CodeGeneratorOptions()97 {98 BracingStyle = "C",99 };100 using var sourceWriter = new StreamWriter(options.OutputFile);101 provider.GenerateCodeFromCompileUnit(102 targetClass, sourceWriter, codegenOptions);103 }104 private static CodeCompileUnit GenerateClass(string @namespace, string @class, string fileOrigin)105 {106 var targetUnit = new CodeCompileUnit();107 var globalNamespace = new CodeNamespace();108 // add imports109 globalNamespace.Imports.Add(new CodeNamespaceImport("System.Threading.Tasks"));110 globalNamespace.Imports.Add(new CodeNamespaceImport("PuppeteerSharp.Tests.BaseTests"));111 globalNamespace.Imports.Add(new CodeNamespaceImport("Xunit"));112 globalNamespace.Imports.Add(new CodeNamespaceImport("Xunit.Abstractions"));113 targetUnit.Namespaces.Add(globalNamespace);114 var codeNamespace = new CodeNamespace(@namespace);115 var targetClass = new CodeTypeDeclaration(@class)116 {117 IsClass = true,118 TypeAttributes = System.Reflection.TypeAttributes.Public | System.Reflection.TypeAttributes.Sealed,119 };120 targetClass.BaseTypes.Add(new CodeTypeReference("PuppeteerSharpPageBaseTest"));121 _ = targetClass.CustomAttributes.Add(new CodeAttributeDeclaration(122 "Collection",123 new CodeAttributeArgument[]124 {125 new CodeAttributeArgument(126 new CodeFieldReferenceExpression(127 new CodeTypeReferenceExpression("TestConstants"),128 "TestFixtureBrowserCollectionName")),129 }));130 targetClass.Comments.Add(new CodeCommentStatement($"<puppeteer-file>{fileOrigin}</puppeteer-file>", true));131 codeNamespace.Types.Add(targetClass);132 targetUnit.Namespaces.Add(codeNamespace);133 // add constructor134 var constructor = new CodeConstructor()135 {136 Attributes = MemberAttributes.Public,137 };138 constructor.Parameters.Add(new CodeParameterDeclarationExpression("ITestOutputHelper", "output"));139 constructor.BaseConstructorArgs.Add(new CodeVariableReferenceExpression("output"));140 constructor.Comments.Add(new CodeCommentStatement("<inheritdoc/>", true));141 targetClass.Members.Add(constructor);142 return targetUnit;143 }144 private static void AddTest(CodeCompileUnit @class, PuppeteerTestAttribute test)145 {146 // make name out of the describe, and we should ignore any whitespaces, hyphens, etc.147 var name = CleanName(test.TestName);148 Console.WriteLine($"Adding {name}");149 var method = new CodeMemberMethod()150 {151 Attributes = MemberAttributes.Public | MemberAttributes.Final,152 ReturnType = new CodeTypeReference("async Task"),153 Name = name,154 };155 @class.Namespaces[1].Types[0].Members.Add(method);156 method.Comments.Add(new CodeCommentStatement($"<puppeteer-file>{test.FileName}</puppeteer-file>", true));157 if (test.Describe != null)158 {...

Full Screen

Full Screen

IdentifyMissingTests.cs

Source:IdentifyMissingTests.cs Github

copy

Full Screen

...33 /// This will identify missing tests from upstream.34 /// </summary>35 internal static class IdentifyMissingTests36 {37 private static readonly List<PuppeteerTestAttribute> _testPairs = new();38 /// <summary>39 /// Runs the scenario.40 /// </summary>41 /// <param name="options">The options argument.</param>42 public static void Run(IdentifyMissingTestsOptions options)43 {44 // get all files that match a pattern45 var directoryInfo = new DirectoryInfo(options.SpecFileLocations);46 if (!directoryInfo.Exists)47 {48 throw new ArgumentException($"The location ({directoryInfo.FullName}) specified does not exist.");49 }50 // let's map the test cases from the spec files51 MapTestsCases(directoryInfo, options, string.Empty);52 // now, let's load the DLL and use some reflection-fu53 var assembly = Assembly.LoadFrom(options.TestsAssemblyPath);54 var attributes = assembly.DefinedTypes.SelectMany(55 type => type.GetMethods().SelectMany(method => method.GetCustomAttributes<PuppeteerTestAttribute>()));56 var potentialMatches = 0;57 var fullMatches = 0;58 var noMatches = 0;59 var totalTests = 0;60 List<PuppeteerTestAttribute> missingTests = new();61 List<KeyValuePair<PuppeteerTestAttribute, List<PuppeteerTestAttribute>>> invalidMaps = new();62 foreach (var x in _testPairs)63 {64 totalTests++;65 // a test can either be a full match, a partial (i.e. just the test name) or no match66 var potentialMatch = attributes.Where(atx => string.Equals(x.TestName, atx.TestName, StringComparison.InvariantCultureIgnoreCase))67 .Where(atx => string.Equals(x.Describe, atx.Describe, StringComparison.InvariantCultureIgnoreCase));68 if (!potentialMatch.Any())69 {70 noMatches++;71 missingTests.Add(x);72 }73 else if (potentialMatch.Any(atx => string.Equals(x.TrimmedName, atx.TrimmedName, StringComparison.InvariantCultureIgnoreCase)))74 {75 fullMatches++;76 continue;77 }78 else79 {80 invalidMaps.Add(new KeyValuePair<PuppeteerTestAttribute, List<PuppeteerTestAttribute>>(x, potentialMatch.ToList()));81 potentialMatches++;82 }83 }84 Console.ForegroundColor = ConsoleColor.Green;85 Console.WriteLine($"Total matching tests: {fullMatches}/{totalTests}.");86 Console.ResetColor();87 Console.ForegroundColor = ConsoleColor.Yellow;88 Console.WriteLine($"Total tests found by name, but not by file: {potentialMatches}/{totalTests}.");89 Console.ResetColor();90 foreach (var invalidTest in invalidMaps)91 {92 Console.WriteLine($"{invalidTest.Key}");93 foreach (var value in invalidTest.Value)94 {95 Console.WriteLine($"\t{value}");96 }97 }98 Console.ForegroundColor = ConsoleColor.Red;99 Console.WriteLine($"Total missing tests: {noMatches}/{totalTests}.");100 Console.ResetColor();101 foreach (var invalidTest in missingTests)102 {103 Console.WriteLine($"{invalidTest}");104 }105 Console.WriteLine($"Found/Mismatched/Missing: {fullMatches}/{potentialMatches}/{noMatches} out of {totalTests}");106 }107 private static void MapTestsCases(DirectoryInfo directoryInfo, IdentifyMissingTestsOptions options, string basePath)108 {109 // get the sub-directories110 if (options.Recursive)111 {112 foreach (var subdirectory in directoryInfo.GetDirectories())113 {114 MapTestsCases(subdirectory, options, $"{basePath}{subdirectory.Name}/");115 }116 }117 foreach (var fileInfo in directoryInfo.GetFiles(options.Pattern))118 {119 if (!fileInfo.FullName.Contains("experimental"))120 {121 ScaffoldTest.FindTestsInFile(122 fileInfo.FullName,123 (testDescribe, testName) =>124 {125 _testPairs.Add(new PuppeteerTestAttribute(basePath + fileInfo.Name, testDescribe, testName));126 });127 }128 }129 }130 }131}...

Full Screen

Full Screen

PuppeteerTestAttribute.cs

Source:PuppeteerTestAttribute.cs Github

copy

Full Screen

...4 /// <summary>5 /// Enables decorating test facts with information about the corresponding test in the upstream repository.6 /// </summary>7 [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]8 public class PuppeteerTestAttribute : Attribute9 {10 /// <summary>11 /// Creates a new instance of the attribute.12 /// </summary>13 /// <param name="fileName"><see cref="FileName"/></param>14 /// <param name="nameOfTest"><see cref="TestName"/></param>15 public PuppeteerTestAttribute(string fileName, string nameOfTest)16 {17 FileName = fileName;18 TestName = nameOfTest;19 }20 /// <summary>21 /// Creates a new instance of the attribute.22 /// </summary>23 /// <param name="fileName"><see cref="FileName"/></param>24 /// <param name="describe"><see cref="Describe"/></param>25 /// <param name="nameOfTest"><see cref="TestName"/></param>26 public PuppeteerTestAttribute(string fileName, string describe, string nameOfTest) : this(fileName, nameOfTest)27 {28 Describe = describe;29 }30 /// <summary>31 /// The file name origin of the test.32 /// </summary>33 public string FileName { get; }34 /// <summary>35 /// Returns the trimmed file name.36 /// </summary>37 public string TrimmedName => FileName.Substring(0, FileName.IndexOf('.'));38 /// <summary>39 /// The name of the test, the decorated code is based on.40 /// </summary>...

Full Screen

Full Screen

PuppeteerTestAttribute

Using AI Code Generation

copy

Full Screen

1using PuppeteerSharp.Xunit;2using Xunit;3{4 [Collection("PuppeteerLoaderFixture collection")]5 {6 [PuppeteerTest("page.spec.ts", "Page.close", "should reject all promises when page is closed")]7 [Fact(Timeout = TestConstants.DefaultTestTimeout)]8 public async Task ShouldRejectAllPromisesWhenPageIsClosed()9 {10 await Page.GoToAsync(TestConstants.EmptyPage);11 var (popupTarget, _) = await TaskUtils.WhenAll(12 Page.WaitForTargetAsync(TestConstants.EmptyPage),13 Page.EvaluateFunctionHandleAsync("url => window.open(url)", TestConstants.EmptyPage)14 );15 var popup = await popupTarget.PageAsync();16 var neverResolves = popup.WaitForFunctionAsync("() => new Promise(r => {})");17 var consolePromise = popup.EvaluateFunctionAsync("() => new Promise(r => {})");18 await TaskUtils.WhenAll(19 popup.CloseAsync(),20 );21 var exception = await Assert.ThrowsAsync<Exception>(() => neverResolves);22 Assert.Contains("Protocol error", exception.Message);23 exception = await Assert.ThrowsAsync<Exception>(() => consolePromise);24 Assert.Contains("Protocol error", exception.Message);25 }26 }27}28using PuppeteerSharp.Xunit;29using Xunit;30{31 [Collection("PuppeteerLoaderFixture collection")]32 {33 [PuppeteerTest("page.spec.ts", "Page.close", "should reject all promises when page is closed")]34 [Fact(Timeout = TestConstants.DefaultTestTimeout)]35 public async Task ShouldRejectAllPromisesWhenPageIsClosed()36 {37 await Page.GoToAsync(TestConstants.EmptyPage);38 var (popupTarget, _) = await TaskUtils.WhenAll(39 Page.WaitForTargetAsync(TestConstants.EmptyPage),40 Page.EvaluateFunctionHandleAsync("url => window.open(url)", TestConstants.EmptyPage)41 );42 var popup = await popupTarget.PageAsync();43 var neverResolves = popup.WaitForFunctionAsync("() => new Promise(r =>

Full Screen

Full Screen

PuppeteerTestAttribute

Using AI Code Generation

copy

Full Screen

1using System.Threading.Tasks;2using PuppeteerSharp.Xunit;3using Xunit;4{5 {6 public async Task ShouldWorkWithNoBrowserInstance(Browser browser, Page page)7 {8 Assert.Equal("Example Domain", await page.GetTitleAsync());9 }10 public async Task ShouldWorkWithNoBrowserInstance2(Browser browser, Page page)11 {12 Assert.Equal("Example Domain", await page.GetTitleAsync());13 }14 }15}16using System.Threading.Tasks;17using PuppeteerSharp.Xunit;18using Xunit;19{20 {21 public async Task ShouldWorkWithNoBrowserInstance(Browser browser, Page page)22 {23 Assert.Equal("Example Domain", await page.GetTitleAsync());24 }25 public async Task ShouldWorkWithNoBrowserInstance2(Browser browser, Page page)26 {27 Assert.Equal("Example Domain", await page.GetTitleAsync());28 }29 }30}31using System.Threading.Tasks;32using PuppeteerSharp.Xunit;33using Xunit;34{35 {36 public async Task ShouldWorkWithNoBrowserInstance(Browser browser, Page page)37 {38 Assert.Equal("Example Domain", await page.GetTitleAsync());39 }40 public async Task ShouldWorkWithNoBrowserInstance2(Browser browser, Page page)41 {42 Assert.Equal("Example Domain", await page

Full Screen

Full Screen

PuppeteerTestAttribute

Using AI Code Generation

copy

Full Screen

1using PuppeteerSharp.Xunit;2using Xunit;3{4 {5 public async Task Test1()6 {7 await Page.ScreenshotAsync("google.png");8 }9 }10}

Full Screen

Full Screen

PuppeteerTestAttribute

Using AI Code Generation

copy

Full Screen

1using PuppeteerSharp.Xunit;2using Xunit;3{4 {5 public PuppeteerTestAttribute(string browserType) : base(browserType)6 {7 }8 }9}10using PuppeteerSharp.Xunit;11using Xunit;12{13 {14 public PuppeteerTestAttribute(string browserType) : base(browserType)15 {16 }17 }18}19using PuppeteerSharp.Xunit;20using Xunit;21{22 {23 public PuppeteerTestAttribute(string browserType) : base(browserType)24 {25 }26 }27}28using PuppeteerSharp.Xunit;29using Xunit;30{31 {32 public PuppeteerTestAttribute(string browserType) : base(browserType)33 {34 }35 }36}37using PuppeteerSharp.Xunit;38using Xunit;39{40 {41 public PuppeteerTestAttribute(string browserType) : base(browserType)42 {43 }44 }45}46using PuppeteerSharp.Xunit;47using Xunit;48{49 {50 public PuppeteerTestAttribute(string browserType) : base(browserType)51 {52 }53 }54}55using PuppeteerSharp.Xunit;56using Xunit;57{

Full Screen

Full Screen

PuppeteerTestAttribute

Using AI Code Generation

copy

Full Screen

1using System;2using System.IO;3using System.Threading.Tasks;4using PuppeteerSharp.Xunit;5using Xunit;6{7 {8 public PuppeteerTestAttribute(string launchType, string product = null) : base(launchType, product)9 {10 }11 public override Task InitializeAsync()12 {13 return Task.CompletedTask;14 }15 public override Task DisposeAsync()16 {17 return Task.CompletedTask;18 }19 }20 {21 [PuppeteerTest("chromium")]22 public async Task Test1()23 {24 await Page.ScreenshotAsync(Path.Combine(Directory.GetCurrentDirectory(), "google.png"));25 Console.WriteLine("Test1");26 }27 [PuppeteerTest("chromium")]28 public async Task Test2()29 {30 await Page.ScreenshotAsync(Path.Combine(Directory.GetCurrentDirectory(), "yahoo.png"));31 Console.WriteLine("Test2");32 }33 }34}35using System;36using System.IO;37using System.Threading.Tasks;38using NUnit.Framework;39using PuppeteerSharp.Xunit;40{41 {42 public PuppeteerTestAttribute(string launchType, string product = null) : base(launchType, product)43 {44 }45 public override Task InitializeAsync()46 {47 return Task.CompletedTask;48 }49 public override Task DisposeAsync()50 {51 return Task.CompletedTask;52 }53 }54 {55 [PuppeteerTest("chromium")]56 public async Task Test1()57 {58 await Page.ScreenshotAsync(Path.Combine(Directory.GetCurrentDirectory(), "google.png"));59 Console.WriteLine("Test1");60 }61 [PuppeteerTest("chromium")]62 public async Task Test2()63 {64 await Page.GoToAsync("http

Full Screen

Full Screen

PuppeteerTestAttribute

Using AI Code Generation

copy

Full Screen

1{2 {3 public Browser Browser { get; set; }4 public Page Page { get; set; }5 public string OutputDirectory { get; set; }6 public PuppeteerLoaderFixture()7 {8 if (Puppeteer.IsSupported)9 {10 Browser = Puppeteer.LaunchAsync(new LaunchOptions11 {12 Args = new[] { "--no-sandbox", "--disable-setuid-sandbox" }13 }).Result;14 Page = Browser.NewPageAsync().Result;15 OutputDirectory = Path.Combine(Directory.GetCurrentDirectory(), "output");16 if (!Directory.Exists(OutputDirectory))17 {18 Directory.CreateDirectory(OutputDirectory);19 }20 }21 }22 public void Dispose()23 {24 if (Puppeteer.IsSupported)25 {26 Page.CloseAsync().Wait();27 Browser.CloseAsync().Wait();28 }29 }30 }31}32{33 [CollectionDefinition("PuppeteerLoaderFixture collection")]34 {35 }36}37{38 [Collection("PuppeteerLoaderFixture collection")]39 {40 public PuppeteerTestAttribute()41 {42 Skip = "PuppeteerSharp is not supported on this platform";43 }44 }45}

Full Screen

Full Screen

PuppeteerTestAttribute

Using AI Code Generation

copy

Full Screen

1using PuppeteerSharp;2using PuppeteerSharp.Xunit;3using Xunit;4using Xunit.Abstractions;5{6 {7 public async Task Test(PuppeteerSharpContext context)8 {9 var page = context.Page;10 await page.ScreenshotAsync("google.png");11 }12 }13}14using PuppeteerSharp;15using PuppeteerSharp.Xunit;16using Xunit;17using Xunit.Abstractions;18{19 {20 public async Task Test(PuppeteerSharpContext context)21 {22 var page = context.Page;23 await page.ScreenshotAsync("google.png");24 }25 }26}27using PuppeteerSharp;28using PuppeteerSharp.Xunit;29using Xunit;30using Xunit.Abstractions;31{32 {33 public async Task Test(PuppeteerSharpContext context)34 {35 var page = context.Page;36 await page.ScreenshotAsync("google.png");37 }38 }39}40using PuppeteerSharp;41using PuppeteerSharp.Xunit;42using Xunit;43using Xunit.Abstractions;44{45 {46 public async Task Test(PuppeteerSharpContext context)47 {48 var page = context.Page;

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Puppeteer-sharp automation tests on LambdaTest cloud grid

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

Most used methods in PuppeteerTestAttribute

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful