Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Mzbb6zeFTjT6Rp8b92AVkA
247 lines
11 KiB
C#
247 lines
11 KiB
C#
using System.Collections.Concurrent;
|
|
using System.Net;
|
|
using System.Net.Sockets;
|
|
using System.Net.WebSockets;
|
|
using System.Text;
|
|
using System.Text.Json;
|
|
using System.Text.Json.Nodes;
|
|
using Febe.Browser.Cdp;
|
|
using Febe.Browser.Diagnostics;
|
|
|
|
namespace Febe.Tests.Browser;
|
|
|
|
/// <summary>The CDP client against a scripted WebSocket peer on a loopback TCP pair (no browser).</summary>
|
|
[TestClass]
|
|
public sealed class CdpClientTests
|
|
{
|
|
[TestMethod]
|
|
public async Task AnswersAreMatchedByIdEvenOutOfOrder()
|
|
{
|
|
await using var pair = await SocketPair.CreateAsync();
|
|
var first = pair.Client.SendAsync("Page.getFrameTree");
|
|
var second = pair.Client.SendAsync("Runtime.evaluate", new JsonObject { ["expression"] = "1+1" });
|
|
|
|
var a = await pair.ReceiveAsync();
|
|
var b = await pair.ReceiveAsync();
|
|
await pair.SendAsync(new JsonObject { ["id"] = b["id"]!.GetValue<int>(), ["result"] = new JsonObject { ["who"] = "second" } });
|
|
await pair.SendAsync(new JsonObject { ["id"] = a["id"]!.GetValue<int>(), ["result"] = new JsonObject { ["who"] = "first" } });
|
|
|
|
Assert.AreEqual("first", (await first).GetProperty("who").GetString());
|
|
Assert.AreEqual("second", (await second).GetProperty("who").GetString());
|
|
Assert.AreEqual("Page.getFrameTree", a["method"]!.GetValue<string>());
|
|
Assert.AreEqual("1+1", b["params"]!["expression"]!.GetValue<string>());
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task ErrorsBecomeCdpCommandExceptions()
|
|
{
|
|
await using var pair = await SocketPair.CreateAsync();
|
|
var call = pair.Client.SendAsync("Page.navigate", new JsonObject { ["url"] = "about:blank" });
|
|
var request = await pair.ReceiveAsync();
|
|
await pair.SendAsync(new JsonObject
|
|
{
|
|
["id"] = request["id"]!.GetValue<int>(),
|
|
["error"] = new JsonObject { ["code"] = -32000, ["message"] = "Cannot navigate" },
|
|
});
|
|
|
|
var ex = await Assert.ThrowsExactlyAsync<CdpCommandException>(() => call);
|
|
Assert.AreEqual(-32000, ex.Code);
|
|
Assert.AreEqual("Page.navigate", ex.Method);
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task EventsReachSubscribersUntilTheyUnsubscribe()
|
|
{
|
|
await using var pair = await SocketPair.CreateAsync();
|
|
var received = new ConcurrentQueue<string>();
|
|
var subscription = pair.Client.On("Page.frameNavigated", p => received.Enqueue(p.GetProperty("frame").GetProperty("url").GetString()!));
|
|
|
|
await pair.SendAsync(new JsonObject { ["method"] = "Page.frameNavigated", ["params"] = new JsonObject { ["frame"] = new JsonObject { ["url"] = "uno" } } });
|
|
await WaitUntilAsync(() => received.Count == 1);
|
|
subscription.Dispose();
|
|
await pair.SendAsync(new JsonObject { ["method"] = "Page.frameNavigated", ["params"] = new JsonObject { ["frame"] = new JsonObject { ["url"] = "due" } } });
|
|
|
|
// A round trip proves the second event was processed before we look.
|
|
var ping = pair.Client.SendAsync("Page.enable");
|
|
var request = await pair.ReceiveAsync();
|
|
await pair.SendAsync(new JsonObject { ["id"] = request["id"]!.GetValue<int>(), ["result"] = new JsonObject() });
|
|
await ping;
|
|
|
|
CollectionAssert.AreEqual(new[] { "uno" }, received.ToArray());
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task ForbiddenCommandsNeverReachTheSocket()
|
|
{
|
|
await using var pair = await SocketPair.CreateAsync();
|
|
await Assert.ThrowsExactlyAsync<CdpCommandNotAllowedException>(() => pair.Client.SendAsync("Emulation.setTimezoneOverride", new { timezoneId = "UTC" }));
|
|
await Assert.ThrowsExactlyAsync<CdpCommandNotAllowedException>(() => pair.Client.SendAsync("Network.setUserAgentOverride", new { userAgent = "x" }));
|
|
await Assert.ThrowsExactlyAsync<CdpCommandNotAllowedException>(() => pair.Client.SendAsync("Runtime.evaluate", new { expression = "document.body.click()" }));
|
|
|
|
// The first frame the peer sees is the allowed command sent afterwards.
|
|
var allowed = pair.Client.SendAsync("Page.enable");
|
|
var first = await pair.ReceiveAsync();
|
|
Assert.AreEqual("Page.enable", first["method"]!.GetValue<string>());
|
|
await pair.SendAsync(new JsonObject { ["id"] = first["id"]!.GetValue<int>(), ["result"] = new JsonObject() });
|
|
await allowed;
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task ClosingTheConnectionFailsPendingCallsAndLaterOnes()
|
|
{
|
|
await using var pair = await SocketPair.CreateAsync();
|
|
var disconnected = new TaskCompletionSource();
|
|
pair.Client.Disconnected += (_, _) => disconnected.TrySetResult();
|
|
var pending = pair.Client.SendAsync("Page.getFrameTree");
|
|
await pair.ReceiveAsync();
|
|
|
|
await pair.CloseServerAsync();
|
|
|
|
await Assert.ThrowsExactlyAsync<CdpDisconnectedException>(() => pending);
|
|
await disconnected.Task.WaitAsync(TimeSpan.FromSeconds(5));
|
|
Assert.IsFalse(pair.Client.IsConnected);
|
|
await Assert.ThrowsExactlyAsync<CdpDisconnectedException>(() => pair.Client.SendAsync("Page.enable"));
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task CancellingACallKeepsTheConnectionUsable()
|
|
{
|
|
await using var pair = await SocketPair.CreateAsync();
|
|
using var cts = new CancellationTokenSource();
|
|
var call = pair.Client.SendAsync("Page.getFrameTree", null, cts.Token);
|
|
await pair.ReceiveAsync();
|
|
await cts.CancelAsync();
|
|
await Assert.ThrowsAsync<OperationCanceledException>(() => call);
|
|
|
|
var next = pair.Client.SendAsync("Page.enable");
|
|
var request = await pair.ReceiveAsync();
|
|
await pair.SendAsync(new JsonObject { ["id"] = request["id"]!.GetValue<int>(), ["result"] = new JsonObject() });
|
|
await next;
|
|
Assert.IsTrue(pair.Client.IsConnected);
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task DisposingFailsPendingCallsAndIsIdempotent()
|
|
{
|
|
var pair = await SocketPair.CreateAsync();
|
|
var pending = pair.Client.SendAsync("Page.getFrameTree");
|
|
await pair.ReceiveAsync();
|
|
|
|
await pair.Client.DisposeAsync();
|
|
await pair.Client.DisposeAsync();
|
|
|
|
await Assert.ThrowsExactlyAsync<CdpDisconnectedException>(() => pending);
|
|
await Assert.ThrowsExactlyAsync<CdpDisconnectedException>(() => pair.Client.SendAsync("Page.enable"));
|
|
await pair.DisposeAsync();
|
|
}
|
|
|
|
[TestMethod]
|
|
public async Task TheLogHoldsCommandNamesOnly()
|
|
{
|
|
var log = new ConcurrentQueue<string>();
|
|
await using var pair = await SocketPair.CreateAsync(new DelegateBrowserLog((_, message, ex) => log.Enqueue(message + ex?.Message)));
|
|
pair.Client.On("Network.responseReceived", _ => throw new InvalidOperationException("boom"));
|
|
|
|
var call = pair.Client.SendAsync("Runtime.evaluate", new JsonObject { ["expression"] = "'parola-segreta-1'" });
|
|
var request = await pair.ReceiveAsync();
|
|
await pair.SendAsync(new JsonObject
|
|
{
|
|
["method"] = "Network.responseReceived",
|
|
["params"] = new JsonObject { ["response"] = new JsonObject { ["url"] = "https://example.invalid/?token=segreto-2" } },
|
|
});
|
|
await pair.SendAsync(new JsonObject
|
|
{
|
|
["id"] = request["id"]!.GetValue<int>(),
|
|
["result"] = new JsonObject { ["result"] = new JsonObject { ["value"] = "valore-segreto-3" } },
|
|
});
|
|
await call;
|
|
|
|
var all = string.Join("\n", log);
|
|
StringAssert.Contains(all, "Runtime.evaluate");
|
|
Assert.IsFalse(all.Contains("segret", StringComparison.Ordinal), "Parameters, events and results never reach the log.");
|
|
}
|
|
|
|
private static async Task WaitUntilAsync(Func<bool> condition)
|
|
{
|
|
for (var i = 0; i < 200 && !condition(); i++)
|
|
{
|
|
await Task.Delay(10);
|
|
}
|
|
|
|
Assert.IsTrue(condition());
|
|
}
|
|
|
|
/// <summary>A CdpClient connected to a server-side WebSocket over a loopback TCP connection.</summary>
|
|
private sealed class SocketPair : IAsyncDisposable
|
|
{
|
|
private readonly TcpClient _tcpClient;
|
|
private readonly TcpClient _tcpServer;
|
|
private readonly WebSocket _server;
|
|
|
|
private SocketPair(TcpClient tcpClient, TcpClient tcpServer, WebSocket server, CdpClient client)
|
|
{
|
|
_tcpClient = tcpClient;
|
|
_tcpServer = tcpServer;
|
|
_server = server;
|
|
Client = client;
|
|
}
|
|
|
|
public CdpClient Client { get; }
|
|
|
|
public static async Task<SocketPair> CreateAsync(IBrowserLog? log = null)
|
|
{
|
|
var listener = new TcpListener(IPAddress.Loopback, 0);
|
|
listener.Start();
|
|
var tcpClient = new TcpClient();
|
|
var accept = listener.AcceptTcpClientAsync();
|
|
await tcpClient.ConnectAsync(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndpoint).Port);
|
|
var tcpServer = await accept;
|
|
listener.Stop();
|
|
|
|
var server = WebSocket.CreateFromStream(tcpServer.GetStream(), new WebSocketCreationOptions { IsServer = true });
|
|
var clientSocket = WebSocket.CreateFromStream(tcpClient.GetStream(), new WebSocketCreationOptions { IsServer = false });
|
|
var client = new CdpClient(clientSocket, log, new CdpClientOptions(TimeSpan.FromSeconds(10)));
|
|
return new SocketPair(tcpClient, tcpServer, server, client);
|
|
}
|
|
|
|
public async Task<JsonNode> ReceiveAsync()
|
|
{
|
|
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5));
|
|
var buffer = new byte[64 * 1024];
|
|
using var message = new MemoryStream();
|
|
WebSocketReceiveResult result;
|
|
do
|
|
{
|
|
result = await _server.ReceiveAsync(buffer, timeout.Token);
|
|
message.Write(buffer, 0, result.Count);
|
|
}
|
|
while (!result.EndOfMessage);
|
|
|
|
return JsonNode.Parse(message.ToArray())!;
|
|
}
|
|
|
|
public Task SendAsync(JsonNode message) =>
|
|
_server.SendAsync(Encoding.UTF8.GetBytes(message.ToJsonString()), WebSocketMessageType.Text, true, CancellationToken.None);
|
|
|
|
public async Task CloseServerAsync()
|
|
{
|
|
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(2));
|
|
try
|
|
{
|
|
await _server.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, null, timeout.Token);
|
|
}
|
|
catch (WebSocketException)
|
|
{
|
|
}
|
|
}
|
|
|
|
public async ValueTask DisposeAsync()
|
|
{
|
|
await Client.DisposeAsync();
|
|
_server.Dispose();
|
|
_tcpClient.Dispose();
|
|
_tcpServer.Dispose();
|
|
}
|
|
}
|
|
}
|