How to use WebSocket class of Microsoft.Playwright.Core package

Best Playwright-dotnet code snippet using Microsoft.Playwright.Core.WebSocket

Run Playwright-dotnet automation tests on LambdaTest cloud grid

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

IgnoreHttpsErrorsTests.cs

Source: IgnoreHttpsErrorsTests.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.Net;
27using System.Threading.Tasks;
28using Microsoft.AspNetCore.Connections.Features;
29using Microsoft.AspNetCore.Http;
30using Microsoft.Playwright.NUnit;
31using NUnit.Framework;
32
33namespace Microsoft.Playwright.Tests
34{
35    ///<playwright-file>ignorehttpserrors.spec.ts</playwright-file>
36    ///<playwright-describe>ignoreHTTPSErrors</playwright-describe>
37    public class IgnoreHttpsErrorsTests : BrowserTestEx
38    {
39        [PlaywrightTest("ignorehttpserrors.spec.ts", "should work")]
40        public async Task ShouldWork()
41        {
42            await using var context = await Browser.NewContextAsync(new() { IgnoreHTTPSErrors = true });
43            var page = await context.NewPageAsync();
44            var responseTask = page.GotoAsync(HttpsServer.EmptyPage);
45
46            var response = responseTask.Result;
47            Assert.AreEqual((int)HttpStatusCode.OK, response.Status);
48        }
49
50        [PlaywrightTest("ignorehttpserrors.spec.ts", "should isolate contexts")]
51        public async Task ShouldIsolateContexts()
52        {
53            await using (var context = await Browser.NewContextAsync(new() { IgnoreHTTPSErrors = true }))
54            {
55                var page = await context.NewPageAsync();
56                var response = await page.GotoAsync(HttpsServer.Prefix + "/empty.html");
57
58                Assert.AreEqual((int)HttpStatusCode.OK, response.Status);
59            }
60
61            await using (var context = await Browser.NewContextAsync())
62            {
63                var page = await context.NewPageAsync();
64                await PlaywrightAssert.ThrowsAsync<PlaywrightException>(() => page.GotoAsync(HttpsServer.Prefix + "/empty.html"));
65            }
66        }
67
68        [PlaywrightTest("ignorehttpserrors.spec.ts", "should work with mixed content")]
69        public async Task ShouldWorkWithMixedContent()
70        {
71            HttpsServer.SetRoute("/mixedcontent.html", async (context) =>
72            {
73                await context.Response.WriteAsync($"<iframe src='{Server.EmptyPage}'></iframe>");
74            });
75            await using var context = await Browser.NewContextAsync(new() { IgnoreHTTPSErrors = true });
76            var page = await context.NewPageAsync();
77            await page.GotoAsync(HttpsServer.Prefix + "/mixedcontent.html", new() { WaitUntil = WaitUntilState.DOMContentLoaded });
78            Assert.AreEqual(2, page.Frames.Count);
79            Assert.AreEqual(3, await page.MainFrame.EvaluateAsync<int>("1 + 2"));
80            Assert.AreEqual(5, await page.FirstChildFrame().EvaluateAsync<int>("2 + 3"));
81        }
82
83        [PlaywrightTest("ignorehttpserrors.spec.ts", "should work with WebSocket")]
84        public async Task ShouldWorkWithWebSocket()
85        {
86            HttpsServer.SendOnWebSocketConnection("incoming");
87            await using var context = await Browser.NewContextAsync(new() { IgnoreHTTPSErrors = true });
88            var page = await context.NewPageAsync();
89            string value = await page.EvaluateAsync<string>(@"endpoint => {
90                let cb;
91              const result = new Promise(f => cb = f);
92              const ws = new WebSocket(endpoint);
93              ws.addEventListener('message', data => { ws.close(); cb(data.data); });
94              ws.addEventListener('error', error => cb('Error'));
95              return result;
96            }", HttpsServer.Prefix.Replace("https", "wss") + "/ws");
97
98            Assert.AreEqual("incoming", value);
99        }
100
101        [PlaywrightTest("ignorehttpserrors.spec.ts", "should fail with WebSocket if not ignored")]
102        public async Task ShouldFailWithWebSocketIfNotIgnored()
103        {
104            await using var context = await Browser.NewContextAsync();
105            var page = await context.NewPageAsync();
106            string value = await page.EvaluateAsync<string>(@"endpoint => {
107                let cb;
108              const result = new Promise(f => cb = f);
109              const ws = new WebSocket(endpoint);
110              ws.addEventListener('message', data => { ws.close(); cb(data.data); });
111              ws.addEventListener('error', error => cb('Error'));
112              return result;
113            }", HttpsServer.Prefix.Replace("https", "wss") + "/ws");
114
115            Assert.AreEqual("Error", value);
116        }
117    }
118}
119
Full Screen

WebSocket.cs

