Add editorconfig and analyzers, format backend code
This commit is contained in:
+35
-36
@@ -3,52 +3,51 @@ using Musify.Domain.Entities;
|
||||
using Musify.Infrastructure.Tests.TestSupport;
|
||||
using Xunit;
|
||||
|
||||
namespace Musify.Infrastructure.Tests.Persistence
|
||||
namespace Musify.Infrastructure.Tests.Persistence;
|
||||
|
||||
[Collection(InfrastructureCollection.Name)]
|
||||
public sealed class AuditableEntityInterceptorTests(InfrastructureTestFixture fixture)
|
||||
{
|
||||
[Collection(InfrastructureCollection.Name)]
|
||||
public sealed class AuditableEntityInterceptorTests(InfrastructureTestFixture fixture)
|
||||
[Fact]
|
||||
public async Task SavingChanges_NewEntity_SetsCreatedAtAndUpdatedAtToNow()
|
||||
{
|
||||
[Fact]
|
||||
public async Task SavingChanges_NewEntity_SetsCreatedAtAndUpdatedAtToNow()
|
||||
{
|
||||
await using var database = fixture.CreateDatabase();
|
||||
var before = DateTime.UtcNow;
|
||||
await using var database = fixture.CreateDatabase();
|
||||
var before = DateTime.UtcNow;
|
||||
|
||||
var name = "audit-user";
|
||||
var user = new User { Id = Random.Shared.NextInt64(1, long.MaxValue), Name = name, NormalizedName = name.ToUpperInvariant() };
|
||||
await database.Users.AddAsync(user, TestContext.Current.CancellationToken);
|
||||
await database.SaveChangesAsync(TestContext.Current.CancellationToken);
|
||||
var name = "audit-user";
|
||||
var user = new User { Id = Random.Shared.NextInt64(1, long.MaxValue), Name = name, NormalizedName = name.ToUpperInvariant() };
|
||||
await database.Users.AddAsync(user, TestContext.Current.CancellationToken);
|
||||
await database.SaveChangesAsync(TestContext.Current.CancellationToken);
|
||||
|
||||
var after = DateTime.UtcNow;
|
||||
var after = DateTime.UtcNow;
|
||||
|
||||
Assert.InRange(user.CreatedAt, before, after);
|
||||
Assert.InRange(user.UpdatedAt, before, after);
|
||||
}
|
||||
Assert.InRange(user.CreatedAt, before, after);
|
||||
Assert.InRange(user.UpdatedAt, before, after);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SavingChanges_ModifiedEntity_BumpsUpdatedAtButKeepsCreatedAt()
|
||||
{
|
||||
await using var database = fixture.CreateDatabase();
|
||||
[Fact]
|
||||
public async Task SavingChanges_ModifiedEntity_BumpsUpdatedAtButKeepsCreatedAt()
|
||||
{
|
||||
await using var database = fixture.CreateDatabase();
|
||||
|
||||
var name = "audit-user-2";
|
||||
var user = new User { Id = Random.Shared.NextInt64(1, long.MaxValue), Name = name, NormalizedName = name.ToUpperInvariant() };
|
||||
await database.Users.AddAsync(user, TestContext.Current.CancellationToken);
|
||||
await database.SaveChangesAsync(TestContext.Current.CancellationToken);
|
||||
var originalCreatedAt = user.CreatedAt;
|
||||
var name = "audit-user-2";
|
||||
var user = new User { Id = Random.Shared.NextInt64(1, long.MaxValue), Name = name, NormalizedName = name.ToUpperInvariant() };
|
||||
await database.Users.AddAsync(user, TestContext.Current.CancellationToken);
|
||||
await database.SaveChangesAsync(TestContext.Current.CancellationToken);
|
||||
var originalCreatedAt = user.CreatedAt;
|
||||
|
||||
await Task.Delay(TimeSpan.FromMilliseconds(50), TestContext.Current.CancellationToken);
|
||||
await Task.Delay(TimeSpan.FromMilliseconds(50), TestContext.Current.CancellationToken);
|
||||
|
||||
user.Name = "audit-user-2-renamed";
|
||||
await database.SaveChangesAsync(TestContext.Current.CancellationToken);
|
||||
user.Name = "audit-user-2-renamed";
|
||||
await database.SaveChangesAsync(TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.Equal(originalCreatedAt, user.CreatedAt);
|
||||
Assert.True(user.UpdatedAt > originalCreatedAt,
|
||||
$"original-created-at={originalCreatedAt:O}, final-updated-at={user.UpdatedAt:O}");
|
||||
Assert.Equal(originalCreatedAt, user.CreatedAt);
|
||||
Assert.True(user.UpdatedAt > originalCreatedAt,
|
||||
$"original-created-at={originalCreatedAt:O}, final-updated-at={user.UpdatedAt:O}");
|
||||
|
||||
await using var reader = fixture.CreateDatabase();
|
||||
var stored = await reader.Users.SingleAsync(u => u.Id == user.Id, TestContext.Current.CancellationToken);
|
||||
Assert.True(stored.UpdatedAt > stored.CreatedAt,
|
||||
$"stored-created-at={stored.CreatedAt:O}, stored-updated-at={stored.UpdatedAt:O}");
|
||||
}
|
||||
await using var reader = fixture.CreateDatabase();
|
||||
var stored = await reader.Users.SingleAsync(u => u.Id == user.Id, TestContext.Current.CancellationToken);
|
||||
Assert.True(stored.UpdatedAt > stored.CreatedAt,
|
||||
$"stored-created-at={stored.CreatedAt:O}, stored-updated-at={stored.UpdatedAt:O}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,105 +4,104 @@ using Musify.Domain.ValueObjects;
|
||||
using Musify.Infrastructure.Tests.TestSupport;
|
||||
using Xunit;
|
||||
|
||||
namespace Musify.Infrastructure.Tests.Persistence
|
||||
namespace Musify.Infrastructure.Tests.Persistence;
|
||||
|
||||
[Collection(InfrastructureCollection.Name)]
|
||||
public sealed class DatabaseTests(InfrastructureTestFixture fixture)
|
||||
{
|
||||
[Collection(InfrastructureCollection.Name)]
|
||||
public sealed class DatabaseTests(InfrastructureTestFixture fixture)
|
||||
[Fact]
|
||||
public async Task SaveChangesAsync_TrackWithOwnedTypes_RoundTripsThroughPostgres()
|
||||
{
|
||||
[Fact]
|
||||
public async Task SaveChangesAsync_TrackWithOwnedTypes_RoundTripsThroughPostgres()
|
||||
await using var database = fixture.CreateDatabase();
|
||||
|
||||
var userName = "roundtrip-user";
|
||||
var user = new User { Id = Random.Shared.NextInt64(1, long.MaxValue), Name = userName, NormalizedName = userName.ToUpperInvariant() };
|
||||
await database.Users.AddAsync(user, TestContext.Current.CancellationToken);
|
||||
|
||||
var trackTitle = "Round Trip Track";
|
||||
var track = new Track
|
||||
{
|
||||
await using var database = fixture.CreateDatabase();
|
||||
Title = trackTitle,
|
||||
NormalizedTitle = trackTitle.ToUpperInvariant(),
|
||||
DurationSeconds = 123.4,
|
||||
OwnerUserId = user.Id,
|
||||
Owner = user,
|
||||
Pictures = new TrackPictures { OriginalName = "cover.webp", ProcessingStatus = ProcessingStatus.Pending },
|
||||
Audio = new TrackAudio { OriginalName = "song.mp3", TranscodeStatus = ProcessingStatus.Pending }
|
||||
};
|
||||
await database.Tracks.AddAsync(track, TestContext.Current.CancellationToken);
|
||||
await database.SaveChangesAsync(TestContext.Current.CancellationToken);
|
||||
|
||||
var userName = "roundtrip-user";
|
||||
var user = new User { Id = Random.Shared.NextInt64(1, long.MaxValue), Name = userName, NormalizedName = userName.ToUpperInvariant() };
|
||||
await database.Users.AddAsync(user, TestContext.Current.CancellationToken);
|
||||
await using var reloaded = fixture.CreateDatabase();
|
||||
var stored = await reloaded.Tracks.AsNoTracking().SingleAsync(t => t.Id == track.Id, TestContext.Current.CancellationToken);
|
||||
|
||||
var trackTitle = "Round Trip Track";
|
||||
var track = new Track
|
||||
{
|
||||
Title = trackTitle,
|
||||
NormalizedTitle = trackTitle.ToUpperInvariant(),
|
||||
DurationSeconds = 123.4,
|
||||
OwnerUserId = user.Id,
|
||||
Owner = user,
|
||||
Pictures = new TrackPictures { OriginalName = "cover.webp", ProcessingStatus = ProcessingStatus.Pending },
|
||||
Audio = new TrackAudio { OriginalName = "song.mp3", TranscodeStatus = ProcessingStatus.Pending }
|
||||
};
|
||||
await database.Tracks.AddAsync(track, TestContext.Current.CancellationToken);
|
||||
await database.SaveChangesAsync(TestContext.Current.CancellationToken);
|
||||
Assert.Equal(trackTitle, stored.Title);
|
||||
Assert.Equal("cover.webp", stored.Pictures.OriginalName);
|
||||
Assert.Equal("song.mp3", stored.Audio.OriginalName);
|
||||
Assert.Equal(user.Id, stored.OwnerUserId);
|
||||
}
|
||||
|
||||
await using var reloaded = fixture.CreateDatabase();
|
||||
var stored = await reloaded.Tracks.AsNoTracking().SingleAsync(t => t.Id == track.Id, TestContext.Current.CancellationToken);
|
||||
[Fact]
|
||||
public async Task SaveChangesAsync_TrackWithTags_RoundTripsThroughNativePostgresEnum()
|
||||
{
|
||||
await using var database = fixture.CreateDatabase();
|
||||
|
||||
Assert.Equal(trackTitle, stored.Title);
|
||||
Assert.Equal("cover.webp", stored.Pictures.OriginalName);
|
||||
Assert.Equal("song.mp3", stored.Audio.OriginalName);
|
||||
Assert.Equal(user.Id, stored.OwnerUserId);
|
||||
}
|
||||
var userName = "tags-roundtrip-user";
|
||||
var user = new User { Id = Random.Shared.NextInt64(1, long.MaxValue), Name = userName, NormalizedName = userName.ToUpperInvariant() };
|
||||
var track = BuildTrack(user, $"tags-{Guid.NewGuid():N}");
|
||||
track.Tags =
|
||||
[
|
||||
new TrackTag { TrackId = track.Id, Tag = Genre.Pop },
|
||||
new TrackTag { TrackId = track.Id, Tag = Genre.Rock }
|
||||
];
|
||||
|
||||
[Fact]
|
||||
public async Task SaveChangesAsync_TrackWithTags_RoundTripsThroughNativePostgresEnum()
|
||||
await database.AddRangeAsync(user, track);
|
||||
await database.SaveChangesAsync(TestContext.Current.CancellationToken);
|
||||
|
||||
await using var reloaded = fixture.CreateDatabase();
|
||||
var stored = await reloaded.Tracks.AsNoTracking()
|
||||
.Include(t => t.Tags)
|
||||
.SingleAsync(t => t.Id == track.Id, TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.Equal([Genre.Pop, Genre.Rock], stored.Tags.Select(t => t.Tag).OrderBy(t => t));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AlbumHasTracks_DeletingAlbum_CascadesToTheLinkRows()
|
||||
{
|
||||
await using var database = fixture.CreateDatabase();
|
||||
|
||||
var userName = "cascade-user";
|
||||
var user = new User { Id = Random.Shared.NextInt64(1, long.MaxValue), Name = userName, NormalizedName = userName.ToUpperInvariant() };
|
||||
var albumTitle = "Cascade Album";
|
||||
var album = new Album { Title = albumTitle, NormalizedTitle = albumTitle.ToUpperInvariant(), OwnerUserId = user.Id };
|
||||
var track = BuildTrack(user, $"cascade-{Guid.NewGuid():N}");
|
||||
var link = new AlbumHasTrack { AlbumId = album.Id, TrackId = track.Id, TrackNumber = 1 };
|
||||
|
||||
await database.AddRangeAsync(user, album, track, link);
|
||||
await database.SaveChangesAsync(TestContext.Current.CancellationToken);
|
||||
|
||||
await using var deleter = fixture.CreateDatabase();
|
||||
var albumToDelete = await deleter.Albums.SingleAsync(a => a.Id == album.Id, TestContext.Current.CancellationToken);
|
||||
deleter.Albums.Remove(albumToDelete);
|
||||
await deleter.SaveChangesAsync(TestContext.Current.CancellationToken);
|
||||
|
||||
await using var verifier = fixture.CreateDatabase();
|
||||
Assert.False(await verifier.AlbumHasTracks.AnyAsync(l => l.AlbumId == album.Id, TestContext.Current.CancellationToken));
|
||||
Assert.True(await verifier.Tracks.AnyAsync(t => t.Id == track.Id, TestContext.Current.CancellationToken));
|
||||
}
|
||||
|
||||
private static Track BuildTrack(User owner, string title)
|
||||
{
|
||||
return new Track
|
||||
{
|
||||
await using var database = fixture.CreateDatabase();
|
||||
|
||||
var userName = "tags-roundtrip-user";
|
||||
var user = new User { Id = Random.Shared.NextInt64(1, long.MaxValue), Name = userName, NormalizedName = userName.ToUpperInvariant() };
|
||||
var track = BuildTrack(user, $"tags-{Guid.NewGuid():N}");
|
||||
track.Tags =
|
||||
[
|
||||
new TrackTag { TrackId = track.Id, Tag = Genre.Pop },
|
||||
new TrackTag { TrackId = track.Id, Tag = Genre.Rock }
|
||||
];
|
||||
|
||||
await database.AddRangeAsync(user, track);
|
||||
await database.SaveChangesAsync(TestContext.Current.CancellationToken);
|
||||
|
||||
await using var reloaded = fixture.CreateDatabase();
|
||||
var stored = await reloaded.Tracks.AsNoTracking()
|
||||
.Include(t => t.Tags)
|
||||
.SingleAsync(t => t.Id == track.Id, TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.Equal([Genre.Pop, Genre.Rock], stored.Tags.Select(t => t.Tag).OrderBy(t => t));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AlbumHasTracks_DeletingAlbum_CascadesToTheLinkRows()
|
||||
{
|
||||
await using var database = fixture.CreateDatabase();
|
||||
|
||||
var userName = "cascade-user";
|
||||
var user = new User { Id = Random.Shared.NextInt64(1, long.MaxValue), Name = userName, NormalizedName = userName.ToUpperInvariant() };
|
||||
var albumTitle = "Cascade Album";
|
||||
var album = new Album { Title = albumTitle, NormalizedTitle = albumTitle.ToUpperInvariant(), OwnerUserId = user.Id };
|
||||
var track = BuildTrack(user, $"cascade-{Guid.NewGuid():N}");
|
||||
var link = new AlbumHasTrack { AlbumId = album.Id, TrackId = track.Id, TrackNumber = 1 };
|
||||
|
||||
await database.AddRangeAsync(user, album, track, link);
|
||||
await database.SaveChangesAsync(TestContext.Current.CancellationToken);
|
||||
|
||||
await using var deleter = fixture.CreateDatabase();
|
||||
var albumToDelete = await deleter.Albums.SingleAsync(a => a.Id == album.Id, TestContext.Current.CancellationToken);
|
||||
deleter.Albums.Remove(albumToDelete);
|
||||
await deleter.SaveChangesAsync(TestContext.Current.CancellationToken);
|
||||
|
||||
await using var verifier = fixture.CreateDatabase();
|
||||
Assert.False(await verifier.AlbumHasTracks.AnyAsync(l => l.AlbumId == album.Id, TestContext.Current.CancellationToken));
|
||||
Assert.True(await verifier.Tracks.AnyAsync(t => t.Id == track.Id, TestContext.Current.CancellationToken));
|
||||
}
|
||||
|
||||
private static Track BuildTrack(User owner, string title)
|
||||
{
|
||||
return new Track
|
||||
{
|
||||
Title = title,
|
||||
NormalizedTitle = title.ToUpperInvariant(),
|
||||
DurationSeconds = 100,
|
||||
OwnerUserId = owner.Id,
|
||||
Owner = owner,
|
||||
Pictures = new TrackPictures(),
|
||||
Audio = new TrackAudio()
|
||||
};
|
||||
}
|
||||
Title = title,
|
||||
NormalizedTitle = title.ToUpperInvariant(),
|
||||
DurationSeconds = 100,
|
||||
OwnerUserId = owner.Id,
|
||||
Owner = owner,
|
||||
Pictures = new TrackPictures(),
|
||||
Audio = new TrackAudio()
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,55 +4,54 @@ using SixLabors.ImageSharp;
|
||||
using SixLabors.ImageSharp.PixelFormats;
|
||||
using Xunit;
|
||||
|
||||
namespace Musify.Infrastructure.Tests.Services
|
||||
namespace Musify.Infrastructure.Tests.Services;
|
||||
|
||||
public sealed class PictureServiceTests
|
||||
{
|
||||
public sealed class PictureServiceTests
|
||||
private static PictureService CreateService() => new(NullLogger<PictureService>.Instance);
|
||||
|
||||
private static MemoryStream CreateSourceImage(int width, int height)
|
||||
{
|
||||
private static PictureService CreateService() => new(NullLogger<PictureService>.Instance);
|
||||
using var image = new Image<Rgba32>(width, height, new Rgba32(255, 0, 0));
|
||||
var stream = new MemoryStream();
|
||||
image.SaveAsPng(stream);
|
||||
stream.Position = 0;
|
||||
return stream;
|
||||
}
|
||||
|
||||
private static MemoryStream CreateSourceImage(int width, int height)
|
||||
{
|
||||
using var image = new Image<Rgba32>(width, height, new Rgba32(255, 0, 0));
|
||||
var stream = new MemoryStream();
|
||||
image.SaveAsPng(stream);
|
||||
stream.Position = 0;
|
||||
return stream;
|
||||
}
|
||||
[Fact]
|
||||
public async Task ResizePictureAsWebpAsync_LargerThanTarget_ShrinksToFitWithinTheRequestedBox()
|
||||
{
|
||||
using var source = CreateSourceImage(800, 600);
|
||||
|
||||
[Fact]
|
||||
public async Task ResizePictureAsWebpAsync_LargerThanTarget_ShrinksToFitWithinTheRequestedBox()
|
||||
{
|
||||
using var source = CreateSourceImage(800, 600);
|
||||
await using var resized = await CreateService().ResizePictureAsWebpAsync(source, 200, 200, TestContext.Current.CancellationToken);
|
||||
|
||||
await using var resized = await CreateService().ResizePictureAsWebpAsync(source, 200, 200, TestContext.Current.CancellationToken);
|
||||
using var result = await Image.LoadAsync(resized, TestContext.Current.CancellationToken);
|
||||
Assert.InRange(result.Width, 1, 200);
|
||||
Assert.InRange(result.Height, 1, 200);
|
||||
Assert.True(result.Width == 200 || result.Height == 200, "expected the longer side to land exactly on the target box");
|
||||
}
|
||||
|
||||
using var result = await Image.LoadAsync(resized, TestContext.Current.CancellationToken);
|
||||
Assert.InRange(result.Width, 1, 200);
|
||||
Assert.InRange(result.Height, 1, 200);
|
||||
Assert.True(result.Width == 200 || result.Height == 200, "expected the longer side to land exactly on the target box");
|
||||
}
|
||||
[Fact]
|
||||
public async Task ResizePictureAsWebpAsync_ReturnsAValidWebpStream()
|
||||
{
|
||||
using var source = CreateSourceImage(100, 100);
|
||||
|
||||
[Fact]
|
||||
public async Task ResizePictureAsWebpAsync_ReturnsAValidWebpStream()
|
||||
{
|
||||
using var source = CreateSourceImage(100, 100);
|
||||
await using var resized = await CreateService().ResizePictureAsWebpAsync(source, 50, 50, TestContext.Current.CancellationToken);
|
||||
|
||||
await using var resized = await CreateService().ResizePictureAsWebpAsync(source, 50, 50, TestContext.Current.CancellationToken);
|
||||
var format = await Image.DetectFormatAsync(resized, TestContext.Current.CancellationToken);
|
||||
Assert.Equal("WEBP", format?.Name, ignoreCase: true);
|
||||
}
|
||||
|
||||
var format = await Image.DetectFormatAsync(resized, TestContext.Current.CancellationToken);
|
||||
Assert.Equal("WEBP", format?.Name, ignoreCase: true);
|
||||
}
|
||||
[Fact]
|
||||
public async Task ResizePictureAsWebpAsync_PreservesAspectRatio()
|
||||
{
|
||||
using var source = CreateSourceImage(400, 200);
|
||||
|
||||
[Fact]
|
||||
public async Task ResizePictureAsWebpAsync_PreservesAspectRatio()
|
||||
{
|
||||
using var source = CreateSourceImage(400, 200);
|
||||
await using var resized = await CreateService().ResizePictureAsWebpAsync(source, 100, 100, TestContext.Current.CancellationToken);
|
||||
|
||||
await using var resized = await CreateService().ResizePictureAsWebpAsync(source, 100, 100, TestContext.Current.CancellationToken);
|
||||
|
||||
using var result = await Image.LoadAsync(resized, TestContext.Current.CancellationToken);
|
||||
Assert.Equal(100, result.Width);
|
||||
Assert.Equal(50, result.Height);
|
||||
}
|
||||
using var result = await Image.LoadAsync(resized, TestContext.Current.CancellationToken);
|
||||
Assert.Equal(100, result.Width);
|
||||
Assert.Equal(50, result.Height);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,79 +3,78 @@ using Microsoft.Extensions.Caching.Memory;
|
||||
using Musify.Infrastructure.Services;
|
||||
using Xunit;
|
||||
|
||||
namespace Musify.Infrastructure.Tests.Services
|
||||
namespace Musify.Infrastructure.Tests.Services;
|
||||
|
||||
public sealed class SingleFlightCacheTests
|
||||
{
|
||||
public sealed class SingleFlightCacheTests
|
||||
private static SingleFlightCache CreateCache() => new(new MemoryCache(new MemoryCacheOptions()));
|
||||
|
||||
[Fact]
|
||||
public async Task GetOrCreateAsync_SecondCallWithinDuration_ReturnsCachedValueWithoutCallingFactory()
|
||||
{
|
||||
private static SingleFlightCache CreateCache() => new(new MemoryCache(new MemoryCacheOptions()));
|
||||
var cache = CreateCache();
|
||||
var calls = 0;
|
||||
Task<ErrorOr<int>> Factory() { calls++; return Task.FromResult<ErrorOr<int>>(calls); }
|
||||
|
||||
[Fact]
|
||||
public async Task GetOrCreateAsync_SecondCallWithinDuration_ReturnsCachedValueWithoutCallingFactory()
|
||||
var first = await cache.GetOrCreateAsync("key", TimeSpan.FromMinutes(1), Factory);
|
||||
var second = await cache.GetOrCreateAsync("key", TimeSpan.FromMinutes(1), Factory);
|
||||
|
||||
Assert.Equal(1, first.Value);
|
||||
Assert.Equal(1, second.Value);
|
||||
Assert.Equal(1, calls);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetOrCreateAsync_ConcurrentCallsForTheSameKey_CollapseIntoASingleFactoryCall()
|
||||
{
|
||||
var cache = CreateCache();
|
||||
var calls = 0;
|
||||
var gate = new TaskCompletionSource();
|
||||
|
||||
async Task<ErrorOr<int>> Factory()
|
||||
{
|
||||
var cache = CreateCache();
|
||||
var calls = 0;
|
||||
Task<ErrorOr<int>> Factory() { calls++; return Task.FromResult<ErrorOr<int>>(calls); }
|
||||
|
||||
var first = await cache.GetOrCreateAsync("key", TimeSpan.FromMinutes(1), Factory);
|
||||
var second = await cache.GetOrCreateAsync("key", TimeSpan.FromMinutes(1), Factory);
|
||||
|
||||
Assert.Equal(1, first.Value);
|
||||
Assert.Equal(1, second.Value);
|
||||
Assert.Equal(1, calls);
|
||||
Interlocked.Increment(ref calls);
|
||||
await gate.Task;
|
||||
return 7;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetOrCreateAsync_ConcurrentCallsForTheSameKey_CollapseIntoASingleFactoryCall()
|
||||
var first = cache.GetOrCreateAsync("concurrent-key", TimeSpan.FromMinutes(1), Factory);
|
||||
var second = cache.GetOrCreateAsync("concurrent-key", TimeSpan.FromMinutes(1), Factory);
|
||||
gate.SetResult();
|
||||
|
||||
var results = await Task.WhenAll(first, second);
|
||||
|
||||
Assert.Equal(1, calls);
|
||||
Assert.All(results, result => Assert.Equal(7, result.Value));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetOrCreateAsync_FactoryReturnsError_DoesNotCacheIt()
|
||||
{
|
||||
var cache = CreateCache();
|
||||
var calls = 0;
|
||||
Task<ErrorOr<int>> Factory()
|
||||
{
|
||||
var cache = CreateCache();
|
||||
var calls = 0;
|
||||
var gate = new TaskCompletionSource();
|
||||
|
||||
async Task<ErrorOr<int>> Factory()
|
||||
{
|
||||
Interlocked.Increment(ref calls);
|
||||
await gate.Task;
|
||||
return 7;
|
||||
}
|
||||
|
||||
var first = cache.GetOrCreateAsync("concurrent-key", TimeSpan.FromMinutes(1), Factory);
|
||||
var second = cache.GetOrCreateAsync("concurrent-key", TimeSpan.FromMinutes(1), Factory);
|
||||
gate.SetResult();
|
||||
|
||||
var results = await Task.WhenAll(first, second);
|
||||
|
||||
Assert.Equal(1, calls);
|
||||
Assert.All(results, result => Assert.Equal(7, result.Value));
|
||||
calls++;
|
||||
return Task.FromResult<ErrorOr<int>>(Error.Failure(description: "boom"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetOrCreateAsync_FactoryReturnsError_DoesNotCacheIt()
|
||||
{
|
||||
var cache = CreateCache();
|
||||
var calls = 0;
|
||||
Task<ErrorOr<int>> Factory()
|
||||
{
|
||||
calls++;
|
||||
return Task.FromResult<ErrorOr<int>>(Error.Failure(description: "boom"));
|
||||
}
|
||||
await cache.GetOrCreateAsync("error-key", TimeSpan.FromMinutes(1), Factory);
|
||||
await cache.GetOrCreateAsync("error-key", TimeSpan.FromMinutes(1), Factory);
|
||||
|
||||
await cache.GetOrCreateAsync("error-key", TimeSpan.FromMinutes(1), Factory);
|
||||
await cache.GetOrCreateAsync("error-key", TimeSpan.FromMinutes(1), Factory);
|
||||
Assert.Equal(2, calls);
|
||||
}
|
||||
|
||||
Assert.Equal(2, calls);
|
||||
}
|
||||
[Fact]
|
||||
public async Task GetOrCreateAsync_NonPositiveDuration_AlwaysCallsTheFactory()
|
||||
{
|
||||
var cache = CreateCache();
|
||||
var calls = 0;
|
||||
Task<ErrorOr<int>> Factory() { calls++; return Task.FromResult<ErrorOr<int>>(calls); }
|
||||
|
||||
[Fact]
|
||||
public async Task GetOrCreateAsync_NonPositiveDuration_AlwaysCallsTheFactory()
|
||||
{
|
||||
var cache = CreateCache();
|
||||
var calls = 0;
|
||||
Task<ErrorOr<int>> Factory() { calls++; return Task.FromResult<ErrorOr<int>>(calls); }
|
||||
await cache.GetOrCreateAsync("no-cache-key", TimeSpan.Zero, Factory);
|
||||
await cache.GetOrCreateAsync("no-cache-key", TimeSpan.Zero, Factory);
|
||||
|
||||
await cache.GetOrCreateAsync("no-cache-key", TimeSpan.Zero, Factory);
|
||||
await cache.GetOrCreateAsync("no-cache-key", TimeSpan.Zero, Factory);
|
||||
|
||||
Assert.Equal(2, calls);
|
||||
}
|
||||
Assert.Equal(2, calls);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,139 +8,138 @@ using Musify.Infrastructure.Services;
|
||||
using Musify.Infrastructure.Tests.TestSupport;
|
||||
using Xunit;
|
||||
|
||||
namespace Musify.Infrastructure.Tests.Services
|
||||
namespace Musify.Infrastructure.Tests.Services;
|
||||
|
||||
[Collection(InfrastructureCollection.Name)]
|
||||
public sealed class StorageServiceTests(InfrastructureTestFixture fixture) : IAsyncLifetime
|
||||
{
|
||||
[Collection(InfrastructureCollection.Name)]
|
||||
public sealed class StorageServiceTests(InfrastructureTestFixture fixture) : IAsyncLifetime
|
||||
private Database database = null!;
|
||||
private StorageService service = null!;
|
||||
|
||||
public ValueTask InitializeAsync()
|
||||
{
|
||||
private Database database = null!;
|
||||
private StorageService service = null!;
|
||||
|
||||
public ValueTask InitializeAsync()
|
||||
database = fixture.CreateDatabase();
|
||||
var storageConfiguration = new InfrastructureStorageConfiguration
|
||||
{
|
||||
database = fixture.CreateDatabase();
|
||||
var storageConfiguration = new InfrastructureStorageConfiguration
|
||||
{
|
||||
Address = fixture.S3ServiceUrl,
|
||||
AccessKey = InfrastructureTestFixture.S3AccessKey,
|
||||
SecretAccessKey = InfrastructureTestFixture.S3SecretKey,
|
||||
ForcePathStyle = true,
|
||||
UseHttp = true,
|
||||
};
|
||||
service = new StorageService(database, fixture.CreateS3Client(), NullLogger<StorageService>.Instance, storageConfiguration);
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
Address = fixture.S3ServiceUrl,
|
||||
AccessKey = InfrastructureTestFixture.S3AccessKey,
|
||||
SecretAccessKey = InfrastructureTestFixture.S3SecretKey,
|
||||
ForcePathStyle = true,
|
||||
UseHttp = true,
|
||||
};
|
||||
service = new StorageService(database, fixture.CreateS3Client(), NullLogger<StorageService>.Instance, storageConfiguration);
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
|
||||
public ValueTask DisposeAsync() => database.DisposeAsync();
|
||||
public ValueTask DisposeAsync() => database.DisposeAsync();
|
||||
|
||||
[Fact]
|
||||
public async Task UploadThenGetFile_RoundTripsTheSameBytes()
|
||||
[Fact]
|
||||
public async Task UploadThenGetFile_RoundTripsTheSameBytes()
|
||||
{
|
||||
var key = $"tests/{Guid.NewGuid():N}/round-trip.txt";
|
||||
var content = "hello seaweedfs"u8.ToArray();
|
||||
|
||||
await service.UploadFileAsync(new MemoryStream(content), "text/plain", InfrastructureTestFixture.S3Bucket, key, TestContext.Current.CancellationToken);
|
||||
|
||||
await using var stream = await service.GetFileAsync(InfrastructureTestFixture.S3Bucket, key, TestContext.Current.CancellationToken);
|
||||
using var reader = new StreamReader(stream, Encoding.UTF8);
|
||||
var readBack = await reader.ReadToEndAsync(TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.Equal("hello seaweedfs", readBack);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HeadObjectAsync_ExistingObject_ReturnsMetadata()
|
||||
{
|
||||
var key = $"tests/{Guid.NewGuid():N}/head.txt";
|
||||
await service.UploadFileAsync(new MemoryStream("x"u8.ToArray()), "text/plain", InfrastructureTestFixture.S3Bucket, key, TestContext.Current.CancellationToken);
|
||||
|
||||
var metadata = await service.HeadObjectAsync(InfrastructureTestFixture.S3Bucket, key, TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.NotNull(metadata);
|
||||
Assert.Equal(1, metadata.ContentLength);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HeadObjectAsync_MissingObject_ReturnsNull()
|
||||
{
|
||||
var metadata = await service.HeadObjectAsync(InfrastructureTestFixture.S3Bucket, $"tests/{Guid.NewGuid():N}/missing.txt", TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.Null(metadata);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveFileAsync_ExistingObject_DeletesIt()
|
||||
{
|
||||
var key = $"tests/{Guid.NewGuid():N}/to-remove.txt";
|
||||
await service.UploadFileAsync(new MemoryStream("x"u8.ToArray()), "text/plain", InfrastructureTestFixture.S3Bucket, key, TestContext.Current.CancellationToken);
|
||||
|
||||
await service.RemoveFileAsync(InfrastructureTestFixture.S3Bucket, key, TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.Null(await service.HeadObjectAsync(InfrastructureTestFixture.S3Bucket, key, TestContext.Current.CancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CopyFileAsync_CopiesToTheDestinationKey()
|
||||
{
|
||||
var sourceKey = $"tests/{Guid.NewGuid():N}/source.txt";
|
||||
var destinationKey = $"tests/{Guid.NewGuid():N}/destination.txt";
|
||||
await service.UploadFileAsync(new MemoryStream("copy-me"u8.ToArray()), "text/plain", InfrastructureTestFixture.S3Bucket, sourceKey, TestContext.Current.CancellationToken);
|
||||
|
||||
await service.CopyFileAsync(InfrastructureTestFixture.S3Bucket, sourceKey, InfrastructureTestFixture.S3Bucket, destinationKey, TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.NotNull(await service.HeadObjectAsync(InfrastructureTestFixture.S3Bucket, destinationKey, TestContext.Current.CancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ListObjectsAsync_ReturnsEveryObjectUnderThePrefix()
|
||||
{
|
||||
var prefix = $"tests/{Guid.NewGuid():N}";
|
||||
await service.UploadFileAsync(new MemoryStream("a"u8.ToArray()), "text/plain", InfrastructureTestFixture.S3Bucket, $"{prefix}/a.txt", TestContext.Current.CancellationToken);
|
||||
await service.UploadFileAsync(new MemoryStream("b"u8.ToArray()), "text/plain", InfrastructureTestFixture.S3Bucket, $"{prefix}/b.txt", TestContext.Current.CancellationToken);
|
||||
|
||||
var keys = new List<string>();
|
||||
await foreach (var item in service.ListObjectsAsync(InfrastructureTestFixture.S3Bucket, prefix, TestContext.Current.CancellationToken))
|
||||
keys.Add(item.Key);
|
||||
|
||||
Assert.Equal([$"{prefix}/a.txt", $"{prefix}/b.txt"], keys.Order());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveFolderAsync_DeletesEveryObjectUnderThePrefix()
|
||||
{
|
||||
var prefix = $"tests/{Guid.NewGuid():N}";
|
||||
await service.UploadFileAsync(new MemoryStream("a"u8.ToArray()), "text/plain", InfrastructureTestFixture.S3Bucket, $"{prefix}/a.txt", TestContext.Current.CancellationToken);
|
||||
await service.UploadFileAsync(new MemoryStream("b"u8.ToArray()), "text/plain", InfrastructureTestFixture.S3Bucket, $"{prefix}/nested/b.txt", TestContext.Current.CancellationToken);
|
||||
|
||||
await service.RemoveFolderAsync(InfrastructureTestFixture.S3Bucket, prefix, TestContext.Current.CancellationToken);
|
||||
|
||||
var remaining = new List<string>();
|
||||
await foreach (var item in service.ListObjectsAsync(InfrastructureTestFixture.S3Bucket, prefix, TestContext.Current.CancellationToken))
|
||||
remaining.Add(item.Key);
|
||||
Assert.Empty(remaining);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUploadUrlAsync_PresignedPut_CanActuallyUploadTheObject()
|
||||
{
|
||||
var key = $"tests/{Guid.NewGuid():N}/presigned.txt";
|
||||
|
||||
var uploadUrl = await service.GetUploadUrlAsync(
|
||||
InfrastructureTestFixture.S3Bucket, key, "text/plain", TimeSpan.FromMinutes(5), TestContext.Current.CancellationToken);
|
||||
|
||||
using var httpClient = new HttpClient();
|
||||
using var request = new HttpRequestMessage(HttpMethod.Put, uploadUrl)
|
||||
{
|
||||
var key = $"tests/{Guid.NewGuid():N}/round-trip.txt";
|
||||
var content = "hello seaweedfs"u8.ToArray();
|
||||
Content = new ByteArrayContent(Encoding.UTF8.GetBytes("presigned content"))
|
||||
};
|
||||
request.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
|
||||
request.Headers.TryAddWithoutValidation("If-None-Match", "*");
|
||||
var response = await httpClient.SendAsync(request, TestContext.Current.CancellationToken);
|
||||
|
||||
await service.UploadFileAsync(new MemoryStream(content), "text/plain", InfrastructureTestFixture.S3Bucket, key, TestContext.Current.CancellationToken);
|
||||
|
||||
await using var stream = await service.GetFileAsync(InfrastructureTestFixture.S3Bucket, key, TestContext.Current.CancellationToken);
|
||||
using var reader = new StreamReader(stream, Encoding.UTF8);
|
||||
var readBack = await reader.ReadToEndAsync(TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.Equal("hello seaweedfs", readBack);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HeadObjectAsync_ExistingObject_ReturnsMetadata()
|
||||
{
|
||||
var key = $"tests/{Guid.NewGuid():N}/head.txt";
|
||||
await service.UploadFileAsync(new MemoryStream("x"u8.ToArray()), "text/plain", InfrastructureTestFixture.S3Bucket, key, TestContext.Current.CancellationToken);
|
||||
|
||||
var metadata = await service.HeadObjectAsync(InfrastructureTestFixture.S3Bucket, key, TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.NotNull(metadata);
|
||||
Assert.Equal(1, metadata.ContentLength);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HeadObjectAsync_MissingObject_ReturnsNull()
|
||||
{
|
||||
var metadata = await service.HeadObjectAsync(InfrastructureTestFixture.S3Bucket, $"tests/{Guid.NewGuid():N}/missing.txt", TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.Null(metadata);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveFileAsync_ExistingObject_DeletesIt()
|
||||
{
|
||||
var key = $"tests/{Guid.NewGuid():N}/to-remove.txt";
|
||||
await service.UploadFileAsync(new MemoryStream("x"u8.ToArray()), "text/plain", InfrastructureTestFixture.S3Bucket, key, TestContext.Current.CancellationToken);
|
||||
|
||||
await service.RemoveFileAsync(InfrastructureTestFixture.S3Bucket, key, TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.Null(await service.HeadObjectAsync(InfrastructureTestFixture.S3Bucket, key, TestContext.Current.CancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CopyFileAsync_CopiesToTheDestinationKey()
|
||||
{
|
||||
var sourceKey = $"tests/{Guid.NewGuid():N}/source.txt";
|
||||
var destinationKey = $"tests/{Guid.NewGuid():N}/destination.txt";
|
||||
await service.UploadFileAsync(new MemoryStream("copy-me"u8.ToArray()), "text/plain", InfrastructureTestFixture.S3Bucket, sourceKey, TestContext.Current.CancellationToken);
|
||||
|
||||
await service.CopyFileAsync(InfrastructureTestFixture.S3Bucket, sourceKey, InfrastructureTestFixture.S3Bucket, destinationKey, TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.NotNull(await service.HeadObjectAsync(InfrastructureTestFixture.S3Bucket, destinationKey, TestContext.Current.CancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ListObjectsAsync_ReturnsEveryObjectUnderThePrefix()
|
||||
{
|
||||
var prefix = $"tests/{Guid.NewGuid():N}";
|
||||
await service.UploadFileAsync(new MemoryStream("a"u8.ToArray()), "text/plain", InfrastructureTestFixture.S3Bucket, $"{prefix}/a.txt", TestContext.Current.CancellationToken);
|
||||
await service.UploadFileAsync(new MemoryStream("b"u8.ToArray()), "text/plain", InfrastructureTestFixture.S3Bucket, $"{prefix}/b.txt", TestContext.Current.CancellationToken);
|
||||
|
||||
var keys = new List<string>();
|
||||
await foreach (var item in service.ListObjectsAsync(InfrastructureTestFixture.S3Bucket, prefix, TestContext.Current.CancellationToken))
|
||||
keys.Add(item.Key);
|
||||
|
||||
Assert.Equal([$"{prefix}/a.txt", $"{prefix}/b.txt"], keys.Order());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RemoveFolderAsync_DeletesEveryObjectUnderThePrefix()
|
||||
{
|
||||
var prefix = $"tests/{Guid.NewGuid():N}";
|
||||
await service.UploadFileAsync(new MemoryStream("a"u8.ToArray()), "text/plain", InfrastructureTestFixture.S3Bucket, $"{prefix}/a.txt", TestContext.Current.CancellationToken);
|
||||
await service.UploadFileAsync(new MemoryStream("b"u8.ToArray()), "text/plain", InfrastructureTestFixture.S3Bucket, $"{prefix}/nested/b.txt", TestContext.Current.CancellationToken);
|
||||
|
||||
await service.RemoveFolderAsync(InfrastructureTestFixture.S3Bucket, prefix, TestContext.Current.CancellationToken);
|
||||
|
||||
var remaining = new List<string>();
|
||||
await foreach (var item in service.ListObjectsAsync(InfrastructureTestFixture.S3Bucket, prefix, TestContext.Current.CancellationToken))
|
||||
remaining.Add(item.Key);
|
||||
Assert.Empty(remaining);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUploadUrlAsync_PresignedPut_CanActuallyUploadTheObject()
|
||||
{
|
||||
var key = $"tests/{Guid.NewGuid():N}/presigned.txt";
|
||||
|
||||
var uploadUrl = await service.GetUploadUrlAsync(
|
||||
InfrastructureTestFixture.S3Bucket, key, "text/plain", TimeSpan.FromMinutes(5), TestContext.Current.CancellationToken);
|
||||
|
||||
using var httpClient = new HttpClient();
|
||||
using var request = new HttpRequestMessage(HttpMethod.Put, uploadUrl)
|
||||
{
|
||||
Content = new ByteArrayContent(Encoding.UTF8.GetBytes("presigned content"))
|
||||
};
|
||||
request.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
|
||||
request.Headers.TryAddWithoutValidation("If-None-Match", "*");
|
||||
var response = await httpClient.SendAsync(request, TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
var metadata = await service.HeadObjectAsync(InfrastructureTestFixture.S3Bucket, key, TestContext.Current.CancellationToken);
|
||||
Assert.NotNull(metadata);
|
||||
Assert.Equal("presigned content".Length, metadata.ContentLength);
|
||||
}
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
var metadata = await service.HeadObjectAsync(InfrastructureTestFixture.S3Bucket, key, TestContext.Current.CancellationToken);
|
||||
Assert.NotNull(metadata);
|
||||
Assert.Equal("presigned content".Length, metadata.ContentLength);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,105 +5,104 @@ using Musify.Infrastructure.Configuration;
|
||||
using Musify.Infrastructure.Services;
|
||||
using Xunit;
|
||||
|
||||
namespace Musify.Infrastructure.Tests.Services
|
||||
namespace Musify.Infrastructure.Tests.Services;
|
||||
|
||||
public sealed class StreamTicketServiceTests : IDisposable
|
||||
{
|
||||
public sealed class StreamTicketServiceTests : IDisposable
|
||||
private readonly string privateKeyPath = Path.GetTempFileName();
|
||||
private readonly RSA rsa = RSA.Create(2048);
|
||||
|
||||
public StreamTicketServiceTests() => File.WriteAllText(privateKeyPath, rsa.ExportPkcs8PrivateKeyPem());
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
private readonly string privateKeyPath = Path.GetTempFileName();
|
||||
private readonly RSA rsa = RSA.Create(2048);
|
||||
rsa.Dispose();
|
||||
File.Delete(privateKeyPath);
|
||||
}
|
||||
|
||||
public StreamTicketServiceTests() => File.WriteAllText(privateKeyPath, rsa.ExportPkcs8PrivateKeyPem());
|
||||
private StreamTicketService CreateService(int ticketTtlSeconds = 3600) => new(new StreamTicketConfiguration
|
||||
{
|
||||
PrivateKeyPath = privateKeyPath,
|
||||
Audience = "media-gateway",
|
||||
Issuer = "musify-webapi",
|
||||
TicketTtlSeconds = ticketTtlSeconds
|
||||
});
|
||||
|
||||
public void Dispose()
|
||||
[Fact]
|
||||
public void IssueTicket_ReturnsATokenSignedWithTheConfiguredKeyAndClaims()
|
||||
{
|
||||
using var service = CreateService(ticketTtlSeconds: 120);
|
||||
|
||||
var ticket = service.IssueTicket(userId: 42, keyPrefix: "Tracks/ProcessedAudios/abc/");
|
||||
|
||||
Assert.Equal(120, ticket.ExpiresInSeconds);
|
||||
|
||||
var handler = new JsonWebTokenHandler();
|
||||
var jwt = handler.ReadJsonWebToken(ticket.Token);
|
||||
Assert.Equal("42", jwt.GetClaim("sub").Value);
|
||||
Assert.Equal("Tracks/ProcessedAudios/abc/", jwt.GetClaim("prefix").Value);
|
||||
Assert.Equal("musify-webapi", jwt.Issuer);
|
||||
Assert.Contains("media-gateway", jwt.Audiences);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IssueTicket_AnonymousUser_OmitsTheSubClaim()
|
||||
{
|
||||
using var service = CreateService();
|
||||
|
||||
var ticket = service.IssueTicket(userId: null, keyPrefix: "Tracks/ProcessedAudios/abc/");
|
||||
|
||||
var handler = new JsonWebTokenHandler();
|
||||
var jwt = handler.ReadJsonWebToken(ticket.Token);
|
||||
Assert.DoesNotContain(jwt.Claims, c => c.Type == "sub");
|
||||
Assert.Equal("Tracks/ProcessedAudios/abc/", jwt.GetClaim("prefix").Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IssueTicket_WithMaxBytes_IncludesTheMaxBytesClaim()
|
||||
{
|
||||
using var service = CreateService();
|
||||
|
||||
var ticket = service.IssueTicket(userId: null, keyPrefix: "Tracks/ProcessedAudios/abc/", maxBytes: 480_000);
|
||||
|
||||
var handler = new JsonWebTokenHandler();
|
||||
var jwt = handler.ReadJsonWebToken(ticket.Token);
|
||||
Assert.Equal("480000", jwt.GetClaim("maxBytes").Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IssueTicket_WithoutMaxBytes_OmitsTheMaxBytesClaim()
|
||||
{
|
||||
using var service = CreateService();
|
||||
|
||||
var ticket = service.IssueTicket(userId: 1, keyPrefix: "Tracks/ProcessedAudios/abc/");
|
||||
|
||||
var handler = new JsonWebTokenHandler();
|
||||
var jwt = handler.ReadJsonWebToken(ticket.Token);
|
||||
Assert.DoesNotContain(jwt.Claims, c => c.Type == "maxBytes");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task IssueTicket_TokenValidatesAgainstTheMatchingPublicKey()
|
||||
{
|
||||
using var service = CreateService();
|
||||
var ticket = service.IssueTicket(userId: 1, keyPrefix: "Tracks/ProcessedAudios/xyz/");
|
||||
|
||||
var publicKeyPem = rsa.ExportSubjectPublicKeyInfoPem();
|
||||
using var verifyingRsa = RSA.Create();
|
||||
verifyingRsa.ImportFromPem(publicKeyPem);
|
||||
|
||||
var handler = new JsonWebTokenHandler();
|
||||
var result = await handler.ValidateTokenAsync(ticket.Token, new TokenValidationParameters
|
||||
{
|
||||
rsa.Dispose();
|
||||
File.Delete(privateKeyPath);
|
||||
}
|
||||
|
||||
private StreamTicketService CreateService(int ticketTtlSeconds = 3600) => new(new StreamTicketConfiguration
|
||||
{
|
||||
PrivateKeyPath = privateKeyPath,
|
||||
Audience = "media-gateway",
|
||||
Issuer = "musify-webapi",
|
||||
TicketTtlSeconds = ticketTtlSeconds
|
||||
ValidIssuer = "musify-webapi",
|
||||
ValidAudience = "media-gateway",
|
||||
ValidateIssuer = true,
|
||||
ValidateAudience = true,
|
||||
ValidateLifetime = true,
|
||||
IssuerSigningKey = new RsaSecurityKey(verifyingRsa),
|
||||
});
|
||||
|
||||
[Fact]
|
||||
public void IssueTicket_ReturnsATokenSignedWithTheConfiguredKeyAndClaims()
|
||||
{
|
||||
using var service = CreateService(ticketTtlSeconds: 120);
|
||||
|
||||
var ticket = service.IssueTicket(userId: 42, keyPrefix: "Tracks/ProcessedAudios/abc/");
|
||||
|
||||
Assert.Equal(120, ticket.ExpiresInSeconds);
|
||||
|
||||
var handler = new JsonWebTokenHandler();
|
||||
var jwt = handler.ReadJsonWebToken(ticket.Token);
|
||||
Assert.Equal("42", jwt.GetClaim("sub").Value);
|
||||
Assert.Equal("Tracks/ProcessedAudios/abc/", jwt.GetClaim("prefix").Value);
|
||||
Assert.Equal("musify-webapi", jwt.Issuer);
|
||||
Assert.Contains("media-gateway", jwt.Audiences);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IssueTicket_AnonymousUser_OmitsTheSubClaim()
|
||||
{
|
||||
using var service = CreateService();
|
||||
|
||||
var ticket = service.IssueTicket(userId: null, keyPrefix: "Tracks/ProcessedAudios/abc/");
|
||||
|
||||
var handler = new JsonWebTokenHandler();
|
||||
var jwt = handler.ReadJsonWebToken(ticket.Token);
|
||||
Assert.DoesNotContain(jwt.Claims, c => c.Type == "sub");
|
||||
Assert.Equal("Tracks/ProcessedAudios/abc/", jwt.GetClaim("prefix").Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IssueTicket_WithMaxBytes_IncludesTheMaxBytesClaim()
|
||||
{
|
||||
using var service = CreateService();
|
||||
|
||||
var ticket = service.IssueTicket(userId: null, keyPrefix: "Tracks/ProcessedAudios/abc/", maxBytes: 480_000);
|
||||
|
||||
var handler = new JsonWebTokenHandler();
|
||||
var jwt = handler.ReadJsonWebToken(ticket.Token);
|
||||
Assert.Equal("480000", jwt.GetClaim("maxBytes").Value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IssueTicket_WithoutMaxBytes_OmitsTheMaxBytesClaim()
|
||||
{
|
||||
using var service = CreateService();
|
||||
|
||||
var ticket = service.IssueTicket(userId: 1, keyPrefix: "Tracks/ProcessedAudios/abc/");
|
||||
|
||||
var handler = new JsonWebTokenHandler();
|
||||
var jwt = handler.ReadJsonWebToken(ticket.Token);
|
||||
Assert.DoesNotContain(jwt.Claims, c => c.Type == "maxBytes");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task IssueTicket_TokenValidatesAgainstTheMatchingPublicKey()
|
||||
{
|
||||
using var service = CreateService();
|
||||
var ticket = service.IssueTicket(userId: 1, keyPrefix: "Tracks/ProcessedAudios/xyz/");
|
||||
|
||||
var publicKeyPem = rsa.ExportSubjectPublicKeyInfoPem();
|
||||
using var verifyingRsa = RSA.Create();
|
||||
verifyingRsa.ImportFromPem(publicKeyPem);
|
||||
|
||||
var handler = new JsonWebTokenHandler();
|
||||
var result = await handler.ValidateTokenAsync(ticket.Token, new TokenValidationParameters
|
||||
{
|
||||
ValidIssuer = "musify-webapi",
|
||||
ValidAudience = "media-gateway",
|
||||
ValidateIssuer = true,
|
||||
ValidateAudience = true,
|
||||
ValidateLifetime = true,
|
||||
IssuerSigningKey = new RsaSecurityKey(verifyingRsa),
|
||||
});
|
||||
|
||||
Assert.True(result.IsValid);
|
||||
}
|
||||
Assert.True(result.IsValid);
|
||||
}
|
||||
}
|
||||
|
||||
+85
-86
@@ -1,105 +1,104 @@
|
||||
using System.Text.Json;
|
||||
using Amazon.S3;
|
||||
using DotNet.Testcontainers.Builders;
|
||||
using DotNet.Testcontainers.Containers;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Musify.Infrastructure.Configuration;
|
||||
using Musify.Infrastructure.Persistence;
|
||||
using Testcontainers.PostgreSql;
|
||||
using DotNet.Testcontainers.Builders;
|
||||
using DotNet.Testcontainers.Containers;
|
||||
using Xunit;
|
||||
|
||||
namespace Musify.Infrastructure.Tests.TestSupport
|
||||
namespace Musify.Infrastructure.Tests.TestSupport;
|
||||
|
||||
public sealed class InfrastructureTestFixture : IAsyncLifetime
|
||||
{
|
||||
public sealed class InfrastructureTestFixture : IAsyncLifetime
|
||||
public const string S3AccessKey = "musify-test";
|
||||
public const string S3SecretKey = "musify-test-secret";
|
||||
public const string S3Bucket = "musify-test-bucket";
|
||||
|
||||
private readonly PostgreSqlContainer postgres = new PostgreSqlBuilder("postgres:17-alpine")
|
||||
.WithDatabase("musify_test")
|
||||
.WithUsername("postgres")
|
||||
.WithPassword("postgres")
|
||||
.Build();
|
||||
|
||||
private readonly IContainer seaweedFs = new ContainerBuilder("chrislusf/seaweedfs:latest")
|
||||
.WithEntrypoint("/bin/sh", "-c")
|
||||
.WithCommand(BuildSeaweedFsStartupScript())
|
||||
.WithPortBinding(9333, assignRandomHostPort: true)
|
||||
.WithPortBinding(8333, assignRandomHostPort: true)
|
||||
.WithWaitStrategy(Wait.ForUnixContainer()
|
||||
.UntilHttpRequestIsSucceeded(request => request.ForPort(9333).ForPath("/cluster/healthz")))
|
||||
.Build();
|
||||
|
||||
public string ConnectionString => postgres.GetConnectionString();
|
||||
|
||||
public string S3ServiceUrl => $"http://{seaweedFs.Hostname}:{seaweedFs.GetMappedPublicPort(8333)}";
|
||||
|
||||
public async ValueTask InitializeAsync()
|
||||
{
|
||||
public const string S3AccessKey = "musify-test";
|
||||
public const string S3SecretKey = "musify-test-secret";
|
||||
public const string S3Bucket = "musify-test-bucket";
|
||||
await Task.WhenAll(postgres.StartAsync(), seaweedFs.StartAsync());
|
||||
|
||||
private readonly PostgreSqlContainer postgres = new PostgreSqlBuilder("postgres:17-alpine")
|
||||
.WithDatabase("musify_test")
|
||||
.WithUsername("postgres")
|
||||
.WithPassword("postgres")
|
||||
.Build();
|
||||
await using var database = new Database(new DatabaseConfiguration { ConnectionString = ConnectionString });
|
||||
await database.Database.MigrateAsync();
|
||||
|
||||
private readonly IContainer seaweedFs = new ContainerBuilder("chrislusf/seaweedfs:latest")
|
||||
.WithEntrypoint("/bin/sh", "-c")
|
||||
.WithCommand(BuildSeaweedFsStartupScript())
|
||||
.WithPortBinding(9333, assignRandomHostPort: true)
|
||||
.WithPortBinding(8333, assignRandomHostPort: true)
|
||||
.WithWaitStrategy(Wait.ForUnixContainer()
|
||||
.UntilHttpRequestIsSucceeded(request => request.ForPort(9333).ForPath("/cluster/healthz")))
|
||||
.Build();
|
||||
|
||||
public string ConnectionString => postgres.GetConnectionString();
|
||||
|
||||
public string S3ServiceUrl => $"http://{seaweedFs.Hostname}:{seaweedFs.GetMappedPublicPort(8333)}";
|
||||
|
||||
public async ValueTask InitializeAsync()
|
||||
{
|
||||
await Task.WhenAll(postgres.StartAsync(), seaweedFs.StartAsync());
|
||||
|
||||
await using var database = new Database(new DatabaseConfiguration { ConnectionString = ConnectionString });
|
||||
await database.Database.MigrateAsync();
|
||||
|
||||
using var s3 = CreateS3Client();
|
||||
await s3.PutBucketAsync(S3Bucket);
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await postgres.DisposeAsync();
|
||||
await seaweedFs.DisposeAsync();
|
||||
}
|
||||
|
||||
public Database CreateDatabase()
|
||||
{
|
||||
var configuration = new ConfigurationBuilder()
|
||||
.AddInMemoryCollection([new("Database:ConnectionString", ConnectionString)])
|
||||
.Build();
|
||||
|
||||
var services = new ServiceCollection();
|
||||
services.AddDatabase(configuration);
|
||||
return services.BuildServiceProvider().GetRequiredService<Database>();
|
||||
}
|
||||
|
||||
public IAmazonS3 CreateS3Client() =>
|
||||
new AmazonS3Client(S3AccessKey, S3SecretKey, new AmazonS3Config
|
||||
{
|
||||
ServiceURL = S3ServiceUrl,
|
||||
ForcePathStyle = true,
|
||||
UseHttp = true,
|
||||
});
|
||||
|
||||
private static string BuildSeaweedFsStartupScript()
|
||||
{
|
||||
var identity = JsonSerializer.Serialize(new
|
||||
{
|
||||
identities = new[]
|
||||
{
|
||||
new
|
||||
{
|
||||
name = "musify-test",
|
||||
credentials = new[] { new { accessKey = S3AccessKey, secretKey = S3SecretKey } },
|
||||
actions = new[] { "Admin", "Read", "Write" }
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return $"""
|
||||
cat > /tmp/s3.conf <<'JSON'
|
||||
{identity}
|
||||
JSON
|
||||
exec weed server -ip.bind=0.0.0.0 -dir=/data -master.volumeSizeLimitMB=1024 -volume.max=0 -filer -s3 -s3.config=/tmp/s3.conf
|
||||
""";
|
||||
}
|
||||
using var s3 = CreateS3Client();
|
||||
await s3.PutBucketAsync(S3Bucket);
|
||||
}
|
||||
|
||||
[CollectionDefinition(Name)]
|
||||
public sealed class InfrastructureCollection : ICollectionFixture<InfrastructureTestFixture>
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
public const string Name = "Infrastructure";
|
||||
await postgres.DisposeAsync();
|
||||
await seaweedFs.DisposeAsync();
|
||||
}
|
||||
|
||||
public Database CreateDatabase()
|
||||
{
|
||||
var configuration = new ConfigurationBuilder()
|
||||
.AddInMemoryCollection([new("Database:ConnectionString", ConnectionString)])
|
||||
.Build();
|
||||
|
||||
var services = new ServiceCollection();
|
||||
services.AddDatabase(configuration);
|
||||
return services.BuildServiceProvider().GetRequiredService<Database>();
|
||||
}
|
||||
|
||||
public IAmazonS3 CreateS3Client() =>
|
||||
new AmazonS3Client(S3AccessKey, S3SecretKey, new AmazonS3Config
|
||||
{
|
||||
ServiceURL = S3ServiceUrl,
|
||||
ForcePathStyle = true,
|
||||
UseHttp = true,
|
||||
});
|
||||
|
||||
private static string BuildSeaweedFsStartupScript()
|
||||
{
|
||||
var identity = JsonSerializer.Serialize(new
|
||||
{
|
||||
identities = new[]
|
||||
{
|
||||
new
|
||||
{
|
||||
name = "musify-test",
|
||||
credentials = new[] { new { accessKey = S3AccessKey, secretKey = S3SecretKey } },
|
||||
actions = new[] { "Admin", "Read", "Write" }
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return $"""
|
||||
cat > /tmp/s3.conf <<'JSON'
|
||||
{identity}
|
||||
JSON
|
||||
exec weed server -ip.bind=0.0.0.0 -dir=/data -master.volumeSizeLimitMB=1024 -volume.max=0 -filer -s3 -s3.config=/tmp/s3.conf
|
||||
""";
|
||||
}
|
||||
}
|
||||
|
||||
[CollectionDefinition(Name)]
|
||||
public sealed class InfrastructureCollection : ICollectionFixture<InfrastructureTestFixture>
|
||||
{
|
||||
public const string Name = "Infrastructure";
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user