refactor: extract tests to library test project

This commit is contained in:
Stevan Freeborn
2025-05-29 00:09:19 -05:00
parent 6479531126
commit ce45893caa
25 changed files with 226 additions and 34 deletions
@@ -17,7 +17,9 @@ public static class ServicesExtensions
c.BaseAddress = new Uri(discordOptions.ApiUrl); c.BaseAddress = new Uri(discordOptions.ApiUrl);
c.DefaultRequestHeaders.Authorization = new("Bot", discordOptions.AppToken); c.DefaultRequestHeaders.Authorization = new("Bot", discordOptions.AppToken);
var userAgentString = $"DiscordBot (https://github.com/StevanFreeborn/steves-bot, {StevesBotInstrumentation.SourceVersion})"; var instrumentation = sp.GetRequiredService<IInstrumentation>();
var userAgentString = $"DiscordBot (https://github.com/StevanFreeborn/steves-bot, {instrumentation.SourceVersion})";
c.DefaultRequestHeaders.Add("User-Agent", userAgentString); c.DefaultRequestHeaders.Add("User-Agent", userAgentString);
}) })
.AddStandardResilienceHandler(); .AddStandardResilienceHandler();
@@ -11,11 +11,15 @@ namespace StevesBot.Library.Telemetry;
public static class HostExtensions public static class HostExtensions
{ {
public static HostApplicationBuilder AddTelemetry(this HostApplicationBuilder builder) public static IHostApplicationBuilder AddTelemetry(this IHostApplicationBuilder builder, Func<IInstrumentation> instrumentationFunc)
{ {
ArgumentNullException.ThrowIfNull(builder); ArgumentNullException.ThrowIfNull(builder);
builder.Services.AddSingleton<StevesBotInstrumentation>(); builder.Services.AddSingleton(instrumentationFunc);
var instrumentation = builder.Services
.BuildServiceProvider()
.GetRequiredService<IInstrumentation>();
var seq = new SeqOptions(); var seq = new SeqOptions();
builder.Configuration.GetSection(nameof(SeqOptions)).Bind(seq); builder.Configuration.GetSection(nameof(SeqOptions)).Bind(seq);
@@ -28,11 +32,11 @@ public static class HostExtensions
builder.Services.AddOpenTelemetry() builder.Services.AddOpenTelemetry()
.ConfigureResource(resource => .ConfigureResource(resource =>
{ {
resource.AddService(StevesBotInstrumentation.SourceName, StevesBotInstrumentation.SourceVersion); resource.AddService(instrumentation.SourceName, instrumentation.SourceVersion);
resource.AddAttributes(new Dictionary<string, object> resource.AddAttributes(new Dictionary<string, object>
{ {
["service.name"] = StevesBotInstrumentation.SourceName, ["service.name"] = instrumentation.SourceName,
["service.version"] = StevesBotInstrumentation.SourceVersion, ["service.version"] = instrumentation.SourceVersion,
["service.instance.id"] = Environment.MachineName, ["service.instance.id"] = Environment.MachineName,
["service.namespace"] = "stevesbot", ["service.namespace"] = "stevesbot",
["service.environment"] = Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") ?? "production", ["service.environment"] = Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") ?? "production",
@@ -49,7 +53,7 @@ public static class HostExtensions
}) })
.WithTracing(tb => .WithTracing(tb =>
{ {
tb.AddSource(StevesBotInstrumentation.SourceName); tb.AddSource(instrumentation.SourceName);
tb.AddAspNetCoreInstrumentation(); tb.AddAspNetCoreInstrumentation();
tb.AddHttpClientInstrumentation(); tb.AddHttpClientInstrumentation();
tb.AddOtlpExporter(o => tb.AddOtlpExporter(o =>
@@ -0,0 +1,10 @@
using System.Diagnostics;
namespace StevesBot.Library.Telemetry;
public interface IInstrumentation : IDisposable
{
string SourceName { get; }
string SourceVersion { get; }
ActivitySource Source { get; }
}
@@ -1,15 +0,0 @@
using System.Diagnostics;
namespace StevesBot.Library.Telemetry;
public sealed class StevesBotInstrumentation : IDisposable
{
public const string SourceName = "StevesBot.Worker";
public const string SourceVersion = "0.0.0";
public ActivitySource Source { get; } = new(SourceName, SourceVersion);
public void Dispose()
{
Source.Dispose();
}
}
@@ -0,0 +1,18 @@
using System.Diagnostics;
namespace StevesBot.Library.Telemetry;
public sealed class StevesBotWebhookInstrumentation : IInstrumentation
{
private const string SourceNameValue = "StevesBot.Webhook";
private const string SourceVersionValue = "0.0.0";
public string SourceName { get; } = SourceNameValue;
public string SourceVersion { get; } = SourceVersionValue;
public ActivitySource Source { get; } = new ActivitySource(SourceNameValue, SourceVersionValue);
public void Dispose()
{
Source.Dispose();
}
}
@@ -0,0 +1,18 @@
using System.Diagnostics;
namespace StevesBot.Library.Telemetry;
public sealed class StevesBotWorkerInstrumentation : IInstrumentation
{
private const string SourceNameValue = "StevesBot.Worker";
private const string SourceVersionValue = "0.0.0";
public string SourceName { get; } = SourceNameValue;
public string SourceVersion { get; } = SourceVersionValue;
public ActivitySource Source { get; } = new ActivitySource(SourceNameValue, SourceVersionValue);
public void Dispose()
{
Source.Dispose();
}
}
+2
View File
@@ -1,5 +1,7 @@
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
builder.AddTelemetry(static () => new StevesBotWebhookInstrumentation());
builder.Services builder.Services
.AddOptionsWithValidateOnStart<SubscriptionOptions>() .AddOptionsWithValidateOnStart<SubscriptionOptions>()
.BindConfiguration(nameof(SubscriptionOptions)) .BindConfiguration(nameof(SubscriptionOptions))
+1
View File
@@ -12,6 +12,7 @@ global using StevesBot.Library.Discord;
global using StevesBot.Library.Discord.Common; global using StevesBot.Library.Discord.Common;
global using StevesBot.Library.Discord.Rest; global using StevesBot.Library.Discord.Rest;
global using StevesBot.Library.Discord.Rest.Requests; global using StevesBot.Library.Discord.Rest.Requests;
global using StevesBot.Library.Telemetry;
global using StevesBot.Webhook.YouTube; global using StevesBot.Webhook.YouTube;
global using StevesBot.Webhook.YouTube.Data; global using StevesBot.Webhook.YouTube.Data;
global using StevesBot.Webhook.YouTube.Handlers; global using StevesBot.Webhook.YouTube.Handlers;
@@ -40,7 +40,7 @@ internal static class NotificationHandler
return Results.Ok(); return Results.Ok();
} }
if (lastPostedStream.Value == videoId) if (lastPostedStream.HasValue(videoId))
{ {
logger.LogInformation("Video ID {VideoId} has already been posted. Skipping notification.", videoId); logger.LogInformation("Video ID {VideoId} has already been posted. Skipping notification.", videoId);
return Results.Ok(); return Results.Ok();
@@ -25,5 +25,10 @@
"DiscordNotificationOptions": { "DiscordNotificationOptions": {
"ChannelId": "ChannelId", "ChannelId": "ChannelId",
"MessageFormat": "MessageFormat" "MessageFormat": "MessageFormat"
},
"SeqOptions": {
"ServerUrl": "ServerUrl",
"ApiKeyHeader": "ApiKeyHeader",
"ApiKey": "ApiKey"
} }
} }
+1 -1
View File
@@ -11,7 +11,7 @@ builder.Services.AddSingleton(static sp =>
return discordOptions; return discordOptions;
}); });
builder.AddTelemetry(); builder.AddTelemetry(static () => new StevesBotWorkerInstrumentation());
builder.Services.AddSingleton<IWebSocketFactory, WebSocketFactory>(); builder.Services.AddSingleton<IWebSocketFactory, WebSocketFactory>();
builder.Services.AddSingleton(TimeProvider.System); builder.Services.AddSingleton(TimeProvider.System);
@@ -1,4 +1,4 @@
namespace StevesBot.Worker.Tests.Unit; namespace StevesBot.Library.Tests.Unit;
public class CreateMessageRequestTests public class CreateMessageRequestTests
{ {
@@ -1,4 +1,4 @@
namespace StevesBot.Worker.Tests.Unit; namespace StevesBot.Library.Tests.Unit;
public class DiscordClientOptionsTests public class DiscordClientOptionsTests
{ {
@@ -1,4 +1,4 @@
namespace StevesBot.Worker.Tests.Unit; namespace StevesBot.Library.Tests.Unit;
public class DiscordMessageReferenceTests public class DiscordMessageReferenceTests
{ {
@@ -1,4 +1,4 @@
namespace StevesBot.Worker.Tests.Unit; namespace StevesBot.Library.Tests.Unit;
public class DiscordMessageReferenceTypesTests public class DiscordMessageReferenceTypesTests
{ {
@@ -0,0 +1 @@
namespace StevesBot.Library.Tests.Unit;
@@ -1,4 +1,4 @@
namespace StevesBot.Worker.Tests.Unit; namespace StevesBot.Library.Tests.Unit;
public class DiscordRestClientExceptionTests public class DiscordRestClientExceptionTests
{ {
@@ -1,6 +1,4 @@
using Microsoft.AspNetCore.Http.HttpResults; namespace StevesBot.Library.Tests.Unit;
namespace StevesBot.Worker.Tests.Unit;
public sealed class DiscordRestClientTests : IDisposable public sealed class DiscordRestClientTests : IDisposable
{ {
@@ -0,0 +1 @@
namespace StevesBot.Library.Tests.Unit;
@@ -0,0 +1,6 @@
namespace StevesBot.Library.Tests.Unit;
public class HostExtensionsTests
{
}
@@ -0,0 +1,66 @@
namespace StevesBot.Library.Tests.Unit;
public class SeqOptionsTests
{
[Fact]
public void Constructor_WhenCalled_ItShouldReturnInstance()
{
var result = new SeqOptions();
result.ServerUrl.Should().Be(string.Empty);
result.ApiKeyHeader.Should().Be(string.Empty);
result.ApiKey.Should().Be(string.Empty);
result.IsEnabled.Should().BeFalse();
result.LogEndpoint.Should().Be($"{string.Empty}/ingest/otlp/v1/logs");
result.TraceEndpoint.Should().Be($"{string.Empty}/ingest/otlp/v1/traces");
result.AuthHeader.Should().Be($"{string.Empty}={string.Empty}");
}
[Fact]
public void Constructor_WhenPropertiesSet_ItShouldReturnCorrectValues()
{
var serverUrl = "http://example.com";
var apiKeyHeader = "ApiKeyHeader";
var apiKey = "ApiKeyValue";
var result = new SeqOptions
{
ServerUrl = serverUrl,
ApiKeyHeader = apiKeyHeader,
ApiKey = apiKey
};
result.ServerUrl.Should().Be(serverUrl);
result.ApiKeyHeader.Should().Be(apiKeyHeader);
result.ApiKey.Should().Be(apiKey);
result.IsEnabled.Should().BeTrue();
result.LogEndpoint.Should().Be($"{serverUrl}/ingest/otlp/v1/logs");
result.TraceEndpoint.Should().Be($"{serverUrl}/ingest/otlp/v1/traces");
result.AuthHeader.Should().Be($"{apiKeyHeader}={apiKey}");
}
[Theory]
[InlineData(null, null, null, false)]
[InlineData("", "", "", false)]
[InlineData("http://example.com", null, null, false)]
[InlineData("http://example.com", "", "", false)]
[InlineData(null, "ApiKeyHeader", null, false)]
[InlineData(null, null, "ApiKeyValue", false)]
[InlineData("http://example.com", "ApiKeyHeader", "ApiKeyValue", true)]
[InlineData("http://example.com", "", "ApiKeyValue", false)]
[InlineData("", "ApiKeyHeader", "ApiKeyValue", false)]
[InlineData("http://example.com", "ApiKeyHeader", null, false)]
[InlineData("", "ApiKeyHeader", null, false)]
[InlineData(null, "ApiKeyHeader", "ApiKeyValue", false)]
public void IsEnabled_WhenPropertiesAreEmpty_ItShouldReturnFalse(string? serverUrl, string? apiKeyHeader, string? apiKey, bool expected)
{
var result = new SeqOptions
{
ServerUrl = serverUrl!,
ApiKeyHeader = apiKeyHeader!,
ApiKey = apiKey!
};
result.IsEnabled.Should().Be(expected);
}
}
@@ -0,0 +1,32 @@
namespace StevesBot.Library.Tests.Unit;
public sealed class StevesBotWebhookInstrumentationTests : IDisposable
{
private readonly StevesBotWebhookInstrumentation _instrumentation = new();
[Fact]
public void SourceName_WhenCalled_ItShouldReturnCorrectName()
{
_instrumentation.SourceName.Should().Be("StevesBot.Webhook");
}
[Fact]
public void SourceVersion_WhenCalled_ItShouldReturnCorrectVersion()
{
_instrumentation.SourceVersion.Should().Be("0.0.0");
}
[Fact]
public void Constructor_WhenCalled_ItShouldReturnInstance()
{
using var result = new StevesBotWorkerInstrumentation();
using var expectedSource = new ActivitySource(_instrumentation.SourceName, _instrumentation.SourceVersion);
result.Source.Should().BeEquivalentTo(expectedSource);
}
public void Dispose()
{
_instrumentation.Dispose();
}
}
@@ -0,0 +1,32 @@
namespace StevesBot.Library.Tests.Unit;
public sealed class StevesBotWorkerInstrumentationTests : IDisposable
{
private readonly StevesBotWorkerInstrumentation _instrumentation = new();
[Fact]
public void SourceName_WhenCalled_ItShouldReturnCorrectName()
{
_instrumentation.SourceName.Should().Be("StevesBot.Worker");
}
[Fact]
public void SourceVersion_WhenCalled_ItShouldReturnCorrectVersion()
{
_instrumentation.SourceVersion.Should().Be("0.0.0");
}
[Fact]
public void Constructor_WhenCalled_ItShouldReturnInstance()
{
using var result = new StevesBotWorkerInstrumentation();
using var expectedSource = new ActivitySource(_instrumentation.SourceName, _instrumentation.SourceVersion);
result.Source.Should().BeEquivalentTo(expectedSource);
}
public void Dispose()
{
_instrumentation.Dispose();
}
}
@@ -1,5 +1,16 @@
global using System.Diagnostics;
global using System.Net;
global using System.Text.Json;
global using Microsoft.Extensions.DependencyInjection; global using Microsoft.Extensions.DependencyInjection;
global using Microsoft.Extensions.Logging;
global using Moq;
global using RichardSzalay.MockHttp;
global using StevesBot.Library.Discord; global using StevesBot.Library.Discord;
global using StevesBot.Library.Discord.Common; global using StevesBot.Library.Discord.Common;
global using StevesBot.Library.Discord.Rest; global using StevesBot.Library.Discord.Rest;
global using StevesBot.Library.Discord.Rest.Requests;
global using StevesBot.Library.Telemetry;