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

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

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

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 UnobservedTaskException code on LambdaTest Cloud Grid

Execute automation tests with UnobservedTaskException 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)