Files
Febe/tests/Febe.Tests/Desktop/Support/FakeDevTools.cs
T

90 lines
3.1 KiB
C#

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