Files
Febe/tests/Febe.Tests/Alerts/Support/AlertFakes.cs
T

118 lines
4.9 KiB
C#

using System.Collections.Concurrent;
using System.Net;
using System.Text;
using System.Text.Json;
using Febe.Core.Alerts;
using Febe.Web.Native;
namespace Febe.Tests.Alerts.Support;
/// <summary>A request that reached the fake Telegram.</summary>
/// <param name="Method">HTTP method.</param>
/// <param name="Uri">Full address (it contains the token: tests check it here, nowhere else).</param>
/// <param name="ContentType">Media type of the body.</param>
/// <param name="Body">The JSON body.</param>
internal sealed record TelegramRequest(HttpMethod Method, Uri Uri, string? ContentType, string Body)
{
public string ChatId => JsonDocument.Parse(Body).RootElement.GetProperty("chat_id").GetString()!;
public string Text => JsonDocument.Parse(Body).RootElement.GetProperty("text").GetString()!;
}
/// <summary>
/// Telegram's Bot API, faked: records every request and answers with <see cref="Respond"/> (by default
/// <c>200 {"ok":true}</c>). Never touches the network: the real api.telegram.org is never contacted from tests.
/// </summary>
internal sealed class FakeTelegramHandler : HttpMessageHandler
{
private readonly ConcurrentQueue<TelegramRequest> _requests = new();
public Func<TelegramRequest, CancellationToken, Task<HttpResponseMessage>>? Respond { get; set; }
public IReadOnlyList<TelegramRequest> Requests => [.. _requests];
public static HttpResponseMessage Answer(HttpStatusCode status, string json) =>
new(status) { Content = new StringContent(json, Encoding.UTF8, "application/json") };
/// <summary>Answers with <paramref name="status"/> and the usual error body of the Bot API.</summary>
public void Fail(HttpStatusCode status, string description) =>
Respond = (_, _) => Task.FromResult(Answer(status, $$"""{"ok":false,"error_code":{{(int)status}},"description":"{{description}}"}"""));
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var body = request.Content is null ? string.Empty : await request.Content.ReadAsStringAsync(cancellationToken);
var recorded = new TelegramRequest(request.Method, request.RequestUri!, request.Content?.Headers.ContentType?.MediaType, body);
_requests.Enqueue(recorded);
return Respond is { } respond
? await respond(recorded, cancellationToken)
: Answer(HttpStatusCode.OK, """{"ok":true,"result":{"message_id":1}}""");
}
}
/// <summary>The desktop shell, faked: it can notify and records the notifications.</summary>
internal sealed class FakeNativeShell(bool canNotify = true) : INativeShell
{
private readonly ConcurrentQueue<(string Title, string Message)> _notifications = new();
public IReadOnlyList<(string Title, string Message)> Notifications => [.. _notifications];
public bool Throws { get; set; }
public bool CanPickFolder => false;
public bool CanShowInFolder => false;
public bool CanOpenUrl => false;
public bool CanNotify { get; } = canNotify;
public bool SupportsAutostart => false;
public Task<string?> PickFolderAsync(string title, string? initialFolder, CancellationToken ct) => Task.FromResult<string?>(null);
public Task<bool> ShowInFolderAsync(string fullPath, CancellationToken ct) => Task.FromResult(false);
public Task<bool> OpenUrlAsync(Uri address, CancellationToken ct) => Task.FromResult(false);
public Task NotifyAsync(string title, string message, CancellationToken ct)
{
if (Throws)
{
throw new InvalidOperationException("notifiche spente");
}
_notifications.Enqueue((title, message));
return Task.CompletedTask;
}
public Task<bool> GetAutostartAsync(CancellationToken ct) => Task.FromResult(false);
public Task SetAutostartAsync(bool enabled, CancellationToken ct) => Task.CompletedTask;
}
/// <summary>Free space by folder, as the test decides.</summary>
internal sealed class FakeFreeSpaceProbe : IFreeSpaceProbe
{
private readonly ConcurrentDictionary<string, FreeSpace?> _spaces = new(StringComparer.Ordinal);
public const long GB = 1024L * 1024 * 1024;
public void Set(string folder, long availableBytes, long totalBytes) => _spaces[folder] = new FreeSpace(availableBytes, totalBytes);
public void Unmeasurable(string folder) => _spaces[folder] = null;
public FreeSpace? Measure(string folder) => _spaces.TryGetValue(folder, out var space) ? space : new FreeSpace(500 * GB, 1000 * GB);
}
/// <summary>The log lines of the alert service.</summary>
internal sealed class AlertLogRecorder
{
private readonly ConcurrentQueue<(AlertLogLevel Level, string Message)> _lines = new();
public IReadOnlyList<(AlertLogLevel Level, string Message)> Lines => [.. _lines];
public string All => string.Join("\n", _lines.Select(l => l.Message));
public void Write(AlertLogLevel level, string message) => _lines.Enqueue((level, message));
}