using System.Collections.Concurrent;
using Febe.Browser.Diagnostics;
using Febe.Browser.WebView2;
namespace Febe.Tests.Desktop.Support;
///
/// A stand-in for the two WebView2 calls (CallDevToolsProtocolMethodAsync, GetDevToolsProtocolEventReceiver):
/// records what reaches «WebView2», answers with , and raises events like WebView2 does, on the
/// thread of the caller (WebView2's UI thread in the real application).
///
internal sealed class FakeDevTools : IWebView2DevTools
{
private readonly ConcurrentDictionary>> _receivers = new(StringComparer.Ordinal);
/// Every call that reached «WebView2»: method and parameters as JSON.
public ConcurrentQueue<(string Method, string Json)> Calls { get; } = new();
/// The answer to a call (default: an empty result object).
public Func> Answer { get; set; } = (_, _) => Task.FromResult("{}");
/// How many event handlers are attached to «WebView2» right now, by event name.
public int Subscribed(string eventName) => _receivers.TryGetValue(eventName, out var list) ? list.Count : 0;
/// Total subscriptions ever made (to see re-subscriptions after a new WebView).
public int SubscriptionsMade { get; private set; }
public Task CallMethodAsync(string methodName, string parametersAsJson)
{
Calls.Enqueue((methodName, parametersAsJson));
return Answer(methodName, parametersAsJson);
}
public IDisposable Subscribe(string eventName, Action onEvent)
{
var list = _receivers.GetOrAdd(eventName, _ => []);
lock (list)
{
list.Add(onEvent);
}
SubscriptionsMade++;
return new Removal(() =>
{
lock (list)
{
list.Remove(onEvent);
}
});
}
/// «WebView2» receives a protocol event: ParameterObjectAsJson goes to the handlers.
public void Raise(string eventName, string parametersJson)
{
if (!_receivers.TryGetValue(eventName, out var list))
{
return;
}
Action[] handlers;
lock (list)
{
handlers = [.. list];
}
foreach (var handler in handlers)
{
handler(parametersJson);
}
}
private sealed class Removal(Action remove) : IDisposable
{
private Action? _remove = remove;
public void Dispose() => Interlocked.Exchange(ref _remove, null)?.Invoke();
}
}
/// Collects what the browser layer logs (to prove that only names get there).
internal sealed class RecordingBrowserLog : IBrowserLog
{
public ConcurrentQueue Lines { get; } = new();
public void Write(BrowserLogLevel level, string message, Exception? exception = null) =>
Lines.Enqueue($"{level} {message} {exception?.GetType().Name} {exception?.Message}");
public string All => string.Join('\n', Lines);
}