How to use AssertCSPError method of Microsoft.Playwright.Tests.TestUtils class

Best Playwright-dotnet code snippet using Microsoft.Playwright.Tests.TestUtils.AssertCSPError

Run Playwright-dotnet automation tests on LambdaTest cloud grid

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

BrowserContextCSPTests.cs

Source: BrowserContextCSPTests.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.Threading.Tasks;
26using Microsoft.Playwright.NUnit;
27using NUnit.Framework;
28
29namespace Microsoft.Playwright.Tests
30{
31    public class BrowserContextCSPTests : BrowserTestEx
32    {
33        [PlaywrightTest("browsercontext-csp.spec.ts", "should bypass CSP meta tag")]
34        public async Task ShouldBypassCSPMetatag()
35        {
36            // Make sure CSP prohibits addScriptTag.
37            await using (var context = await Browser.NewContextAsync())
38            {
39                var page = await context.NewPageAsync();
40                await page.GotoAsync(Server.Prefix + "/csp.html");
41                var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => page.AddScriptTagAsync(new() { Content = "window.__injected = 42;" }));
42                TestUtils.AssertCSPError(exception.Message);
43                Assert.Null(await page.EvaluateAsync("window.__injected"));
44            }
45            // By-pass CSP and try one more time.
46            await using (var context = await Browser.NewContextAsync(new() { BypassCSP = true }))
47            {
48                var page = await context.NewPageAsync();
49                await page.GotoAsync(Server.Prefix + "/csp.html");
50                await page.AddScriptTagAsync(new() { Content = "window.__injected = 42;" });
51                Assert.AreEqual(42, await page.EvaluateAsync<int>("window.__injected"));
52            }
53        }
54
55        [PlaywrightTest("browsercontext-csp.spec.ts", "should bypass CSP header")]
56        public async Task ShouldBypassCSPHeader()
57        {
58            // Make sure CSP prohibits addScriptTag.
59            Server.SetCSP("/empty.html", "default-src 'self'");
60
61            await using (var context = await Browser.NewContextAsync())
62            {
63                var page = await context.NewPageAsync();
64                await page.GotoAsync(Server.EmptyPage);
65                var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => page.AddScriptTagAsync(new() { Content = "window.__injected = 42;" }));
66                TestUtils.AssertCSPError(exception.Message);
67                Assert.Null(await page.EvaluateAsync("window.__injected"));
68            }
69
70            // By-pass CSP and try one more time.
71            await using (var context = await Browser.NewContextAsync(new() { BypassCSP = true }))
72            {
73                var page = await context.NewPageAsync();
74                await page.GotoAsync(Server.EmptyPage);
75                await page.AddScriptTagAsync(new() { Content = "window.__injected = 42;" });
76                Assert.AreEqual(42, await page.EvaluateAsync<int>("window.__injected"));
77            }
78        }
79
80        [PlaywrightTest("browsercontext-csp.spec.ts", "should bypass after cross-process navigation")]
81        public async Task ShouldBypassAfterCrossProcessNavigation()
82        {
83            await using var context = await Browser.NewContextAsync(new() { BypassCSP = true });
84            var page = await context.NewPageAsync();
85            await page.GotoAsync(Server.Prefix + "/csp.html");
86            await page.AddScriptTagAsync(new() { Content = "window.__injected = 42;" });
87            Assert.AreEqual(42, await page.EvaluateAsync<int>("window.__injected"));
88
89            await page.GotoAsync(Server.CrossProcessPrefix + "/csp.html");
90            await page.AddScriptTagAsync(new() { Content = "window.__injected = 42;" });
91            Assert.AreEqual(42, await page.EvaluateAsync<int>("window.__injected"));
92        }
93
94        [PlaywrightTest("browsercontext-csp.spec.ts", "should bypass CSP in iframes as well")]
95        public async Task ShouldBypassCSPInIframesAsWell()
96        {
97            await using (var context = await Browser.NewContextAsync())
98            {
99                var page = await context.NewPageAsync();
100                await page.GotoAsync(Server.EmptyPage);
101
102                // Make sure CSP prohibits addScriptTag in an iframe.
103                var frame = await FrameUtils.AttachFrameAsync(page, "frame1", Server.Prefix + "/csp.html");
104                var exception = await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => frame.AddScriptTagAsync(new() { Content = "window.__injected = 42;" }));
105                TestUtils.AssertCSPError(exception.Message);
106                Assert.Null(await frame.EvaluateAsync<int?>("() => window.__injected"));
107            }
108
109            // By-pass CSP and try one more time.
110            await using (var context = await Browser.NewContextAsync(new() { BypassCSP = true }))
111            {
112                var page = await context.NewPageAsync();
113                await page.GotoAsync(Server.EmptyPage);
114
115                // Make sure CSP prohibits addScriptTag in an iframe.
116                var frame = await FrameUtils.AttachFrameAsync(page, "frame1", Server.Prefix + "/csp.html");
117                await frame.AddScriptTagAsync(new() { Content = "window.__injected = 42;" }).ContinueWith(_ => Task.CompletedTask);
118                Assert.AreEqual(42, await frame.EvaluateAsync<int?>("() => window.__injected"));
119
120            }
121        }
122    }
123}
124
Full Screen