Source: WebSocket.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 Microsoft.Playwright.Transport;
27using Microsoft.Playwright.Transport.Channels;
28using Microsoft.Playwright.Transport.Protocol;
29
30namespace Microsoft.Playwright.Core
31{
32    internal class WebSocket : ChannelOwnerBase, IChannelOwner<WebSocket>, IWebSocket
33    {
34        private readonly WebSocketChannel _channel;
35        private readonly WebSocketInitializer _initializer;
36
37        internal WebSocket(IChannelOwner parent, string guid, WebSocketInitializer initializer) : base(parent, guid)
38        {
39            _channel = new(guid, parent.Connection, this);
40            _initializer = initializer;
41
42            _channel.Close += (_, _) =>
43            {
44                IsClosed = true;
45                Close?.Invoke(this, this);
46            };
47            _channel.FrameReceived += (_, e) => FrameReceived?.Invoke(this, e);
48            _channel.FrameSent += (_, e) => FrameSent?.Invoke(this, e);
49            _channel.SocketError += (_, e) => SocketError?.Invoke(this, e);
50        }
51
52        public event EventHandler<IWebSocket> Close;
53
54        public event EventHandler<IWebSocketFrame> FrameSent;
55
56        public event EventHandler<IWebSocketFrame> FrameReceived;
57
58        public event EventHandler<string> SocketError;
59
60        ChannelBase IChannelOwner.Channel => _channel;
61
62        IChannel<WebSocket> IChannelOwner<WebSocket>.Channel => _channel;
63
64        public string Url => _initializer.Url;
65
66        public bool IsClosed { get; internal set; }
67    }
68}
69
Full Screen

BinaryHttpClientTest.cs

Source: BinaryHttpClientTest.cs Github

copy
1// Licensed to the .NET Foundation under one or more agreements.
2// The .NET Foundation licenses this file to you under the MIT license.
3
4using System;
5using System.Linq;
6using System.Threading.Tasks;
7using BasicTestApp.HttpClientTest;
8using Microsoft.AspNetCore.BrowserTesting;
9using Microsoft.AspNetCore.Components.E2ETest.Infrastructure.ServerFixtures;
10using Microsoft.AspNetCore.Components.E2ETest.Infrastructure;
11using Microsoft.AspNetCore.Testing;
12using PlaywrightSharp;
13using TestServer;
14using Xunit;
15using Xunit.Abstractions;
16
17namespace Microsoft.AspNetCore.Components.E2ETest.Tests
18{
19    public class BinaryHttpClientTest : PlaywrightTestBase,
20        IClassFixture<BasicTestAppServerSiteFixture<CorsStartup>>,
21        IClassFixture<DevHostServerFixture<BasicTestApp.Program>>
22    {
23        private readonly DevHostServerFixture<BasicTestApp.Program> _devHostServerFixture;
24        readonly ServerFixture _apiServerFixture;
25        //IWebElement _appElement;
26        //IWebElement _responseStatus;
27        //IWebElement _responseStatusText;
28        //IWebElement _testOutcome;
29
30        public BinaryHttpClientTest(
31            DevHostServerFixture<BasicTestApp.Program> devHostServerFixture,
32            BasicTestAppServerSiteFixture<CorsStartup> apiServerFixture,
33            ITestOutputHelper output)
34            : base(output)
35        {
36            _devHostServerFixture = devHostServerFixture;
37            _devHostServerFixture.PathBase = "/subdir";
38            _apiServerFixture = apiServerFixture;
39        }
40
41        //protected override void InitializeAsyncCore()
42        //{
43        //    //Browser.Navigate(_devHostServerFixture.RootUri, "/subdir", noReload: true);
44        //    //_appElement = Browser.MountTestComponent<BinaryHttpRequestsComponent>();
45        //}
46
47        [Fact]
48        public async Task CanSendAndReceiveBytes()
49        {
50            if (BrowserManager.IsAvailable(BrowserKind.Chromium))
51            {
52                await using var browser = await BrowserManager.GetBrowserInstance(BrowserKind.Chromium, BrowserContextInfo);
53                var page = await browser.NewPageAsync();
54                await page.GoToAsync(_devHostServerFixture.RootUri + "/subdir/api/data");
55
56/*                var socket = BrowserContextInfo.Pages[page].WebSockets.SingleOrDefault() ??
57                    (await page.WaitForEventAsync(PageEvent.WebSocket)).WebSocket;
58
59                // Receive render batch
60                await socket.WaitForEventAsync(WebSocketEvent.FrameReceived);
61                await socket.WaitForEventAsync(WebSocketEvent.FrameSent);
62
63                // JS interop call to intercept navigation
64                await socket.WaitForEventAsync(WebSocketEvent.FrameReceived);
65                await socket.WaitForEventAsync(WebSocketEvent.FrameSent);
66
67                await page.WaitForSelectorAsync("ul");*/
68
69                await page.CloseAsync();
70            }
71
72
73            //IssueRequest("/subdir/api/data");
74            //Assert.Equal("OK", _responseStatus.Text);
75            //Assert.Equal("OK", _responseStatusText.Text);
76            //Assert.Equal("", _testOutcome.Text);
77        }
78
79        private void IssueRequest()
80        {
81            //var targetUri = new Uri(_apiServerFixture.RootUri, relativeUri);
82            //SetValue("request-uri", targetUri.AbsoluteUri);
83
84            //_appElement.FindElement(By.Id("send-request")).Click();
85
86            //_responseStatus = Browser.Exists(By.Id("response-status"));
87            //_responseStatusText = _appElement.FindElement(By.Id("response-status-text"));
88            //_testOutcome = _appElement.FindElement(By.Id("test-outcome"));
89
90        }
91    }
92}
93
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

Most used methods in WebSocket

    No methods found for this class 😞

Run Selenium Automation Tests on LambdaTest Cloud Grid

Trigger Selenium automation tests on a cloud-based Grid of 3000+ real browsers and operating systems.

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)