How to use PlaywrightTestAttribute method of Microsoft.Playwright.Tests.PlaywrightTestAttribute class

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

Run Playwright-dotnet automation tests on LambdaTest cloud grid

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

PlaywrightTestAttribute.cs

Source: PlaywrightTestAttribute.cs Github

copy
1/*
2 * MIT License
3 *
4 * Copyright (c) Microsoft Corporation.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 * SOFTWARE.
23 */
24
25using System;
26using System.Collections.Generic;
27using System.Threading.Tasks;
28using NUnit.Framework;
29using NUnit.Framework.Interfaces;
30using NUnit.Framework.Internal;
31using NUnit.Framework.Internal.Commands;
32
33// Run all tests in sequence
34[assembly: LevelOfParallelism(1)]
35
36namespace Microsoft.Playwright.Tests
37{
38    /// <summary>
39    /// Enables decorating test facts with information about the corresponding test in the upstream repository.
40    /// </summary>
41    [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
42    public class PlaywrightTestAttribute : TestAttribute, IWrapSetUpTearDown
43    {
44        public PlaywrightTestAttribute()
45        {
46        }
47
48        /// <summary>
49        /// Creates a new instance of the attribute.
50        /// </summary>
51        /// <param name="fileName"><see cref="FileName"/></param>
52        /// <param name="nameOfTest"><see cref="TestName"/></param>
53        public PlaywrightTestAttribute(string fileName, string nameOfTest)
54        {
55            FileName = fileName;
56            TestName = nameOfTest;
57        }
58
59        /// <summary>
60        /// Creates a new instance of the attribute.
61        /// </summary>
62        /// <param name="fileName"><see cref="FileName"/></param>
63        /// <param name="describe"><see cref="Describe"/></param>
64        /// <param name="nameOfTest"><see cref="TestName"/></param>
65        public PlaywrightTestAttribute(string fileName, string describe, string nameOfTest) : this(fileName, nameOfTest)
66        {
67            Describe = describe;
68        }
69
70        /// <summary>
71        /// The file name origin of the test.
72        /// </summary>
73        public string FileName { get; }
74
75        /// <summary>
76        /// Returns the trimmed file name.
77        /// </summary>
78        public string TrimmedName => FileName.Substring(0, FileName.IndexOf('.'));
79
80        /// <summary>
81        /// The name of the test, the decorated code is based on.
82        /// </summary>
83        public string TestName { get; }
84
85        /// <summary>
86        /// The describe of the test, the decorated code is based on, if one exists.
87        /// </summary>
88        public string Describe { get; }
89
90        /// <summary>
91        /// Wraps the current test command in a <see cref="UnobservedTaskExceptionCommand"/>.
92        /// </summary>
93        /// <param name="command">the test command</param>
94        /// <returns>the wrapped test command</returns>
95        public TestCommand Wrap(TestCommand command)
96            => new UnobservedTaskExceptionCommand(command);
97
98        /// <summary>
99        /// Helper to detect UnobservedTaskExceptions
100        /// </summary>
101        private sealed class UnobservedTaskExceptionCommand : DelegatingTestCommand
102        {
103            public UnobservedTaskExceptionCommand(TestCommand innerCommand)
104                : base(innerCommand)
105            {
106            }
107
108            private readonly List<Exception> _unobservedTaskExceptions = new();
109
110            public override TestResult Execute(TestExecutionContext context)
111            {
112                TaskScheduler.UnobservedTaskException += UnobservedTaskException;
113                TestResult result = null;
114                try
115                {
116                    result = innerCommand.Execute(context);
117                }
118                finally
119                {
120                    // force a GC and wait for finalizers of (among other things) Tasks
121                    // for which the UnobservedTaskException is raised if the task.Exception was not observed 
122                    GC.Collect();
123                    GC.WaitForPendingFinalizers();
124
125                    TaskScheduler.UnobservedTaskException -= UnobservedTaskException;
126
127                    if (_unobservedTaskExceptions.Count > 0)
128                    {
129                        result.RecordTearDownException(new AggregateException(_unobservedTaskExceptions));
130                        _unobservedTaskExceptions.Clear();
131                    }
132                }
133                return result;
134            }
135
136            private void UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
137            {
138                _unobservedTaskExceptions.Add(e.Exception);
139            }
140        }
141    }
142}
143
Full Screen

IdentifyMissingTests.cs

Source: IdentifyMissingTests.cs Github

copy
1/*
2 * MIT License
3 *
4 * Copyright (c) Microsoft Corporation.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in all
14 * copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22 * SOFTWARE.
23 */
24
25using System;
26using System.Collections.Generic;
27using System.IO;
28using System.Linq;
29using System.Reflection;
30
31namespace Microsoft.Playwright.Tests
32{
33    /// <summary>
34    /// This will identify missing tests from upstream.
35    /// </summary>
36    internal static class IdentifyMissingTests
37    {
38        private static readonly List<(string FileName, string TestName)> _testPairs = new();
39
40        /// <summary>
41        /// Runs the scenario.
42        /// </summary>
43        /// <param name="options">The options argument.</param>
44        public static void Run(IdentifyMissingTestsOptions options)
45        {
46            // get all files that match a pattern
47            var directoryInfo = new DirectoryInfo(options.SpecFileLocations);
48            if (!directoryInfo.Exists)
49            {
50                throw new ArgumentException($"The location ({directoryInfo.FullName}) specified does not exist.");
51            }
52
53            // let's map the test cases from the spec files
54            MapTestsCases(directoryInfo, options, string.Empty);
55
56            // now, let's load the DLL and use some reflection-fu
57            var assembly = Assembly.LoadFrom(options.TestsAssemblyPath);
58
59            var attributes = assembly.DefinedTypes.SelectMany(
60                type => type.GetMethods().SelectMany(method => method.GetCustomAttributes<PlaywrightTestAttribute>()));
61
62            int potentialMatches = 0;
63            int fullMatches = 0;
64            int noMatches = 0;
65            int totalTests = 0;
66
67            List<(string FileName, string TestName)> missingTests = new();
68            List<KeyValuePair<(string FileName, string TestName), List<(string FileName, string TestName)>>> invalidMaps = new();
69            foreach (var atx in attributes)
70            {
71                totalTests++;
72
73                // a test can either be a full match, a partial (i.e. just the test name) or no match
74                var potentialMatch = _testPairs.Where(x => string.Equals(x.TestName, atx.TestName, StringComparison.InvariantCultureIgnoreCase));
75                if (!potentialMatch.Any())
76                {
77                    noMatches++;
78                    missingTests.Add((atx.FileName, atx.TestName));
79                }
80                else if (potentialMatch.Any(x => string.Equals(x.FileName, atx.TrimmedName, StringComparison.InvariantCultureIgnoreCase)))
81                {
82                    fullMatches++;
83                    continue;
84                }
85                else
86                {
87                    invalidMaps.Add(new KeyValuePair<(string, string), List<(string, string)>>((atx.TrimmedName, atx.TestName), potentialMatch.ToList()));
88                    potentialMatches++;
89                }
90            }
91
92            Console.ForegroundColor = ConsoleColor.Green;
93            Console.WriteLine($"Total matching tests: {fullMatches}/{totalTests}.");
94            Console.ResetColor();
95
96            Console.ForegroundColor = ConsoleColor.Yellow;
97            Console.WriteLine($"Total tests found by name, but not by file: {potentialMatches}/{totalTests}.");
98            Console.ResetColor();
99
100            foreach (var invalidTest in invalidMaps)
101            {
102                Console.WriteLine($"{invalidTest.Key.FileName}: {invalidTest.Key.TestName}");
103                foreach (var (fileName, testName) in invalidTest.Value)
104                {
105                    Console.WriteLine($"\t{fileName}: {testName}");
106                }
107            }
108
109            Console.ForegroundColor = ConsoleColor.Red;
110            Console.WriteLine($"Total missing tests: {noMatches}/{totalTests}.");
111            Console.ResetColor();
112
113            foreach (var invalidTest in missingTests)
114            {
115                Console.WriteLine($"{invalidTest.FileName}: {invalidTest.TestName}");
116            }
117
118            Console.WriteLine($"Found/Mismatched/Missing: {fullMatches}/{potentialMatches}/{noMatches} out of {totalTests}");
119        }
120
121        private static void MapTestsCases(DirectoryInfo directoryInfo, IdentifyMissingTestsOptions options, string basePath)
122        {
123            // get the sub-directories
124            if (options.Recursive)
125            {
126                foreach (var subdirectory in directoryInfo.GetDirectories())
127                {
128                    MapTestsCases(subdirectory, options, $"{basePath}{subdirectory.Name}/");
129                }
130            }
131
132            foreach (var fileInfo in directoryInfo.GetFiles(options.Pattern))
133            {
134                ScaffoldTest.FindTestsInFile(
135                    fileInfo.FullName,
136                    (testName) =>
137                    {
138                        _testPairs.Add(new(basePath + fileInfo.Name.Substring(0, fileInfo.Name.IndexOf('.')), testName));
139                    });
140            }
141        }
142    }
143}
144
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Trigger PlaywrightTestAttribute code on LambdaTest Cloud Grid

Execute automation tests with PlaywrightTestAttribute on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)