TestUtils.cs

Source: TestUtils.cs Github

copy
1/*
2 * MIT License
3 *
4 * Copyright (c) 2020 Darío Kondratiuk
5 * Modifications copyright (c) Microsoft Corporation.
6 *
7 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
13 *
14 * The above copyright notice and this permission notice shall be included in all
15 * copies or substantial portions of the Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23 * SOFTWARE.
24 */
25
26using System;
27using System.IO;
28using System.Text;
29using System.Threading.Tasks;
30using NUnit.Framework;
31
32namespace Microsoft.Playwright.Tests
33{
34    internal class TestUtils
35    {
36        internal static string FindParentDirectory(string directory)
37        {
38            // when using Directory.GetCurrentDirectory, for .NET 4.8 under test explorer on Windows,
39            // the location was Local App Data
40            string current = AppContext.BaseDirectory;
41            while (!Directory.Exists(Path.Combine(current, directory)))
42            {
43                current = Directory.GetParent(current).FullName;
44            }
45            return Path.Combine(current, directory);
46        }
47
48        internal static void AssertSSLError(string errorMessage)
49        {
50            if (TestConstants.IsChromium)
51            {
52                StringAssert.Contains("net::ERR_CERT_AUTHORITY_INVALID", errorMessage);
53            }
54            else if (TestConstants.IsWebKit)
55            {
56                if (TestConstants.IsMacOSX)
57                    StringAssert.Contains("The certificate for this server is invalid", errorMessage);
58                else if (TestConstants.IsWindows)
59                    StringAssert.Contains("SSL peer certificate or SSH remote key was not OK", errorMessage);
60                else
61                    StringAssert.Contains("Unacceptable TLS certificate", errorMessage);
62            }
63            else
64            {
65                StringAssert.Contains("SSL_ERROR_UNKNOWN", errorMessage);
66            }
67        }
68
69        internal static void AssertCSPError(string errorMessage)
70        {
71            if (TestConstants.IsWebKit)
72            {
73                StringAssert.StartsWith("Refused to execute a script because its hash, its nonce, or 'unsafe-inline' appears in neither the script-src directive nor the default-src directive of the Content Security Policy.", errorMessage);
74            }
75            else if (TestConstants.IsFirefox)
76            {
77                StringAssert.StartsWith("[JavaScript Error: \"Content Security Policy: The page’s settings blocked the loading of a resource at inline (“default-src”).\"", errorMessage);
78            }
79            else
80            {
81                StringAssert.StartsWith("Refused to execute inline script because it violates the following Content Security Policy directive: \"default-src 'self'\".", errorMessage);
82            }
83        }
84
85        /// <summary>
86        /// Removes as much whitespace as possible from a given string. Whitespace
87        /// that separates letters and/or digits is collapsed to a space character.
88        /// Other whitespace is fully removed.
89        /// </summary>
90        public static string CompressText(string text)
91        {
92            if (string.IsNullOrEmpty(text))
93            {
94                return text;
95            }
96
97            var sb = new StringBuilder();
98            bool inWhitespace = false;
99            foreach (char ch in text)
100            {
101                if (char.IsWhiteSpace(ch))
102                {
103                    if (ch != '\n' && ch != '\r')
104                    {
105                        inWhitespace = true;
106                    }
107                }
108                else
109                {
110                    if (inWhitespace)
111                    {
112                        inWhitespace = false;
113                        if (sb.Length > 0 && char.IsLetterOrDigit(sb[sb.Length - 1]) && char.IsLetterOrDigit(ch))
114                        {
115                            sb.Append(' ');
116                        }
117                    }
118                    sb.Append(ch);
119                }
120            }
121
122            return sb.ToString();
123        }
124
125        internal static async Task RegisterEngineWithPathAsync(IPlaywright playwright, string name, string path)
126        {
127            try
128            {
129                await playwright.Selectors.RegisterAsync(name, new() { Path = path });
130            }
131            catch (PlaywrightException ex) when (ex.Message.Contains("has been already registered"))
132            {
133            }
134        }
135
136        internal static string GetAsset(string path) => Path.Combine(FindParentDirectory("Playwright.Tests.TestServer"), "assets", path);
137
138        internal static async Task VerifyViewportAsync(IPage page, int width, int height)
139        {
140            Assert.AreEqual(width, (int)page.ViewportSize.Width);
141            Assert.AreEqual(height, (int)page.ViewportSize.Height);
142            Assert.AreEqual(width, await page.EvaluateAsync<int>("window.innerWidth"));
143            Assert.AreEqual(height, await page.EvaluateAsync<int>("window.innerHeight"));
144        }
145
146        internal static async Task RegisterEngineAsync(IPlaywright playwright, string name, string script, bool? contentScript = null)
147        {
148            try
149            {
150                await playwright.Selectors.RegisterAsync(name, new() { Script = script, ContentScript = contentScript });
151            }
152            catch (PlaywrightException ex) when (ex.Message.Contains("has been already registered"))
153            {
154            }
155        }
156    }
157}
158
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 AssertCSPError code on LambdaTest Cloud Grid

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