Use block-scoped namespaces in the test suite
Converts all 73 test source files from file-scoped (namespace X;) to
block-scoped (namespace X { ... }) declarations, re-indenting their
contents accordingly. Matches the existing convention already used in
several production files (e.g. Musify.Infrastructure.Configuration,
Musify.Application.Contracts).
Mechanical change only, done with a script, verified with a full
rebuild (0 warnings, 0 errors) and test run (257/257 passing).
This commit is contained in:
+40
-39
@@ -2,57 +2,58 @@ using ErrorOr;
|
||||
using Musify.Infrastructure.Services;
|
||||
using Xunit;
|
||||
|
||||
namespace Musify.Infrastructure.Tests.Services;
|
||||
|
||||
public sealed class DisabledYouTubeMusicServiceTests
|
||||
namespace Musify.Infrastructure.Tests.Services
|
||||
{
|
||||
private readonly DisabledYouTubeMusicService service = new();
|
||||
|
||||
[Fact]
|
||||
public async Task SearchSongsAsync_ReturnsForbidden()
|
||||
public sealed class DisabledYouTubeMusicServiceTests
|
||||
{
|
||||
var result = await service.SearchSongsAsync("query", string.Empty, TestContext.Current.CancellationToken);
|
||||
private readonly DisabledYouTubeMusicService service = new();
|
||||
|
||||
Assert.Equal(ErrorType.Forbidden, result.FirstError.Type);
|
||||
}
|
||||
[Fact]
|
||||
public async Task SearchSongsAsync_ReturnsForbidden()
|
||||
{
|
||||
var result = await service.SearchSongsAsync("query", string.Empty, TestContext.Current.CancellationToken);
|
||||
|
||||
[Fact]
|
||||
public async Task SearchAlbumsAsync_ReturnsForbidden()
|
||||
{
|
||||
var result = await service.SearchAlbumsAsync("query", string.Empty, TestContext.Current.CancellationToken);
|
||||
Assert.Equal(ErrorType.Forbidden, result.FirstError.Type);
|
||||
}
|
||||
|
||||
Assert.Equal(ErrorType.Forbidden, result.FirstError.Type);
|
||||
}
|
||||
[Fact]
|
||||
public async Task SearchAlbumsAsync_ReturnsForbidden()
|
||||
{
|
||||
var result = await service.SearchAlbumsAsync("query", string.Empty, TestContext.Current.CancellationToken);
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbumAsync_ReturnsForbidden()
|
||||
{
|
||||
var result = await service.GetAlbumAsync("album-1", TestContext.Current.CancellationToken);
|
||||
Assert.Equal(ErrorType.Forbidden, result.FirstError.Type);
|
||||
}
|
||||
|
||||
Assert.Equal(ErrorType.Forbidden, result.FirstError.Type);
|
||||
}
|
||||
[Fact]
|
||||
public async Task GetAlbumAsync_ReturnsForbidden()
|
||||
{
|
||||
var result = await service.GetAlbumAsync("album-1", TestContext.Current.CancellationToken);
|
||||
|
||||
[Fact]
|
||||
public async Task GetAudioStreamAsync_ReturnsForbidden()
|
||||
{
|
||||
var result = await service.GetAudioStreamAsync("video-1", TestContext.Current.CancellationToken);
|
||||
Assert.Equal(ErrorType.Forbidden, result.FirstError.Type);
|
||||
}
|
||||
|
||||
Assert.Equal(ErrorType.Forbidden, result.FirstError.Type);
|
||||
}
|
||||
[Fact]
|
||||
public async Task GetAudioStreamAsync_ReturnsForbidden()
|
||||
{
|
||||
var result = await service.GetAudioStreamAsync("video-1", TestContext.Current.CancellationToken);
|
||||
|
||||
[Fact]
|
||||
public async Task GetSongAsync_ReturnsForbidden()
|
||||
{
|
||||
var result = await service.GetSongAsync("video-1", TestContext.Current.CancellationToken);
|
||||
Assert.Equal(ErrorType.Forbidden, result.FirstError.Type);
|
||||
}
|
||||
|
||||
Assert.Equal(ErrorType.Forbidden, result.FirstError.Type);
|
||||
}
|
||||
[Fact]
|
||||
public async Task GetSongAsync_ReturnsForbidden()
|
||||
{
|
||||
var result = await service.GetSongAsync("video-1", TestContext.Current.CancellationToken);
|
||||
|
||||
[Fact]
|
||||
public void ResolveArtworkUrl_ReturnsTheUrlUnchanged()
|
||||
{
|
||||
var result = service.ResolveArtworkUrl("https://img.example/thumb.jpg");
|
||||
Assert.Equal(ErrorType.Forbidden, result.FirstError.Type);
|
||||
}
|
||||
|
||||
Assert.Equal("https://img.example/thumb.jpg", result);
|
||||
[Fact]
|
||||
public void ResolveArtworkUrl_ReturnsTheUrlUnchanged()
|
||||
{
|
||||
var result = service.ResolveArtworkUrl("https://img.example/thumb.jpg");
|
||||
|
||||
Assert.Equal("https://img.example/thumb.jpg", result);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,54 +4,55 @@ using SixLabors.ImageSharp;
|
||||
using SixLabors.ImageSharp.PixelFormats;
|
||||
using Xunit;
|
||||
|
||||
namespace Musify.Infrastructure.Tests.Services;
|
||||
|
||||
public sealed class PictureServiceTests
|
||||
namespace Musify.Infrastructure.Tests.Services
|
||||
{
|
||||
private static PictureService CreateService() => new(NullLogger<PictureService>.Instance);
|
||||
|
||||
private static MemoryStream CreateSourceImage(int width, int height)
|
||||
public sealed class PictureServiceTests
|
||||
{
|
||||
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 PictureService CreateService() => new(NullLogger<PictureService>.Instance);
|
||||
|
||||
[Fact]
|
||||
public async Task ResizePictureAsWebpAsync_LargerThanTarget_ShrinksToFitWithinTheRequestedBox()
|
||||
{
|
||||
using var source = CreateSourceImage(800, 600);
|
||||
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;
|
||||
}
|
||||
|
||||
await using var resized = await CreateService().ResizePictureAsWebpAsync(source, 200, 200, TestContext.Current.CancellationToken);
|
||||
[Fact]
|
||||
public async Task ResizePictureAsWebpAsync_LargerThanTarget_ShrinksToFitWithinTheRequestedBox()
|
||||
{
|
||||
using var source = CreateSourceImage(800, 600);
|
||||
|
||||
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");
|
||||
}
|
||||
await using var resized = await CreateService().ResizePictureAsWebpAsync(source, 200, 200, TestContext.Current.CancellationToken);
|
||||
|
||||
[Fact]
|
||||
public async Task ResizePictureAsWebpAsync_ReturnsAValidWebpStream()
|
||||
{
|
||||
using var source = CreateSourceImage(100, 100);
|
||||
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");
|
||||
}
|
||||
|
||||
await using var resized = await CreateService().ResizePictureAsWebpAsync(source, 50, 50, TestContext.Current.CancellationToken);
|
||||
[Fact]
|
||||
public async Task ResizePictureAsWebpAsync_ReturnsAValidWebpStream()
|
||||
{
|
||||
using var source = CreateSourceImage(100, 100);
|
||||
|
||||
var format = await Image.DetectFormatAsync(resized, TestContext.Current.CancellationToken);
|
||||
Assert.Equal("WEBP", format?.Name, ignoreCase: true);
|
||||
}
|
||||
await using var resized = await CreateService().ResizePictureAsWebpAsync(source, 50, 50, TestContext.Current.CancellationToken);
|
||||
|
||||
[Fact]
|
||||
public async Task ResizePictureAsWebpAsync_PreservesAspectRatio()
|
||||
{
|
||||
using var source = CreateSourceImage(400, 200);
|
||||
var format = await Image.DetectFormatAsync(resized, TestContext.Current.CancellationToken);
|
||||
Assert.Equal("WEBP", format?.Name, ignoreCase: true);
|
||||
}
|
||||
|
||||
await using var resized = await CreateService().ResizePictureAsWebpAsync(source, 100, 100, TestContext.Current.CancellationToken);
|
||||
[Fact]
|
||||
public async Task ResizePictureAsWebpAsync_PreservesAspectRatio()
|
||||
{
|
||||
using var source = CreateSourceImage(400, 200);
|
||||
|
||||
using var result = await Image.LoadAsync(resized, TestContext.Current.CancellationToken);
|
||||
Assert.Equal(100, result.Width);
|
||||
Assert.Equal(50, result.Height);
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,96 +7,97 @@ using Musify.Infrastructure.Services;
|
||||
using Musify.Infrastructure.Tests.TestSupport;
|
||||
using Xunit;
|
||||
|
||||
namespace Musify.Infrastructure.Tests.Services;
|
||||
|
||||
[Collection(InfrastructureCollection.Name)]
|
||||
public sealed class PlayListPresetSeederTests(InfrastructureTestFixture fixture)
|
||||
namespace Musify.Infrastructure.Tests.Services
|
||||
{
|
||||
private static PlayListConfiguration NewConfiguration(bool overwritePresetPictures) => new()
|
||||
[Collection(InfrastructureCollection.Name)]
|
||||
public sealed class PlayListPresetSeederTests(InfrastructureTestFixture fixture)
|
||||
{
|
||||
Routes = new PlayListRoutes { ParentFolders = $"PlayLists-{Guid.NewGuid():N}" },
|
||||
SeedPresetPictures = true,
|
||||
OverwritePresetPictures = overwritePresetPictures
|
||||
};
|
||||
|
||||
private (PlayListPresetSeeder Seeder, IStorageService Storage) Build(PlayListConfiguration configuration)
|
||||
{
|
||||
var services = new ServiceCollection();
|
||||
services.AddSingleton(configuration);
|
||||
services.AddSingleton(new ApplicationStorageConfiguration { Bucket = InfrastructureTestFixture.S3Bucket });
|
||||
services.AddSingleton<IStorageService>(_ => new StorageService(
|
||||
fixture.CreateDatabase(),
|
||||
fixture.CreateS3Client(),
|
||||
NullLogger<StorageService>.Instance,
|
||||
new InfrastructureStorageConfiguration
|
||||
{
|
||||
Address = fixture.S3ServiceUrl,
|
||||
AccessKey = InfrastructureTestFixture.S3AccessKey,
|
||||
SecretAccessKey = InfrastructureTestFixture.S3SecretKey,
|
||||
ForcePathStyle = true,
|
||||
UseHttp = true,
|
||||
}));
|
||||
services.AddSingleton<IPictureService>(new PictureService(NullLogger<PictureService>.Instance));
|
||||
|
||||
var provider = services.BuildServiceProvider();
|
||||
var seeder = new PlayListPresetSeeder(provider.GetRequiredService<IServiceScopeFactory>(), NullLogger<PlayListPresetSeeder>.Instance);
|
||||
return (seeder, provider.GetRequiredService<IStorageService>());
|
||||
}
|
||||
|
||||
private static async Task RunToCompletionAsync(PlayListPresetSeeder seeder)
|
||||
{
|
||||
await seeder.StartAsync(TestContext.Current.CancellationToken);
|
||||
await (seeder.ExecuteTask ?? Task.CompletedTask);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_SeedsAllFourPresetPictures()
|
||||
{
|
||||
var configuration = NewConfiguration(overwritePresetPictures: false);
|
||||
var (seeder, storage) = Build(configuration);
|
||||
|
||||
await RunToCompletionAsync(seeder);
|
||||
|
||||
var routes = configuration.Routes;
|
||||
foreach (var key in new[]
|
||||
{
|
||||
routes.BuildOriginalPicturePath(routes.PresetOriginalPicture),
|
||||
routes.PresetSmallPicturePath,
|
||||
routes.PresetMediumPicturePath,
|
||||
routes.PresetLargePicturePath
|
||||
})
|
||||
private static PlayListConfiguration NewConfiguration(bool overwritePresetPictures) => new()
|
||||
{
|
||||
var metadata = await storage.HeadObjectAsync(InfrastructureTestFixture.S3Bucket, key, TestContext.Current.CancellationToken);
|
||||
Assert.True(metadata is not null, $"expected {key} to have been seeded");
|
||||
Routes = new PlayListRoutes { ParentFolders = $"PlayLists-{Guid.NewGuid():N}" },
|
||||
SeedPresetPictures = true,
|
||||
OverwritePresetPictures = overwritePresetPictures
|
||||
};
|
||||
|
||||
private (PlayListPresetSeeder Seeder, IStorageService Storage) Build(PlayListConfiguration configuration)
|
||||
{
|
||||
var services = new ServiceCollection();
|
||||
services.AddSingleton(configuration);
|
||||
services.AddSingleton(new ApplicationStorageConfiguration { Bucket = InfrastructureTestFixture.S3Bucket });
|
||||
services.AddSingleton<IStorageService>(_ => new StorageService(
|
||||
fixture.CreateDatabase(),
|
||||
fixture.CreateS3Client(),
|
||||
NullLogger<StorageService>.Instance,
|
||||
new InfrastructureStorageConfiguration
|
||||
{
|
||||
Address = fixture.S3ServiceUrl,
|
||||
AccessKey = InfrastructureTestFixture.S3AccessKey,
|
||||
SecretAccessKey = InfrastructureTestFixture.S3SecretKey,
|
||||
ForcePathStyle = true,
|
||||
UseHttp = true,
|
||||
}));
|
||||
services.AddSingleton<IPictureService>(new PictureService(NullLogger<PictureService>.Instance));
|
||||
|
||||
var provider = services.BuildServiceProvider();
|
||||
var seeder = new PlayListPresetSeeder(provider.GetRequiredService<IServiceScopeFactory>(), NullLogger<PlayListPresetSeeder>.Instance);
|
||||
return (seeder, provider.GetRequiredService<IStorageService>());
|
||||
}
|
||||
|
||||
private static async Task RunToCompletionAsync(PlayListPresetSeeder seeder)
|
||||
{
|
||||
await seeder.StartAsync(TestContext.Current.CancellationToken);
|
||||
await (seeder.ExecuteTask ?? Task.CompletedTask);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_SeedsAllFourPresetPictures()
|
||||
{
|
||||
var configuration = NewConfiguration(overwritePresetPictures: false);
|
||||
var (seeder, storage) = Build(configuration);
|
||||
|
||||
await RunToCompletionAsync(seeder);
|
||||
|
||||
var routes = configuration.Routes;
|
||||
foreach (var key in new[]
|
||||
{
|
||||
routes.BuildOriginalPicturePath(routes.PresetOriginalPicture),
|
||||
routes.PresetSmallPicturePath,
|
||||
routes.PresetMediumPicturePath,
|
||||
routes.PresetLargePicturePath
|
||||
})
|
||||
{
|
||||
var metadata = await storage.HeadObjectAsync(InfrastructureTestFixture.S3Bucket, key, TestContext.Current.CancellationToken);
|
||||
Assert.True(metadata is not null, $"expected {key} to have been seeded");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_RunTwiceWithoutOverwrite_StaysIdempotent()
|
||||
{
|
||||
var configuration = NewConfiguration(overwritePresetPictures: false);
|
||||
var (firstSeeder, storage) = Build(configuration);
|
||||
await RunToCompletionAsync(firstSeeder);
|
||||
|
||||
var (secondSeeder, _) = Build(configuration);
|
||||
await RunToCompletionAsync(secondSeeder);
|
||||
|
||||
var metadata = await storage.HeadObjectAsync(
|
||||
InfrastructureTestFixture.S3Bucket, configuration.Routes.PresetSmallPicturePath, TestContext.Current.CancellationToken);
|
||||
Assert.NotNull(metadata);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_SeedPresetPicturesDisabled_UploadsNothing()
|
||||
{
|
||||
var configuration = NewConfiguration(overwritePresetPictures: false);
|
||||
configuration.SeedPresetPictures = false;
|
||||
var (seeder, storage) = Build(configuration);
|
||||
|
||||
await RunToCompletionAsync(seeder);
|
||||
|
||||
var metadata = await storage.HeadObjectAsync(
|
||||
InfrastructureTestFixture.S3Bucket, configuration.Routes.PresetSmallPicturePath, TestContext.Current.CancellationToken);
|
||||
Assert.Null(metadata);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_RunTwiceWithoutOverwrite_StaysIdempotent()
|
||||
{
|
||||
var configuration = NewConfiguration(overwritePresetPictures: false);
|
||||
var (firstSeeder, storage) = Build(configuration);
|
||||
await RunToCompletionAsync(firstSeeder);
|
||||
|
||||
var (secondSeeder, _) = Build(configuration);
|
||||
await RunToCompletionAsync(secondSeeder);
|
||||
|
||||
var metadata = await storage.HeadObjectAsync(
|
||||
InfrastructureTestFixture.S3Bucket, configuration.Routes.PresetSmallPicturePath, TestContext.Current.CancellationToken);
|
||||
Assert.NotNull(metadata);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ExecuteAsync_SeedPresetPicturesDisabled_UploadsNothing()
|
||||
{
|
||||
var configuration = NewConfiguration(overwritePresetPictures: false);
|
||||
configuration.SeedPresetPictures = false;
|
||||
var (seeder, storage) = Build(configuration);
|
||||
|
||||
await RunToCompletionAsync(seeder);
|
||||
|
||||
var metadata = await storage.HeadObjectAsync(
|
||||
InfrastructureTestFixture.S3Bucket, configuration.Routes.PresetSmallPicturePath, TestContext.Current.CancellationToken);
|
||||
Assert.Null(metadata);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,78 +3,79 @@ using Microsoft.Extensions.Caching.Memory;
|
||||
using Musify.Infrastructure.Services;
|
||||
using Xunit;
|
||||
|
||||
namespace Musify.Infrastructure.Tests.Services;
|
||||
|
||||
public sealed class SingleFlightCacheTests
|
||||
namespace Musify.Infrastructure.Tests.Services
|
||||
{
|
||||
private static SingleFlightCache CreateCache() => new(new MemoryCache(new MemoryCacheOptions()));
|
||||
|
||||
[Fact]
|
||||
public async Task GetOrCreateAsync_SecondCallWithinDuration_ReturnsCachedValueWithoutCallingFactory()
|
||||
public sealed class SingleFlightCacheTests
|
||||
{
|
||||
var cache = CreateCache();
|
||||
var calls = 0;
|
||||
Task<ErrorOr<int>> Factory() { calls++; return Task.FromResult<ErrorOr<int>>(calls); }
|
||||
private static SingleFlightCache CreateCache() => new(new MemoryCache(new MemoryCacheOptions()));
|
||||
|
||||
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()
|
||||
[Fact]
|
||||
public async Task GetOrCreateAsync_SecondCallWithinDuration_ReturnsCachedValueWithoutCallingFactory()
|
||||
{
|
||||
Interlocked.Increment(ref calls);
|
||||
await gate.Task;
|
||||
return 7;
|
||||
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);
|
||||
}
|
||||
|
||||
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()
|
||||
[Fact]
|
||||
public async Task GetOrCreateAsync_ConcurrentCallsForTheSameKey_CollapseIntoASingleFactoryCall()
|
||||
{
|
||||
calls++;
|
||||
return Task.FromResult<ErrorOr<int>>(Error.Failure(description: "boom"));
|
||||
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));
|
||||
}
|
||||
|
||||
await cache.GetOrCreateAsync("error-key", TimeSpan.FromMinutes(1), Factory);
|
||||
await cache.GetOrCreateAsync("error-key", TimeSpan.FromMinutes(1), Factory);
|
||||
[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"));
|
||||
}
|
||||
|
||||
Assert.Equal(2, calls);
|
||||
}
|
||||
await cache.GetOrCreateAsync("error-key", TimeSpan.FromMinutes(1), Factory);
|
||||
await cache.GetOrCreateAsync("error-key", TimeSpan.FromMinutes(1), Factory);
|
||||
|
||||
[Fact]
|
||||
public async Task GetOrCreateAsync_NonPositiveDuration_AlwaysCallsTheFactory()
|
||||
{
|
||||
var cache = CreateCache();
|
||||
var calls = 0;
|
||||
Task<ErrorOr<int>> Factory() { calls++; return Task.FromResult<ErrorOr<int>>(calls); }
|
||||
Assert.Equal(2, calls);
|
||||
}
|
||||
|
||||
await cache.GetOrCreateAsync("no-cache-key", TimeSpan.Zero, Factory);
|
||||
await cache.GetOrCreateAsync("no-cache-key", TimeSpan.Zero, Factory);
|
||||
[Fact]
|
||||
public async Task GetOrCreateAsync_NonPositiveDuration_AlwaysCallsTheFactory()
|
||||
{
|
||||
var cache = CreateCache();
|
||||
var calls = 0;
|
||||
Task<ErrorOr<int>> Factory() { calls++; return Task.FromResult<ErrorOr<int>>(calls); }
|
||||
|
||||
Assert.Equal(2, calls);
|
||||
await cache.GetOrCreateAsync("no-cache-key", TimeSpan.Zero, Factory);
|
||||
await cache.GetOrCreateAsync("no-cache-key", TimeSpan.Zero, Factory);
|
||||
|
||||
Assert.Equal(2, calls);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,144 +8,145 @@ using Musify.Infrastructure.Services;
|
||||
using Musify.Infrastructure.Tests.TestSupport;
|
||||
using Xunit;
|
||||
|
||||
namespace Musify.Infrastructure.Tests.Services;
|
||||
|
||||
[Collection(InfrastructureCollection.Name)]
|
||||
public sealed class StorageServiceTests(InfrastructureTestFixture fixture) : IAsyncLifetime
|
||||
namespace Musify.Infrastructure.Tests.Services
|
||||
{
|
||||
private Database database = null!;
|
||||
private StorageService service = null!;
|
||||
|
||||
public ValueTask InitializeAsync()
|
||||
[Collection(InfrastructureCollection.Name)]
|
||||
public sealed class StorageServiceTests(InfrastructureTestFixture fixture) : IAsyncLifetime
|
||||
{
|
||||
database = fixture.CreateDatabase();
|
||||
var storageConfiguration = new InfrastructureStorageConfiguration
|
||||
private Database database = null!;
|
||||
private StorageService service = null!;
|
||||
|
||||
public ValueTask InitializeAsync()
|
||||
{
|
||||
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;
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
public ValueTask DisposeAsync() => database.DisposeAsync();
|
||||
public ValueTask DisposeAsync() => database.DisposeAsync();
|
||||
|
||||
[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)
|
||||
[Fact]
|
||||
public async Task UploadThenGetFile_RoundTripsTheSameBytes()
|
||||
{
|
||||
// Not StringContent: it appends "; charset=utf-8" to Content-Type, which no longer
|
||||
// matches the "text/plain" the presigned URL's signature was computed over (SigV4
|
||||
// signs Content-Type byte-for-byte) and the server answers 403 SignatureDoesNotMatch.
|
||||
Content = new ByteArrayContent(Encoding.UTF8.GetBytes("presigned content"))
|
||||
};
|
||||
request.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
|
||||
// GetUploadUrlAsync defaults preventOverwrite to true, which signs the URL together with
|
||||
// this header (see StorageService.GetUploadUrlAsync) — the actual PUT has to send it too,
|
||||
// or the signature no longer matches and the server answers 403.
|
||||
request.Headers.TryAddWithoutValidation("If-None-Match", "*");
|
||||
var response = await httpClient.SendAsync(request, TestContext.Current.CancellationToken);
|
||||
var key = $"tests/{Guid.NewGuid():N}/round-trip.txt";
|
||||
var content = "hello seaweedfs"u8.ToArray();
|
||||
|
||||
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);
|
||||
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)
|
||||
{
|
||||
// Not StringContent: it appends "; charset=utf-8" to Content-Type, which no longer
|
||||
// matches the "text/plain" the presigned URL's signature was computed over (SigV4
|
||||
// signs Content-Type byte-for-byte) and the server answers 403 SignatureDoesNotMatch.
|
||||
Content = new ByteArrayContent(Encoding.UTF8.GetBytes("presigned content"))
|
||||
};
|
||||
request.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
|
||||
// GetUploadUrlAsync defaults preventOverwrite to true, which signs the URL together with
|
||||
// this header (see StorageService.GetUploadUrlAsync) — the actual PUT has to send it too,
|
||||
// or the signature no longer matches and the server answers 403.
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,67 +5,68 @@ using Musify.Infrastructure.Configuration;
|
||||
using Musify.Infrastructure.Services;
|
||||
using Xunit;
|
||||
|
||||
namespace Musify.Infrastructure.Tests.Services;
|
||||
|
||||
public sealed class StreamTicketServiceTests : IDisposable
|
||||
namespace Musify.Infrastructure.Tests.Services
|
||||
{
|
||||
private readonly string privateKeyPath = Path.GetTempFileName();
|
||||
private readonly RSA rsa = RSA.Create(2048);
|
||||
|
||||
public StreamTicketServiceTests() => File.WriteAllText(privateKeyPath, rsa.ExportPkcs8PrivateKeyPem());
|
||||
|
||||
public void Dispose()
|
||||
public sealed class StreamTicketServiceTests : IDisposable
|
||||
{
|
||||
rsa.Dispose();
|
||||
File.Delete(privateKeyPath);
|
||||
}
|
||||
private readonly string privateKeyPath = Path.GetTempFileName();
|
||||
private readonly RSA rsa = RSA.Create(2048);
|
||||
|
||||
private StreamTicketService CreateService(int ticketTtlSeconds = 3600) => new(new StreamTicketConfiguration
|
||||
{
|
||||
PrivateKeyPath = privateKeyPath,
|
||||
Audience = "media-gateway",
|
||||
Issuer = "musify-webapi",
|
||||
TicketTtlSeconds = ticketTtlSeconds
|
||||
});
|
||||
public StreamTicketServiceTests() => File.WriteAllText(privateKeyPath, rsa.ExportPkcs8PrivateKeyPem());
|
||||
|
||||
[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 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
|
||||
public void Dispose()
|
||||
{
|
||||
ValidIssuer = "musify-webapi",
|
||||
ValidAudience = "media-gateway",
|
||||
ValidateIssuer = true,
|
||||
ValidateAudience = true,
|
||||
ValidateLifetime = true,
|
||||
IssuerSigningKey = new RsaSecurityKey(verifyingRsa),
|
||||
rsa.Dispose();
|
||||
File.Delete(privateKeyPath);
|
||||
}
|
||||
|
||||
private StreamTicketService CreateService(int ticketTtlSeconds = 3600) => new(new StreamTicketConfiguration
|
||||
{
|
||||
PrivateKeyPath = privateKeyPath,
|
||||
Audience = "media-gateway",
|
||||
Issuer = "musify-webapi",
|
||||
TicketTtlSeconds = ticketTtlSeconds
|
||||
});
|
||||
|
||||
Assert.True(result.IsValid);
|
||||
[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 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user