Fix test bad practices and tighten weak assertions

- StorageServiceTests: replace out-param + manual dispose with IAsyncLifetime
- PictureServiceTests: Assert.True bound checks -> Assert.InRange
- CreateAlbumCommandHandlerTests: assert the specific NotFound error type
  instead of just IsError, matching what the test name promises
- CreateAlbumRequestValidatorTests: replace a boundary Theory that computed
  its expected result inline with explicit Facts against the real
  AlbumReleaseYear constants
- Remove unused using directives across a handful of production and test
  files found during the review

Full suite verified green: 250/250 tests passing, 0 build warnings.
This commit is contained in:
2026-09-09 21:53:00 +02:00
parent a26f4b43fd
commit b57949a6bc
24 changed files with 48 additions and 66 deletions
@@ -1,4 +1,3 @@
using Mediator;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Musify.Application.Configuration; using Musify.Application.Configuration;
@@ -1,4 +1,3 @@
using System.Linq;
using Musify.Domain.Entities; using Musify.Domain.Entities;
using Musify.Domain.ValueObjects; using Musify.Domain.ValueObjects;
@@ -4,7 +4,6 @@ using Musify.Application.Events;
using Musify.Infrastructure.Configuration; using Musify.Infrastructure.Configuration;
using Musify.Infrastructure.MassTransit.Activities.Audio; using Musify.Infrastructure.MassTransit.Activities.Audio;
using Musify.Infrastructure.MassTransit.Activities.Files; using Musify.Infrastructure.MassTransit.Activities.Files;
using Musify.Infrastructure.MassTransit.Activities;
using Musify.Infrastructure.MassTransit.Arguments; using Musify.Infrastructure.MassTransit.Arguments;
using Musify.Infrastructure.MassTransit.Consumers; using Musify.Infrastructure.MassTransit.Consumers;
@@ -1,4 +1,3 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
@@ -1,5 +1,4 @@
using System; using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable #nullable disable
@@ -1,5 +1,4 @@
using System; using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable #nullable disable
@@ -1,5 +1,4 @@
using System; using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable #nullable disable
@@ -1,4 +1,3 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable #nullable disable
@@ -1,4 +1,3 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable #nullable disable
@@ -1,5 +1,4 @@
using System; using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable #nullable disable
@@ -1,5 +1,4 @@
using System; using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable #nullable disable
@@ -1,5 +1,4 @@
using System; using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable #nullable disable
@@ -1,5 +1,4 @@
using System; using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable #nullable disable
@@ -1,5 +1,3 @@
using Microsoft.AspNetCore.OpenApi;
namespace Musify.Api.OpenApi; namespace Musify.Api.OpenApi;
public static class OpenApiExtensions public static class OpenApiExtensions
-2
View File
@@ -1,6 +1,4 @@
using Hangfire; using Hangfire;
using Mediator;
using Microsoft.Extensions.DependencyInjection;
using Musify.Application.Configuration; using Musify.Application.Configuration;
using Musify.Application.Services; using Musify.Application.Services;
using Musify.Infrastructure.Jobs; using Musify.Infrastructure.Jobs;
@@ -41,20 +41,34 @@ public sealed class CreateAlbumRequestValidatorTests
Assert.False(result.IsValid); Assert.False(result.IsValid);
} }
[Theory] [Fact]
[InlineData(1876)] public void Validate_ReleaseYearBeforeTheEarliestBoundary_Fails()
[InlineData(1877)]
public void Validate_ReleaseYearAtOrBeforeTheEarliestBoundary(int year)
{ {
var result = validator.Validate(new CreateAlbumRequest("Title", null, year)); var result = validator.Validate(new CreateAlbumRequest("Title", null, AlbumReleaseYear.Earliest - 1));
Assert.Equal(year >= 1877, result.IsValid); Assert.False(result.IsValid);
} }
[Fact] [Fact]
public void Validate_ReleaseYearMoreThanOneYearInTheFuture_Fails() public void Validate_ReleaseYearAtTheEarliestBoundary_Passes()
{ {
var result = validator.Validate(new CreateAlbumRequest("Title", null, DateTime.UtcNow.Year + 2)); var result = validator.Validate(new CreateAlbumRequest("Title", null, AlbumReleaseYear.Earliest));
Assert.True(result.IsValid);
}
[Fact]
public void Validate_ReleaseYearAtTheLatestBoundary_Passes()
{
var result = validator.Validate(new CreateAlbumRequest("Title", null, AlbumReleaseYear.Latest));
Assert.True(result.IsValid);
}
[Fact]
public void Validate_ReleaseYearPastTheLatestBoundary_Fails()
{
var result = validator.Validate(new CreateAlbumRequest("Title", null, AlbumReleaseYear.Latest + 1));
Assert.False(result.IsValid); Assert.False(result.IsValid);
} }
@@ -1,3 +1,4 @@
using ErrorOr;
using Musify.Application.Albums; using Musify.Application.Albums;
using Musify.Application.Tests.TestSupport; using Musify.Application.Tests.TestSupport;
using Xunit; using Xunit;
@@ -37,7 +38,6 @@ public sealed class CreateAlbumCommandHandlerTests : HandlerTestBase
var result = await CreateHandler().Handle(command, CancellationToken.None); var result = await CreateHandler().Handle(command, CancellationToken.None);
Assert.True(result.IsError); Assert.Equal(ErrorType.NotFound, result.FirstError.Type);
Assert.Equal(ErrorOr.ErrorType.NotFound, result.FirstError.Type);
} }
} }
@@ -3,7 +3,6 @@ using Musify.Application.Contracts;
using Musify.Application.Mixes; using Musify.Application.Mixes;
using Musify.Application.Tests.TestSupport; using Musify.Application.Tests.TestSupport;
using Musify.Domain.Entities; using Musify.Domain.Entities;
using Musify.Domain.ValueObjects;
using NSubstitute; using NSubstitute;
using Xunit; using Xunit;
@@ -47,7 +46,7 @@ public sealed class GenerateMixesForUserCommandHandlerTests : HandlerTestBase
youTubeMusicService youTubeMusicService
.SearchSongsAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>()) .SearchSongsAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<CancellationToken>())
.Returns(new YouTubeSearchResult( .Returns(new YouTubeSearchResult(
[new YouTubeSongResult("yt-1", "YouTube Song", "Seed Artist", "Album", 200, "https://img/thumb.jpg", false, [])], [new YouTubeSongResult("yt-1", "YouTube Song", "Seed Artist", "Album", 200, "https://img/thumb.jpg", IsExplicit: false, [] )],
ContinuationToken: string.Empty)); ContinuationToken: string.Empty));
youTubeMusicService.ResolveArtworkUrl(Arg.Any<string>()).Returns(callInfo => callInfo.Arg<string>()); youTubeMusicService.ResolveArtworkUrl(Arg.Any<string>()).Returns(callInfo => callInfo.Arg<string>());
@@ -5,7 +5,6 @@ using Musify.Application.PlayLists;
using Musify.Application.Services; using Musify.Application.Services;
using Musify.Application.Tests.TestSupport; using Musify.Application.Tests.TestSupport;
using Musify.Domain.Entities; using Musify.Domain.Entities;
using Musify.Domain.ValueObjects;
using NSubstitute; using NSubstitute;
using Xunit; using Xunit;
@@ -1,5 +1,4 @@
using ErrorOr; using ErrorOr;
using Musify.Application.Configuration;
using Musify.Application.Contracts; using Musify.Application.Contracts;
using Musify.Application.PlayLists; using Musify.Application.PlayLists;
using Musify.Application.Services; using Musify.Application.Services;
@@ -1,7 +1,6 @@
using ErrorOr; using ErrorOr;
using Musify.Application.Tests.TestSupport; using Musify.Application.Tests.TestSupport;
using Musify.Application.Tracks; using Musify.Application.Tracks;
using Musify.Domain.ValueObjects;
using Xunit; using Xunit;
namespace Musify.Application.Tests.Tracks; namespace Musify.Application.Tests.Tracks;
@@ -1,4 +1,3 @@
using Microsoft.EntityFrameworkCore;
using Musify.Domain.Entities; using Musify.Domain.Entities;
using Musify.Infrastructure.Tests.TestSupport; using Musify.Infrastructure.Tests.TestSupport;
using Xunit; using Xunit;
@@ -27,9 +27,9 @@ public sealed class PictureServiceTests
await using var resized = await CreateService().ResizePictureAsWebpAsync(source, 200, 200, CancellationToken.None); await using var resized = await CreateService().ResizePictureAsWebpAsync(source, 200, 200, CancellationToken.None);
using var result = await Image.LoadAsync(resized); using var result = await Image.LoadAsync(resized);
Assert.True(result.Width <= 200); Assert.InRange(result.Width, 1, 200);
Assert.True(result.Height <= 200); Assert.InRange(result.Height, 1, 200);
Assert.True(result.Width == 200 || result.Height == 200); Assert.True(result.Width == 200 || result.Height == 200, "expected the longer side to land exactly on the target box");
} }
[Fact] [Fact]
@@ -1,7 +1,9 @@
using System.Net; using System.Net;
using System.Net.Http.Headers;
using System.Text; using System.Text;
using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Logging.Abstractions;
using Musify.Infrastructure.Configuration; using Musify.Infrastructure.Configuration;
using Musify.Infrastructure.Persistence;
using Musify.Infrastructure.Services; using Musify.Infrastructure.Services;
using Musify.Infrastructure.Tests.TestSupport; using Musify.Infrastructure.Tests.TestSupport;
using Xunit; using Xunit;
@@ -9,9 +11,12 @@ using Xunit;
namespace Musify.Infrastructure.Tests.Services; namespace Musify.Infrastructure.Tests.Services;
[Collection(InfrastructureCollection.Name)] [Collection(InfrastructureCollection.Name)]
public sealed class StorageServiceTests(InfrastructureTestFixture fixture) public sealed class StorageServiceTests(InfrastructureTestFixture fixture) : IAsyncLifetime
{ {
private StorageService CreateService(out Musify.Infrastructure.Persistence.Database database) private Database database = null!;
private StorageService service = null!;
public Task InitializeAsync()
{ {
database = fixture.CreateDatabase(); database = fixture.CreateDatabase();
var storageConfiguration = new InfrastructureStorageConfiguration var storageConfiguration = new InfrastructureStorageConfiguration
@@ -22,14 +27,15 @@ public sealed class StorageServiceTests(InfrastructureTestFixture fixture)
ForcePathStyle = true, ForcePathStyle = true,
UseHttp = true, UseHttp = true,
}; };
return new StorageService(database, fixture.CreateS3Client(), NullLogger<StorageService>.Instance, storageConfiguration); service = new StorageService(database, fixture.CreateS3Client(), NullLogger<StorageService>.Instance, storageConfiguration);
return Task.CompletedTask;
} }
public Task DisposeAsync() => database.DisposeAsync().AsTask();
[Fact] [Fact]
public async Task UploadThenGetFile_RoundTripsTheSameBytes() public async Task UploadThenGetFile_RoundTripsTheSameBytes()
{ {
var service = CreateService(out var database);
await using var _ = database;
var key = $"tests/{Guid.NewGuid():N}/round-trip.txt"; var key = $"tests/{Guid.NewGuid():N}/round-trip.txt";
var content = "hello seaweedfs"u8.ToArray(); var content = "hello seaweedfs"u8.ToArray();
@@ -45,8 +51,6 @@ public sealed class StorageServiceTests(InfrastructureTestFixture fixture)
[Fact] [Fact]
public async Task HeadObjectAsync_ExistingObject_ReturnsMetadata() public async Task HeadObjectAsync_ExistingObject_ReturnsMetadata()
{ {
var service = CreateService(out var database);
await using var _ = database;
var key = $"tests/{Guid.NewGuid():N}/head.txt"; var key = $"tests/{Guid.NewGuid():N}/head.txt";
await service.UploadFileAsync(new MemoryStream("x"u8.ToArray()), "text/plain", InfrastructureTestFixture.S3Bucket, key, CancellationToken.None); await service.UploadFileAsync(new MemoryStream("x"u8.ToArray()), "text/plain", InfrastructureTestFixture.S3Bucket, key, CancellationToken.None);
@@ -59,9 +63,6 @@ public sealed class StorageServiceTests(InfrastructureTestFixture fixture)
[Fact] [Fact]
public async Task HeadObjectAsync_MissingObject_ReturnsNull() public async Task HeadObjectAsync_MissingObject_ReturnsNull()
{ {
var service = CreateService(out var database);
await using var _ = database;
var metadata = await service.HeadObjectAsync(InfrastructureTestFixture.S3Bucket, $"tests/{Guid.NewGuid():N}/missing.txt", CancellationToken.None); var metadata = await service.HeadObjectAsync(InfrastructureTestFixture.S3Bucket, $"tests/{Guid.NewGuid():N}/missing.txt", CancellationToken.None);
Assert.Null(metadata); Assert.Null(metadata);
@@ -70,8 +71,6 @@ public sealed class StorageServiceTests(InfrastructureTestFixture fixture)
[Fact] [Fact]
public async Task RemoveFileAsync_ExistingObject_DeletesIt() public async Task RemoveFileAsync_ExistingObject_DeletesIt()
{ {
var service = CreateService(out var database);
await using var _ = database;
var key = $"tests/{Guid.NewGuid():N}/to-remove.txt"; var key = $"tests/{Guid.NewGuid():N}/to-remove.txt";
await service.UploadFileAsync(new MemoryStream("x"u8.ToArray()), "text/plain", InfrastructureTestFixture.S3Bucket, key, CancellationToken.None); await service.UploadFileAsync(new MemoryStream("x"u8.ToArray()), "text/plain", InfrastructureTestFixture.S3Bucket, key, CancellationToken.None);
@@ -83,8 +82,6 @@ public sealed class StorageServiceTests(InfrastructureTestFixture fixture)
[Fact] [Fact]
public async Task CopyFileAsync_CopiesToTheDestinationKey() public async Task CopyFileAsync_CopiesToTheDestinationKey()
{ {
var service = CreateService(out var database);
await using var _ = database;
var sourceKey = $"tests/{Guid.NewGuid():N}/source.txt"; var sourceKey = $"tests/{Guid.NewGuid():N}/source.txt";
var destinationKey = $"tests/{Guid.NewGuid():N}/destination.txt"; var destinationKey = $"tests/{Guid.NewGuid():N}/destination.txt";
await service.UploadFileAsync(new MemoryStream("copy-me"u8.ToArray()), "text/plain", InfrastructureTestFixture.S3Bucket, sourceKey, CancellationToken.None); await service.UploadFileAsync(new MemoryStream("copy-me"u8.ToArray()), "text/plain", InfrastructureTestFixture.S3Bucket, sourceKey, CancellationToken.None);
@@ -97,8 +94,6 @@ public sealed class StorageServiceTests(InfrastructureTestFixture fixture)
[Fact] [Fact]
public async Task ListObjectsAsync_ReturnsEveryObjectUnderThePrefix() public async Task ListObjectsAsync_ReturnsEveryObjectUnderThePrefix()
{ {
var service = CreateService(out var database);
await using var _ = database;
var prefix = $"tests/{Guid.NewGuid():N}"; var prefix = $"tests/{Guid.NewGuid():N}";
await service.UploadFileAsync(new MemoryStream("a"u8.ToArray()), "text/plain", InfrastructureTestFixture.S3Bucket, $"{prefix}/a.txt", CancellationToken.None); await service.UploadFileAsync(new MemoryStream("a"u8.ToArray()), "text/plain", InfrastructureTestFixture.S3Bucket, $"{prefix}/a.txt", CancellationToken.None);
await service.UploadFileAsync(new MemoryStream("b"u8.ToArray()), "text/plain", InfrastructureTestFixture.S3Bucket, $"{prefix}/b.txt", CancellationToken.None); await service.UploadFileAsync(new MemoryStream("b"u8.ToArray()), "text/plain", InfrastructureTestFixture.S3Bucket, $"{prefix}/b.txt", CancellationToken.None);
@@ -113,8 +108,6 @@ public sealed class StorageServiceTests(InfrastructureTestFixture fixture)
[Fact] [Fact]
public async Task RemoveFolderAsync_DeletesEveryObjectUnderThePrefix() public async Task RemoveFolderAsync_DeletesEveryObjectUnderThePrefix()
{ {
var service = CreateService(out var database);
await using var _ = database;
var prefix = $"tests/{Guid.NewGuid():N}"; var prefix = $"tests/{Guid.NewGuid():N}";
await service.UploadFileAsync(new MemoryStream("a"u8.ToArray()), "text/plain", InfrastructureTestFixture.S3Bucket, $"{prefix}/a.txt", CancellationToken.None); await service.UploadFileAsync(new MemoryStream("a"u8.ToArray()), "text/plain", InfrastructureTestFixture.S3Bucket, $"{prefix}/a.txt", CancellationToken.None);
await service.UploadFileAsync(new MemoryStream("b"u8.ToArray()), "text/plain", InfrastructureTestFixture.S3Bucket, $"{prefix}/nested/b.txt", CancellationToken.None); await service.UploadFileAsync(new MemoryStream("b"u8.ToArray()), "text/plain", InfrastructureTestFixture.S3Bucket, $"{prefix}/nested/b.txt", CancellationToken.None);
@@ -130,8 +123,6 @@ public sealed class StorageServiceTests(InfrastructureTestFixture fixture)
[Fact] [Fact]
public async Task GetUploadUrlAsync_PresignedPut_CanActuallyUploadTheObject() public async Task GetUploadUrlAsync_PresignedPut_CanActuallyUploadTheObject()
{ {
var service = CreateService(out var database);
await using var _ = database;
var key = $"tests/{Guid.NewGuid():N}/presigned.txt"; var key = $"tests/{Guid.NewGuid():N}/presigned.txt";
var uploadUrl = await service.GetUploadUrlAsync( var uploadUrl = await service.GetUploadUrlAsync(
@@ -145,15 +136,14 @@ public sealed class StorageServiceTests(InfrastructureTestFixture fixture)
// signs Content-Type byte-for-byte) and the server answers 403 SignatureDoesNotMatch. // signs Content-Type byte-for-byte) and the server answers 403 SignatureDoesNotMatch.
Content = new ByteArrayContent(Encoding.UTF8.GetBytes("presigned content")) Content = new ByteArrayContent(Encoding.UTF8.GetBytes("presigned content"))
}; };
request.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("text/plain"); request.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
// GetUploadUrlAsync defaults preventOverwrite to true, which signs the URL together with // GetUploadUrlAsync defaults preventOverwrite to true, which signs the URL together with
// this header (see StorageService.GetUploadUrlAsync) — the actual PUT has to send it too, // this header (see StorageService.GetUploadUrlAsync) — the actual PUT has to send it too,
// or the signature no longer matches and the server answers 403. // or the signature no longer matches and the server answers 403.
request.Headers.TryAddWithoutValidation("If-None-Match", "*"); request.Headers.TryAddWithoutValidation("If-None-Match", "*");
var response = await httpClient.SendAsync(request); var response = await httpClient.SendAsync(request);
var responseBody = await response.Content.ReadAsStringAsync();
Assert.True(response.StatusCode == HttpStatusCode.OK, $"status={response.StatusCode}, body={responseBody}"); Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var metadata = await service.HeadObjectAsync(InfrastructureTestFixture.S3Bucket, key, CancellationToken.None); var metadata = await service.HeadObjectAsync(InfrastructureTestFixture.S3Bucket, key, CancellationToken.None);
Assert.NotNull(metadata); Assert.NotNull(metadata);
Assert.Equal("presigned content".Length, metadata.ContentLength); Assert.Equal("presigned content".Length, metadata.ContentLength);