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:
@@ -3,82 +3,83 @@ using Microsoft.AspNetCore.Http;
|
||||
using Musify.Api.Authentication;
|
||||
using Xunit;
|
||||
|
||||
namespace Musify.Api.Tests.Authentication;
|
||||
|
||||
public sealed class CurrentUserTests
|
||||
namespace Musify.Api.Tests.Authentication
|
||||
{
|
||||
private static async Task<CurrentUser> BindAsync(ClaimsPrincipal principal)
|
||||
public sealed class CurrentUserTests
|
||||
{
|
||||
var context = new DefaultHttpContext { User = principal };
|
||||
var bound = await CurrentUser.BindAsync(context, parameter: null!);
|
||||
return bound!;
|
||||
}
|
||||
private static async Task<CurrentUser> BindAsync(ClaimsPrincipal principal)
|
||||
{
|
||||
var context = new DefaultHttpContext { User = principal };
|
||||
var bound = await CurrentUser.BindAsync(context, parameter: null!);
|
||||
return bound!;
|
||||
}
|
||||
|
||||
private static ClaimsPrincipal AuthenticatedPrincipal(params Claim[] claims) =>
|
||||
new(new ClaimsIdentity(claims, authenticationType: "TestAuth"));
|
||||
private static ClaimsPrincipal AuthenticatedPrincipal(params Claim[] claims) =>
|
||||
new(new ClaimsIdentity(claims, authenticationType: "TestAuth"));
|
||||
|
||||
[Fact]
|
||||
public async Task BindAsync_AuthenticatedPrincipalWithValidClaims_PopulatesEveryField()
|
||||
{
|
||||
var principal = AuthenticatedPrincipal(
|
||||
new Claim(ClaimTypes.NameIdentifier, "42"),
|
||||
new Claim(ClaimTypes.Name, "jdoe"),
|
||||
new Claim(ClaimTypes.GivenName, "Jane"),
|
||||
new Claim(ClaimTypes.Surname, "Doe"));
|
||||
[Fact]
|
||||
public async Task BindAsync_AuthenticatedPrincipalWithValidClaims_PopulatesEveryField()
|
||||
{
|
||||
var principal = AuthenticatedPrincipal(
|
||||
new Claim(ClaimTypes.NameIdentifier, "42"),
|
||||
new Claim(ClaimTypes.Name, "jdoe"),
|
||||
new Claim(ClaimTypes.GivenName, "Jane"),
|
||||
new Claim(ClaimTypes.Surname, "Doe"));
|
||||
|
||||
var user = await BindAsync(principal);
|
||||
var user = await BindAsync(principal);
|
||||
|
||||
Assert.True(user.IsAuthenticated);
|
||||
Assert.Equal(42, user.Id);
|
||||
Assert.Equal(42, user.RequiredId);
|
||||
Assert.Equal("jdoe", user.Username);
|
||||
Assert.Equal("Jane", user.FirstName);
|
||||
Assert.Equal("Doe", user.LastName);
|
||||
}
|
||||
Assert.True(user.IsAuthenticated);
|
||||
Assert.Equal(42, user.Id);
|
||||
Assert.Equal(42, user.RequiredId);
|
||||
Assert.Equal("jdoe", user.Username);
|
||||
Assert.Equal("Jane", user.FirstName);
|
||||
Assert.Equal("Doe", user.LastName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task BindAsync_AnonymousPrincipal_IsNotAuthenticatedAndHasNoId()
|
||||
{
|
||||
var user = await BindAsync(new ClaimsPrincipal(new ClaimsIdentity()));
|
||||
[Fact]
|
||||
public async Task BindAsync_AnonymousPrincipal_IsNotAuthenticatedAndHasNoId()
|
||||
{
|
||||
var user = await BindAsync(new ClaimsPrincipal(new ClaimsIdentity()));
|
||||
|
||||
Assert.False(user.IsAuthenticated);
|
||||
Assert.Null(user.Id);
|
||||
}
|
||||
Assert.False(user.IsAuthenticated);
|
||||
Assert.Null(user.Id);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("not-a-number")]
|
||||
[InlineData("0")]
|
||||
[InlineData("")]
|
||||
public async Task BindAsync_NonNumericOrZeroNameIdentifier_LeavesIdNull(string rawId)
|
||||
{
|
||||
var user = await BindAsync(AuthenticatedPrincipal(new Claim(ClaimTypes.NameIdentifier, rawId)));
|
||||
[Theory]
|
||||
[InlineData("not-a-number")]
|
||||
[InlineData("0")]
|
||||
[InlineData("")]
|
||||
public async Task BindAsync_NonNumericOrZeroNameIdentifier_LeavesIdNull(string rawId)
|
||||
{
|
||||
var user = await BindAsync(AuthenticatedPrincipal(new Claim(ClaimTypes.NameIdentifier, rawId)));
|
||||
|
||||
Assert.Null(user.Id);
|
||||
}
|
||||
Assert.Null(user.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RequiredId_MissingId_Throws()
|
||||
{
|
||||
var user = await BindAsync(new ClaimsPrincipal(new ClaimsIdentity()));
|
||||
[Fact]
|
||||
public async Task RequiredId_MissingId_Throws()
|
||||
{
|
||||
var user = await BindAsync(new ClaimsPrincipal(new ClaimsIdentity()));
|
||||
|
||||
Assert.Throws<InvalidOperationException>(() => user.RequiredId);
|
||||
}
|
||||
Assert.Throws<InvalidOperationException>(() => user.RequiredId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task HasClaim_ExistingClaimType_ReturnsTrue()
|
||||
{
|
||||
var user = await BindAsync(AuthenticatedPrincipal(new Claim("role", "admin")));
|
||||
[Fact]
|
||||
public async Task HasClaim_ExistingClaimType_ReturnsTrue()
|
||||
{
|
||||
var user = await BindAsync(AuthenticatedPrincipal(new Claim("role", "admin")));
|
||||
|
||||
Assert.True(user.HasClaim("role"));
|
||||
Assert.False(user.HasClaim("missing"));
|
||||
}
|
||||
Assert.True(user.HasClaim("role"));
|
||||
Assert.False(user.HasClaim("missing"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task FindClaim_ExistingClaimType_ReturnsItsValue()
|
||||
{
|
||||
var user = await BindAsync(AuthenticatedPrincipal(new Claim("picture", "https://avatar.example/jane.png")));
|
||||
[Fact]
|
||||
public async Task FindClaim_ExistingClaimType_ReturnsItsValue()
|
||||
{
|
||||
var user = await BindAsync(AuthenticatedPrincipal(new Claim("picture", "https://avatar.example/jane.png")));
|
||||
|
||||
Assert.Equal("https://avatar.example/jane.png", user.FindClaim("picture"));
|
||||
Assert.Null(user.FindClaim("missing"));
|
||||
Assert.Equal("https://avatar.example/jane.png", user.FindClaim("picture"));
|
||||
Assert.Null(user.FindClaim("missing"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,93 +6,94 @@ using Musify.Api.Tests.TestSupport;
|
||||
using Musify.Application.Albums.Responses;
|
||||
using Xunit;
|
||||
|
||||
namespace Musify.Api.Tests.Endpoints;
|
||||
|
||||
[Collection(ApiCollection.Name)]
|
||||
public sealed class AlbumEndpointsTests(ApiTestFixture fixture)
|
||||
namespace Musify.Api.Tests.Endpoints
|
||||
{
|
||||
private async Task<long> CreateUserAsync()
|
||||
[Collection(ApiCollection.Name)]
|
||||
public sealed class AlbumEndpointsTests(ApiTestFixture fixture)
|
||||
{
|
||||
var userId = Random.Shared.NextInt64(1, long.MaxValue);
|
||||
var response = await fixture.CreateAnonymousClient()
|
||||
.PostAsJsonAsync("/users", new CreateUserRequest(userId, $"user-{userId}", null, null));
|
||||
response.EnsureSuccessStatusCode();
|
||||
return userId;
|
||||
}
|
||||
private async Task<long> CreateUserAsync()
|
||||
{
|
||||
var userId = Random.Shared.NextInt64(1, long.MaxValue);
|
||||
var response = await fixture.CreateAnonymousClient()
|
||||
.PostAsJsonAsync("/users", new CreateUserRequest(userId, $"user-{userId}", null, null));
|
||||
response.EnsureSuccessStatusCode();
|
||||
return userId;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PostAlbums_NoAuthHeader_ReturnsUnauthorized()
|
||||
{
|
||||
var response = await fixture.CreateAnonymousClient()
|
||||
.PostAsJsonAsync("/albums", new CreateAlbumRequest("Unauthorized Album", null, null), TestContext.Current.CancellationToken);
|
||||
[Fact]
|
||||
public async Task PostAlbums_NoAuthHeader_ReturnsUnauthorized()
|
||||
{
|
||||
var response = await fixture.CreateAnonymousClient()
|
||||
.PostAsJsonAsync("/albums", new CreateAlbumRequest("Unauthorized Album", null, null), TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
}
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PostAlbums_AuthenticatedExistingUser_ReturnsCreatedAlbum()
|
||||
{
|
||||
var userId = await CreateUserAsync();
|
||||
var client = fixture.CreateAuthenticatedClient(userId);
|
||||
[Fact]
|
||||
public async Task PostAlbums_AuthenticatedExistingUser_ReturnsCreatedAlbum()
|
||||
{
|
||||
var userId = await CreateUserAsync();
|
||||
var client = fixture.CreateAuthenticatedClient(userId);
|
||||
|
||||
var response = await client.PostAsJsonAsync("/albums", new CreateAlbumRequest("My Album", "desc", 2024), TestContext.Current.CancellationToken);
|
||||
var response = await client.PostAsJsonAsync("/albums", new CreateAlbumRequest("My Album", "desc", 2024), TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
var body = await response.Content.ReadFromJsonAsync<AlbumApplicationResponse>(TestContext.Current.CancellationToken);
|
||||
Assert.NotNull(body);
|
||||
Assert.Equal("My Album", body.Title);
|
||||
Assert.Equal(userId, body.OwnerUserId);
|
||||
}
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
var body = await response.Content.ReadFromJsonAsync<AlbumApplicationResponse>(TestContext.Current.CancellationToken);
|
||||
Assert.NotNull(body);
|
||||
Assert.Equal("My Album", body.Title);
|
||||
Assert.Equal(userId, body.OwnerUserId);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PostAlbums_BlankTitle_ReturnsValidationProblem()
|
||||
{
|
||||
var userId = await CreateUserAsync();
|
||||
var client = fixture.CreateAuthenticatedClient(userId);
|
||||
[Fact]
|
||||
public async Task PostAlbums_BlankTitle_ReturnsValidationProblem()
|
||||
{
|
||||
var userId = await CreateUserAsync();
|
||||
var client = fixture.CreateAuthenticatedClient(userId);
|
||||
|
||||
var response = await client.PostAsJsonAsync("/albums", new CreateAlbumRequest("", null, null), TestContext.Current.CancellationToken);
|
||||
var response = await client.PostAsJsonAsync("/albums", new CreateAlbumRequest("", null, null), TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
}
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetAlbumById_AfterCreate_ReturnsIt()
|
||||
{
|
||||
var userId = await CreateUserAsync();
|
||||
var client = fixture.CreateAuthenticatedClient(userId);
|
||||
var created = await (await client.PostAsJsonAsync("/albums", new CreateAlbumRequest("Findable", null, null), TestContext.Current.CancellationToken))
|
||||
.Content.ReadFromJsonAsync<AlbumApplicationResponse>(TestContext.Current.CancellationToken);
|
||||
[Fact]
|
||||
public async Task GetAlbumById_AfterCreate_ReturnsIt()
|
||||
{
|
||||
var userId = await CreateUserAsync();
|
||||
var client = fixture.CreateAuthenticatedClient(userId);
|
||||
var created = await (await client.PostAsJsonAsync("/albums", new CreateAlbumRequest("Findable", null, null), TestContext.Current.CancellationToken))
|
||||
.Content.ReadFromJsonAsync<AlbumApplicationResponse>(TestContext.Current.CancellationToken);
|
||||
|
||||
var response = await fixture.CreateAnonymousClient().GetAsync($"/albums/{created!.Id}", TestContext.Current.CancellationToken);
|
||||
var response = await fixture.CreateAnonymousClient().GetAsync($"/albums/{created!.Id}", TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
}
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteAlbum_NotTheOwner_ReturnsUnauthorized()
|
||||
{
|
||||
var owner = await CreateUserAsync();
|
||||
var stranger = await CreateUserAsync();
|
||||
var created = await (await fixture.CreateAuthenticatedClient(owner).PostAsJsonAsync("/albums", new CreateAlbumRequest("Owned", null, null), TestContext.Current.CancellationToken))
|
||||
.Content.ReadFromJsonAsync<AlbumApplicationResponse>(TestContext.Current.CancellationToken);
|
||||
[Fact]
|
||||
public async Task DeleteAlbum_NotTheOwner_ReturnsUnauthorized()
|
||||
{
|
||||
var owner = await CreateUserAsync();
|
||||
var stranger = await CreateUserAsync();
|
||||
var created = await (await fixture.CreateAuthenticatedClient(owner).PostAsJsonAsync("/albums", new CreateAlbumRequest("Owned", null, null), TestContext.Current.CancellationToken))
|
||||
.Content.ReadFromJsonAsync<AlbumApplicationResponse>(TestContext.Current.CancellationToken);
|
||||
|
||||
var response = await fixture.CreateAuthenticatedClient(stranger).DeleteAsync($"/albums/{created!.Id}", TestContext.Current.CancellationToken);
|
||||
var response = await fixture.CreateAuthenticatedClient(stranger).DeleteAsync($"/albums/{created!.Id}", TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
}
|
||||
Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DeleteAlbum_Owner_ReturnsNoContentAndAlbumIsGone()
|
||||
{
|
||||
var userId = await CreateUserAsync();
|
||||
var client = fixture.CreateAuthenticatedClient(userId);
|
||||
var created = await (await client.PostAsJsonAsync("/albums", new CreateAlbumRequest("Deletable", null, null), TestContext.Current.CancellationToken))
|
||||
.Content.ReadFromJsonAsync<AlbumApplicationResponse>(TestContext.Current.CancellationToken);
|
||||
[Fact]
|
||||
public async Task DeleteAlbum_Owner_ReturnsNoContentAndAlbumIsGone()
|
||||
{
|
||||
var userId = await CreateUserAsync();
|
||||
var client = fixture.CreateAuthenticatedClient(userId);
|
||||
var created = await (await client.PostAsJsonAsync("/albums", new CreateAlbumRequest("Deletable", null, null), TestContext.Current.CancellationToken))
|
||||
.Content.ReadFromJsonAsync<AlbumApplicationResponse>(TestContext.Current.CancellationToken);
|
||||
|
||||
var deleteResponse = await client.DeleteAsync($"/albums/{created!.Id}", TestContext.Current.CancellationToken);
|
||||
var getResponse = await fixture.CreateAnonymousClient().GetAsync($"/albums/{created.Id}", TestContext.Current.CancellationToken);
|
||||
var deleteResponse = await client.DeleteAsync($"/albums/{created!.Id}", TestContext.Current.CancellationToken);
|
||||
var getResponse = await fixture.CreateAnonymousClient().GetAsync($"/albums/{created.Id}", TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.Equal(HttpStatusCode.NoContent, deleteResponse.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.NotFound, getResponse.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.NoContent, deleteResponse.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.NotFound, getResponse.StatusCode);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,69 +5,70 @@ using Musify.Api.Tests.TestSupport;
|
||||
using Musify.Application.Users.Responses;
|
||||
using Xunit;
|
||||
|
||||
namespace Musify.Api.Tests.Endpoints;
|
||||
|
||||
[Collection(ApiCollection.Name)]
|
||||
public sealed class UserEndpointsTests(ApiTestFixture fixture)
|
||||
namespace Musify.Api.Tests.Endpoints
|
||||
{
|
||||
[Fact]
|
||||
public async Task PostUsers_NewUser_ReturnsCreatedWithLocationHeader()
|
||||
[Collection(ApiCollection.Name)]
|
||||
public sealed class UserEndpointsTests(ApiTestFixture fixture)
|
||||
{
|
||||
var client = fixture.CreateAnonymousClient();
|
||||
var userId = Random.Shared.NextInt64(1, long.MaxValue);
|
||||
[Fact]
|
||||
public async Task PostUsers_NewUser_ReturnsCreatedWithLocationHeader()
|
||||
{
|
||||
var client = fixture.CreateAnonymousClient();
|
||||
var userId = Random.Shared.NextInt64(1, long.MaxValue);
|
||||
|
||||
var response = await client.PostAsJsonAsync("/users", new CreateUserRequest(userId, "Jane Doe", "Jane", "Doe"), TestContext.Current.CancellationToken);
|
||||
var response = await client.PostAsJsonAsync("/users", new CreateUserRequest(userId, "Jane Doe", "Jane", "Doe"), TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
Assert.Equal($"/users/{userId}", response.Headers.Location?.OriginalString);
|
||||
var body = await response.Content.ReadFromJsonAsync<UserApplicationResponse>(TestContext.Current.CancellationToken);
|
||||
Assert.NotNull(body);
|
||||
Assert.Equal("Jane Doe", body.Name);
|
||||
}
|
||||
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
|
||||
Assert.Equal($"/users/{userId}", response.Headers.Location?.OriginalString);
|
||||
var body = await response.Content.ReadFromJsonAsync<UserApplicationResponse>(TestContext.Current.CancellationToken);
|
||||
Assert.NotNull(body);
|
||||
Assert.Equal("Jane Doe", body.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PostUsers_BlankName_ReturnsValidationProblem()
|
||||
{
|
||||
var client = fixture.CreateAnonymousClient();
|
||||
[Fact]
|
||||
public async Task PostUsers_BlankName_ReturnsValidationProblem()
|
||||
{
|
||||
var client = fixture.CreateAnonymousClient();
|
||||
|
||||
var response = await client.PostAsJsonAsync("/users", new CreateUserRequest(Random.Shared.NextInt64(1, long.MaxValue), "", null, null), TestContext.Current.CancellationToken);
|
||||
var response = await client.PostAsJsonAsync("/users", new CreateUserRequest(Random.Shared.NextInt64(1, long.MaxValue), "", null, null), TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
}
|
||||
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PostUsers_DuplicateId_ReturnsConflict()
|
||||
{
|
||||
var client = fixture.CreateAnonymousClient();
|
||||
var userId = Random.Shared.NextInt64(1, long.MaxValue);
|
||||
await client.PostAsJsonAsync("/users", new CreateUserRequest(userId, "First", null, null), TestContext.Current.CancellationToken);
|
||||
[Fact]
|
||||
public async Task PostUsers_DuplicateId_ReturnsConflict()
|
||||
{
|
||||
var client = fixture.CreateAnonymousClient();
|
||||
var userId = Random.Shared.NextInt64(1, long.MaxValue);
|
||||
await client.PostAsJsonAsync("/users", new CreateUserRequest(userId, "First", null, null), TestContext.Current.CancellationToken);
|
||||
|
||||
var response = await client.PostAsJsonAsync("/users", new CreateUserRequest(userId, "Second", null, null), TestContext.Current.CancellationToken);
|
||||
var response = await client.PostAsJsonAsync("/users", new CreateUserRequest(userId, "Second", null, null), TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.Equal(HttpStatusCode.Conflict, response.StatusCode);
|
||||
}
|
||||
Assert.Equal(HttpStatusCode.Conflict, response.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserById_ExistingUser_ReturnsIt()
|
||||
{
|
||||
var client = fixture.CreateAnonymousClient();
|
||||
var userId = Random.Shared.NextInt64(1, long.MaxValue);
|
||||
await client.PostAsJsonAsync("/users", new CreateUserRequest(userId, "Findable User", null, null), TestContext.Current.CancellationToken);
|
||||
[Fact]
|
||||
public async Task GetUserById_ExistingUser_ReturnsIt()
|
||||
{
|
||||
var client = fixture.CreateAnonymousClient();
|
||||
var userId = Random.Shared.NextInt64(1, long.MaxValue);
|
||||
await client.PostAsJsonAsync("/users", new CreateUserRequest(userId, "Findable User", null, null), TestContext.Current.CancellationToken);
|
||||
|
||||
var response = await client.GetAsync($"/users/{userId}", TestContext.Current.CancellationToken);
|
||||
var response = await client.GetAsync($"/users/{userId}", TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
var body = await response.Content.ReadFromJsonAsync<UserApplicationResponse>(TestContext.Current.CancellationToken);
|
||||
Assert.Equal("Findable User", body?.Name);
|
||||
}
|
||||
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
|
||||
var body = await response.Content.ReadFromJsonAsync<UserApplicationResponse>(TestContext.Current.CancellationToken);
|
||||
Assert.Equal("Findable User", body?.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetUserById_MissingUser_ReturnsNotFound()
|
||||
{
|
||||
var client = fixture.CreateAnonymousClient();
|
||||
[Fact]
|
||||
public async Task GetUserById_MissingUser_ReturnsNotFound()
|
||||
{
|
||||
var client = fixture.CreateAnonymousClient();
|
||||
|
||||
var response = await client.GetAsync($"/users/{Random.Shared.NextInt64(1, long.MaxValue)}", TestContext.Current.CancellationToken);
|
||||
var response = await client.GetAsync($"/users/{Random.Shared.NextInt64(1, long.MaxValue)}", TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,134 +4,135 @@ using Microsoft.Extensions.DependencyInjection;
|
||||
using Musify.Api.Extensions;
|
||||
using Xunit;
|
||||
|
||||
namespace Musify.Api.Tests.Extensions;
|
||||
|
||||
public sealed class ErrorOrHttpExtensionsTests
|
||||
namespace Musify.Api.Tests.Extensions
|
||||
{
|
||||
// The concrete IResult types (NoContent, UnauthorizedHttpResult, ...) resolve logging/problem-
|
||||
// details services from HttpContext.RequestServices when they execute, so it can't be empty.
|
||||
private static readonly IServiceProvider Services = new ServiceCollection().AddLogging().AddProblemDetails().BuildServiceProvider();
|
||||
|
||||
private static async Task<(int StatusCode, string Body)> ExecuteAsync(IResult result)
|
||||
public sealed class ErrorOrHttpExtensionsTests
|
||||
{
|
||||
var context = new DefaultHttpContext { RequestServices = Services };
|
||||
var bodyStream = new MemoryStream();
|
||||
context.Response.Body = bodyStream;
|
||||
// The concrete IResult types (NoContent, UnauthorizedHttpResult, ...) resolve logging/problem-
|
||||
// details services from HttpContext.RequestServices when they execute, so it can't be empty.
|
||||
private static readonly IServiceProvider Services = new ServiceCollection().AddLogging().AddProblemDetails().BuildServiceProvider();
|
||||
|
||||
await result.ExecuteAsync(context);
|
||||
|
||||
bodyStream.Position = 0;
|
||||
using var reader = new StreamReader(bodyStream);
|
||||
return (context.Response.StatusCode, await reader.ReadToEndAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ToHttpResult_Success_ReturnsNoContent()
|
||||
{
|
||||
ErrorOr<Success> result = new Success();
|
||||
|
||||
var (statusCode, _) = await ExecuteAsync(result.ToHttpResult());
|
||||
|
||||
Assert.Equal(StatusCodes.Status204NoContent, statusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ToHttpResult_Value_ReturnsOkWithTheValue()
|
||||
{
|
||||
ErrorOr<string> result = "hello";
|
||||
|
||||
var (statusCode, body) = await ExecuteAsync(result.ToHttpResult());
|
||||
|
||||
Assert.Equal(StatusCodes.Status200OK, statusCode);
|
||||
Assert.Contains("hello", body);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ToHttpResult_NotFoundError_ReturnsNotFound()
|
||||
{
|
||||
ErrorOr<string> result = Error.NotFound(description: "not here");
|
||||
|
||||
var (statusCode, _) = await ExecuteAsync(result.ToHttpResult());
|
||||
|
||||
Assert.Equal(StatusCodes.Status404NotFound, statusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ToHttpResult_UnauthorizedError_ReturnsUnauthorized()
|
||||
{
|
||||
ErrorOr<string> result = Error.Unauthorized();
|
||||
|
||||
var (statusCode, _) = await ExecuteAsync(result.ToHttpResult());
|
||||
|
||||
Assert.Equal(StatusCodes.Status401Unauthorized, statusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ToHttpResult_ForbiddenError_ReturnsForbidden()
|
||||
{
|
||||
ErrorOr<string> result = Error.Forbidden();
|
||||
|
||||
var (statusCode, _) = await ExecuteAsync(result.ToHttpResult());
|
||||
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, statusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ToHttpResult_ConflictError_ReturnsConflict()
|
||||
{
|
||||
ErrorOr<string> result = Error.Conflict();
|
||||
|
||||
var (statusCode, _) = await ExecuteAsync(result.ToHttpResult());
|
||||
|
||||
Assert.Equal(StatusCodes.Status409Conflict, statusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ToHttpResult_FailureError_ReturnsProblem500()
|
||||
{
|
||||
ErrorOr<string> result = Error.Failure();
|
||||
|
||||
var (statusCode, _) = await ExecuteAsync(result.ToHttpResult());
|
||||
|
||||
Assert.Equal(StatusCodes.Status500InternalServerError, statusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ToHttpResult_ValidationErrors_ReturnsValidationProblem()
|
||||
{
|
||||
ErrorOr<string> result = new List<Error>
|
||||
private static async Task<(int StatusCode, string Body)> ExecuteAsync(IResult result)
|
||||
{
|
||||
Error.Validation("Name", "Name is required"),
|
||||
Error.Validation("Name", "Name is too long"),
|
||||
Error.Validation("Age", "Age must be positive"),
|
||||
};
|
||||
var context = new DefaultHttpContext { RequestServices = Services };
|
||||
var bodyStream = new MemoryStream();
|
||||
context.Response.Body = bodyStream;
|
||||
|
||||
var (statusCode, body) = await ExecuteAsync(result.ToHttpResult());
|
||||
await result.ExecuteAsync(context);
|
||||
|
||||
Assert.Equal(StatusCodes.Status400BadRequest, statusCode);
|
||||
Assert.Contains("Name is required", body);
|
||||
Assert.Contains("Age must be positive", body);
|
||||
}
|
||||
bodyStream.Position = 0;
|
||||
using var reader = new StreamReader(bodyStream);
|
||||
return (context.Response.StatusCode, await reader.ReadToEndAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ToCreatedResult_Success_ReturnsCreatedAtTheGivenLocation()
|
||||
{
|
||||
ErrorOr<string> result = "the-id";
|
||||
[Fact]
|
||||
public async Task ToHttpResult_Success_ReturnsNoContent()
|
||||
{
|
||||
ErrorOr<Success> result = new Success();
|
||||
|
||||
var context = new DefaultHttpContext { RequestServices = Services, Response = { Body = new MemoryStream() } };
|
||||
await result.ToCreatedResult(value => $"/things/{value}").ExecuteAsync(context);
|
||||
var (statusCode, _) = await ExecuteAsync(result.ToHttpResult());
|
||||
|
||||
Assert.Equal(StatusCodes.Status201Created, context.Response.StatusCode);
|
||||
Assert.Equal("/things/the-id", context.Response.Headers.Location);
|
||||
}
|
||||
Assert.Equal(StatusCodes.Status204NoContent, statusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ToCreatedResult_Error_ReturnsTheMappedErrorStatus()
|
||||
{
|
||||
ErrorOr<string> result = Error.Conflict();
|
||||
[Fact]
|
||||
public async Task ToHttpResult_Value_ReturnsOkWithTheValue()
|
||||
{
|
||||
ErrorOr<string> result = "hello";
|
||||
|
||||
var (statusCode, _) = await ExecuteAsync(result.ToCreatedResult(value => $"/things/{value}"));
|
||||
var (statusCode, body) = await ExecuteAsync(result.ToHttpResult());
|
||||
|
||||
Assert.Equal(StatusCodes.Status409Conflict, statusCode);
|
||||
Assert.Equal(StatusCodes.Status200OK, statusCode);
|
||||
Assert.Contains("hello", body);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ToHttpResult_NotFoundError_ReturnsNotFound()
|
||||
{
|
||||
ErrorOr<string> result = Error.NotFound(description: "not here");
|
||||
|
||||
var (statusCode, _) = await ExecuteAsync(result.ToHttpResult());
|
||||
|
||||
Assert.Equal(StatusCodes.Status404NotFound, statusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ToHttpResult_UnauthorizedError_ReturnsUnauthorized()
|
||||
{
|
||||
ErrorOr<string> result = Error.Unauthorized();
|
||||
|
||||
var (statusCode, _) = await ExecuteAsync(result.ToHttpResult());
|
||||
|
||||
Assert.Equal(StatusCodes.Status401Unauthorized, statusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ToHttpResult_ForbiddenError_ReturnsForbidden()
|
||||
{
|
||||
ErrorOr<string> result = Error.Forbidden();
|
||||
|
||||
var (statusCode, _) = await ExecuteAsync(result.ToHttpResult());
|
||||
|
||||
Assert.Equal(StatusCodes.Status403Forbidden, statusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ToHttpResult_ConflictError_ReturnsConflict()
|
||||
{
|
||||
ErrorOr<string> result = Error.Conflict();
|
||||
|
||||
var (statusCode, _) = await ExecuteAsync(result.ToHttpResult());
|
||||
|
||||
Assert.Equal(StatusCodes.Status409Conflict, statusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ToHttpResult_FailureError_ReturnsProblem500()
|
||||
{
|
||||
ErrorOr<string> result = Error.Failure();
|
||||
|
||||
var (statusCode, _) = await ExecuteAsync(result.ToHttpResult());
|
||||
|
||||
Assert.Equal(StatusCodes.Status500InternalServerError, statusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ToHttpResult_ValidationErrors_ReturnsValidationProblem()
|
||||
{
|
||||
ErrorOr<string> result = new List<Error>
|
||||
{
|
||||
Error.Validation("Name", "Name is required"),
|
||||
Error.Validation("Name", "Name is too long"),
|
||||
Error.Validation("Age", "Age must be positive"),
|
||||
};
|
||||
|
||||
var (statusCode, body) = await ExecuteAsync(result.ToHttpResult());
|
||||
|
||||
Assert.Equal(StatusCodes.Status400BadRequest, statusCode);
|
||||
Assert.Contains("Name is required", body);
|
||||
Assert.Contains("Age must be positive", body);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ToCreatedResult_Success_ReturnsCreatedAtTheGivenLocation()
|
||||
{
|
||||
ErrorOr<string> result = "the-id";
|
||||
|
||||
var context = new DefaultHttpContext { RequestServices = Services, Response = { Body = new MemoryStream() } };
|
||||
await result.ToCreatedResult(value => $"/things/{value}").ExecuteAsync(context);
|
||||
|
||||
Assert.Equal(StatusCodes.Status201Created, context.Response.StatusCode);
|
||||
Assert.Equal("/things/the-id", context.Response.Headers.Location);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ToCreatedResult_Error_ReturnsTheMappedErrorStatus()
|
||||
{
|
||||
ErrorOr<string> result = Error.Conflict();
|
||||
|
||||
var (statusCode, _) = await ExecuteAsync(result.ToCreatedResult(value => $"/things/{value}"));
|
||||
|
||||
Assert.Equal(StatusCodes.Status409Conflict, statusCode);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,61 +6,62 @@ using Musify.Api.Filters;
|
||||
using NSubstitute;
|
||||
using Xunit;
|
||||
|
||||
namespace Musify.Api.Tests.Filters;
|
||||
|
||||
public sealed class ValidationFilterTests
|
||||
namespace Musify.Api.Tests.Filters
|
||||
{
|
||||
public sealed record Payload(string Name);
|
||||
|
||||
// EndpointFilterInvocationContext.Create has no (HttpContext, object[]) overload — only
|
||||
// Create<T0>, Create<T0,T1>, etc. Passing an object[] to a params-object[] call site binds
|
||||
// to Create<T0> with T0 inferred as object[] itself, so .Arguments ends up with one element
|
||||
// (the array, boxed) instead of the array's contents — OfType<Payload>() then never matches
|
||||
// and the filter silently falls through to "no argument, skip validation" for every case.
|
||||
private static EndpointFilterInvocationContext CreateContext<T>(T argument) =>
|
||||
EndpointFilterInvocationContext.Create(new DefaultHttpContext(), argument);
|
||||
|
||||
[Fact]
|
||||
public async Task InvokeAsync_ValidPayload_CallsNext()
|
||||
public sealed class ValidationFilterTests
|
||||
{
|
||||
var validator = Substitute.For<IValidator<Payload>>();
|
||||
validator.ValidateAsync(Arg.Any<Payload>(), Arg.Any<CancellationToken>()).Returns(new ValidationResult());
|
||||
var filter = new ValidationFilter<Payload>(validator);
|
||||
var context = CreateContext(new Payload("ok"));
|
||||
public sealed record Payload(string Name);
|
||||
|
||||
var result = await filter.InvokeAsync(context, _ => ValueTask.FromResult<object?>("next-called"));
|
||||
// EndpointFilterInvocationContext.Create has no (HttpContext, object[]) overload — only
|
||||
// Create<T0>, Create<T0,T1>, etc. Passing an object[] to a params-object[] call site binds
|
||||
// to Create<T0> with T0 inferred as object[] itself, so .Arguments ends up with one element
|
||||
// (the array, boxed) instead of the array's contents — OfType<Payload>() then never matches
|
||||
// and the filter silently falls through to "no argument, skip validation" for every case.
|
||||
private static EndpointFilterInvocationContext CreateContext<T>(T argument) =>
|
||||
EndpointFilterInvocationContext.Create(new DefaultHttpContext(), argument);
|
||||
|
||||
Assert.Equal("next-called", result);
|
||||
await validator.Received(1).ValidateAsync(Arg.Is<Payload>(p => p.Name == "ok"), Arg.Any<CancellationToken>());
|
||||
}
|
||||
[Fact]
|
||||
public async Task InvokeAsync_ValidPayload_CallsNext()
|
||||
{
|
||||
var validator = Substitute.For<IValidator<Payload>>();
|
||||
validator.ValidateAsync(Arg.Any<Payload>(), Arg.Any<CancellationToken>()).Returns(new ValidationResult());
|
||||
var filter = new ValidationFilter<Payload>(validator);
|
||||
var context = CreateContext(new Payload("ok"));
|
||||
|
||||
[Fact]
|
||||
public async Task InvokeAsync_InvalidPayload_ReturnsValidationProblemWithoutCallingNext()
|
||||
{
|
||||
var validator = Substitute.For<IValidator<Payload>>();
|
||||
validator.ValidateAsync(Arg.Any<Payload>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new ValidationResult([new ValidationFailure("Name", "Name is required")]));
|
||||
var filter = new ValidationFilter<Payload>(validator);
|
||||
var context = CreateContext(new Payload(""));
|
||||
var nextCalled = false;
|
||||
var result = await filter.InvokeAsync(context, _ => ValueTask.FromResult<object?>("next-called"));
|
||||
|
||||
var result = await filter.InvokeAsync(context, _ => { nextCalled = true; return ValueTask.FromResult<object?>(null); });
|
||||
Assert.Equal("next-called", result);
|
||||
await validator.Received(1).ValidateAsync(Arg.Is<Payload>(p => p.Name == "ok"), Arg.Any<CancellationToken>());
|
||||
}
|
||||
|
||||
Assert.False(nextCalled);
|
||||
var problem = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status400BadRequest, problem.StatusCode);
|
||||
}
|
||||
[Fact]
|
||||
public async Task InvokeAsync_InvalidPayload_ReturnsValidationProblemWithoutCallingNext()
|
||||
{
|
||||
var validator = Substitute.For<IValidator<Payload>>();
|
||||
validator.ValidateAsync(Arg.Any<Payload>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new ValidationResult([new ValidationFailure("Name", "Name is required")]));
|
||||
var filter = new ValidationFilter<Payload>(validator);
|
||||
var context = CreateContext(new Payload(""));
|
||||
var nextCalled = false;
|
||||
|
||||
[Fact]
|
||||
public async Task InvokeAsync_NoMatchingArgument_CallsNextWithoutValidating()
|
||||
{
|
||||
var validator = Substitute.For<IValidator<Payload>>();
|
||||
var filter = new ValidationFilter<Payload>(validator);
|
||||
var context = CreateContext(42);
|
||||
var result = await filter.InvokeAsync(context, _ => { nextCalled = true; return ValueTask.FromResult<object?>(null); });
|
||||
|
||||
var result = await filter.InvokeAsync(context, _ => ValueTask.FromResult<object?>("next-called"));
|
||||
Assert.False(nextCalled);
|
||||
var problem = Assert.IsType<ProblemHttpResult>(result);
|
||||
Assert.Equal(StatusCodes.Status400BadRequest, problem.StatusCode);
|
||||
}
|
||||
|
||||
Assert.Equal("next-called", result);
|
||||
await validator.DidNotReceiveWithAnyArgs().ValidateAsync(Arg.Any<Payload>(), Arg.Any<CancellationToken>());
|
||||
[Fact]
|
||||
public async Task InvokeAsync_NoMatchingArgument_CallsNextWithoutValidating()
|
||||
{
|
||||
var validator = Substitute.For<IValidator<Payload>>();
|
||||
var filter = new ValidationFilter<Payload>(validator);
|
||||
var context = CreateContext(42);
|
||||
|
||||
var result = await filter.InvokeAsync(context, _ => ValueTask.FromResult<object?>("next-called"));
|
||||
|
||||
Assert.Equal("next-called", result);
|
||||
await validator.DidNotReceiveWithAnyArgs().ValidateAsync(Arg.Any<Payload>(), Arg.Any<CancellationToken>());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,111 +11,112 @@ using NSubstitute;
|
||||
using Testcontainers.PostgreSql;
|
||||
using Xunit;
|
||||
|
||||
namespace Musify.Api.Tests.TestSupport;
|
||||
|
||||
/// <summary>
|
||||
/// Boots the real <c>Musify.Api</c> host — real routing, real auth/authorization pipeline,
|
||||
/// real validators, real Mediator handlers — against a private Postgres container (so EF
|
||||
/// queries behave like production, not like a stand-in). The services this API talks to over
|
||||
/// the network (object storage, YouTube, the message bus, stream-ticket signing) are replaced
|
||||
/// with NSubstitute fakes: they are Infrastructure's job to verify against the real thing (see
|
||||
/// Musify.Infrastructure.Tests), not the HTTP layer's.
|
||||
/// </summary>
|
||||
public sealed class ApiTestFixture : WebApplicationFactory<Program>, IAsyncLifetime
|
||||
namespace Musify.Api.Tests.TestSupport
|
||||
{
|
||||
private readonly PostgreSqlContainer postgres = new PostgreSqlBuilder("postgres:17-alpine")
|
||||
.WithDatabase("musify_api_test")
|
||||
.WithUsername("postgres")
|
||||
.WithPassword("postgres")
|
||||
.Build();
|
||||
|
||||
public IStorageService StorageService { get; } = Substitute.For<IStorageService>();
|
||||
|
||||
public IEventBus EventBus { get; } = Substitute.For<IEventBus>();
|
||||
|
||||
public IYouTubeMusicService YouTubeMusicService { get; } = Substitute.For<IYouTubeMusicService>();
|
||||
|
||||
public IStreamTicketService StreamTicketService { get; } = Substitute.For<IStreamTicketService>();
|
||||
|
||||
public async ValueTask InitializeAsync()
|
||||
/// <summary>
|
||||
/// Boots the real <c>Musify.Api</c> host — real routing, real auth/authorization pipeline,
|
||||
/// real validators, real Mediator handlers — against a private Postgres container (so EF
|
||||
/// queries behave like production, not like a stand-in). The services this API talks to over
|
||||
/// the network (object storage, YouTube, the message bus, stream-ticket signing) are replaced
|
||||
/// with NSubstitute fakes: they are Infrastructure's job to verify against the real thing (see
|
||||
/// Musify.Infrastructure.Tests), not the HTTP layer's.
|
||||
/// </summary>
|
||||
public sealed class ApiTestFixture : WebApplicationFactory<Program>, IAsyncLifetime
|
||||
{
|
||||
await postgres.StartAsync();
|
||||
private readonly PostgreSqlContainer postgres = new PostgreSqlBuilder("postgres:17-alpine")
|
||||
.WithDatabase("musify_api_test")
|
||||
.WithUsername("postgres")
|
||||
.WithPassword("postgres")
|
||||
.Build();
|
||||
|
||||
using var scope = Services.CreateScope();
|
||||
var database = scope.ServiceProvider.GetRequiredService<Musify.Infrastructure.Persistence.Database>();
|
||||
await database.Database.MigrateAsync();
|
||||
}
|
||||
public IStorageService StorageService { get; } = Substitute.For<IStorageService>();
|
||||
|
||||
// xUnit v3's IAsyncLifetime IS System.IAsyncDisposable (rather than declaring its own
|
||||
// Task-returning DisposeAsync as in v2), so there is a single DisposeAsync slot to fill —
|
||||
// override the one WebApplicationFactory already provides instead of implementing the
|
||||
// interface explicitly alongside it.
|
||||
public override async ValueTask DisposeAsync()
|
||||
{
|
||||
await base.DisposeAsync();
|
||||
await postgres.DisposeAsync();
|
||||
}
|
||||
public IEventBus EventBus { get; } = Substitute.For<IEventBus>();
|
||||
|
||||
/// <summary>An <see cref="HttpClient"/> with no auth header — every protected endpoint answers 401.</summary>
|
||||
public HttpClient CreateAnonymousClient() => CreateClient();
|
||||
public IYouTubeMusicService YouTubeMusicService { get; } = Substitute.For<IYouTubeMusicService>();
|
||||
|
||||
/// <summary>An <see cref="HttpClient"/> authenticated as the given user id (see <see cref="FakeAuthenticationHandler"/>).</summary>
|
||||
public HttpClient CreateAuthenticatedClient(long userId, string userName = "test-user")
|
||||
{
|
||||
var client = CreateClient();
|
||||
client.DefaultRequestHeaders.Add(FakeAuthenticationHandler.UserIdHeader, userId.ToString());
|
||||
client.DefaultRequestHeaders.Add("X-Test-User-Name", userName);
|
||||
return client;
|
||||
}
|
||||
public IStreamTicketService StreamTicketService { get; } = Substitute.For<IStreamTicketService>();
|
||||
|
||||
protected override void ConfigureWebHost(IWebHostBuilder builder)
|
||||
{
|
||||
builder.ConfigureAppConfiguration((_, configuration) =>
|
||||
public async ValueTask InitializeAsync()
|
||||
{
|
||||
configuration.AddInMemoryCollection(new Dictionary<string, string?>
|
||||
await postgres.StartAsync();
|
||||
|
||||
using var scope = Services.CreateScope();
|
||||
var database = scope.ServiceProvider.GetRequiredService<Musify.Infrastructure.Persistence.Database>();
|
||||
await database.Database.MigrateAsync();
|
||||
}
|
||||
|
||||
// xUnit v3's IAsyncLifetime IS System.IAsyncDisposable (rather than declaring its own
|
||||
// Task-returning DisposeAsync as in v2), so there is a single DisposeAsync slot to fill —
|
||||
// override the one WebApplicationFactory already provides instead of implementing the
|
||||
// interface explicitly alongside it.
|
||||
public override async ValueTask DisposeAsync()
|
||||
{
|
||||
await base.DisposeAsync();
|
||||
await postgres.DisposeAsync();
|
||||
}
|
||||
|
||||
/// <summary>An <see cref="HttpClient"/> with no auth header — every protected endpoint answers 401.</summary>
|
||||
public HttpClient CreateAnonymousClient() => CreateClient();
|
||||
|
||||
/// <summary>An <see cref="HttpClient"/> authenticated as the given user id (see <see cref="FakeAuthenticationHandler"/>).</summary>
|
||||
public HttpClient CreateAuthenticatedClient(long userId, string userName = "test-user")
|
||||
{
|
||||
var client = CreateClient();
|
||||
client.DefaultRequestHeaders.Add(FakeAuthenticationHandler.UserIdHeader, userId.ToString());
|
||||
client.DefaultRequestHeaders.Add("X-Test-User-Name", userName);
|
||||
return client;
|
||||
}
|
||||
|
||||
protected override void ConfigureWebHost(IWebHostBuilder builder)
|
||||
{
|
||||
builder.ConfigureAppConfiguration((_, configuration) =>
|
||||
{
|
||||
["Database:ConnectionString"] = postgres.GetConnectionString(),
|
||||
["Authentication:MetadataAddress"] = "https://auth.musify.test/.well-known/openid-configuration",
|
||||
["Authentication:IssuerAddress"] = "https://auth.musify.test",
|
||||
["Authentication:AudienceAddress"] = "musify-api-test",
|
||||
["Authentication:ClientId"] = "musify-api-test",
|
||||
["Authentication:AuthorizationEndpoint"] = "https://auth.musify.test/authorize",
|
||||
["Authentication:TokenEndpoint"] = "https://auth.musify.test/token",
|
||||
["Authentication:Scopes:0"] = "openid",
|
||||
["StreamTicket:PrivateKeyPath"] = "unused-in-tests.pem",
|
||||
["OpenTelemetry:OtlpEndpoint"] = "http://localhost:4317",
|
||||
["MassTransit:Address"] = "rabbitmq://localhost:5672",
|
||||
["MassTransit:Username"] = "guest",
|
||||
["MassTransit:Password"] = "guest",
|
||||
["InfrastructureStorage:Address"] = "http://localhost:8333",
|
||||
["InfrastructureStorage:AccessKey"] = "unused-in-tests",
|
||||
["InfrastructureStorage:SecretAccessKey"] = "unused-in-tests",
|
||||
["InfrastructureStorage:ForcePathStyle"] = "true",
|
||||
["InfrastructureStorage:UseHttp"] = "true",
|
||||
["ApplicationStorage:Bucket"] = "musify-api-test",
|
||||
["StreamGateway:PublicBaseUrl"] = "http://stream.musify.test",
|
||||
["PlayList:SeedPresetPictures"] = "false",
|
||||
configuration.AddInMemoryCollection(new Dictionary<string, string?>
|
||||
{
|
||||
["Database:ConnectionString"] = postgres.GetConnectionString(),
|
||||
["Authentication:MetadataAddress"] = "https://auth.musify.test/.well-known/openid-configuration",
|
||||
["Authentication:IssuerAddress"] = "https://auth.musify.test",
|
||||
["Authentication:AudienceAddress"] = "musify-api-test",
|
||||
["Authentication:ClientId"] = "musify-api-test",
|
||||
["Authentication:AuthorizationEndpoint"] = "https://auth.musify.test/authorize",
|
||||
["Authentication:TokenEndpoint"] = "https://auth.musify.test/token",
|
||||
["Authentication:Scopes:0"] = "openid",
|
||||
["StreamTicket:PrivateKeyPath"] = "unused-in-tests.pem",
|
||||
["OpenTelemetry:OtlpEndpoint"] = "http://localhost:4317",
|
||||
["MassTransit:Address"] = "rabbitmq://localhost:5672",
|
||||
["MassTransit:Username"] = "guest",
|
||||
["MassTransit:Password"] = "guest",
|
||||
["InfrastructureStorage:Address"] = "http://localhost:8333",
|
||||
["InfrastructureStorage:AccessKey"] = "unused-in-tests",
|
||||
["InfrastructureStorage:SecretAccessKey"] = "unused-in-tests",
|
||||
["InfrastructureStorage:ForcePathStyle"] = "true",
|
||||
["InfrastructureStorage:UseHttp"] = "true",
|
||||
["ApplicationStorage:Bucket"] = "musify-api-test",
|
||||
["StreamGateway:PublicBaseUrl"] = "http://stream.musify.test",
|
||||
["PlayList:SeedPresetPictures"] = "false",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
builder.ConfigureTestServices(services =>
|
||||
{
|
||||
services.Replace(ServiceDescriptor.Singleton(StorageService));
|
||||
services.Replace(ServiceDescriptor.Scoped(_ => EventBus));
|
||||
services.Replace(ServiceDescriptor.Singleton(YouTubeMusicService));
|
||||
services.Replace(ServiceDescriptor.Singleton(StreamTicketService));
|
||||
builder.ConfigureTestServices(services =>
|
||||
{
|
||||
services.Replace(ServiceDescriptor.Singleton(StorageService));
|
||||
services.Replace(ServiceDescriptor.Scoped(_ => EventBus));
|
||||
services.Replace(ServiceDescriptor.Singleton(YouTubeMusicService));
|
||||
services.Replace(ServiceDescriptor.Singleton(StreamTicketService));
|
||||
|
||||
// Overrides the real JwtBearer scheme as the default, so requests authenticate via
|
||||
// FakeAuthenticationHandler instead of needing a real token and a reachable IdP.
|
||||
services
|
||||
.AddAuthentication(FakeAuthenticationHandler.SchemeName)
|
||||
.AddScheme<AuthenticationSchemeOptions, FakeAuthenticationHandler>(FakeAuthenticationHandler.SchemeName, _ => { });
|
||||
});
|
||||
// Overrides the real JwtBearer scheme as the default, so requests authenticate via
|
||||
// FakeAuthenticationHandler instead of needing a real token and a reachable IdP.
|
||||
services
|
||||
.AddAuthentication(FakeAuthenticationHandler.SchemeName)
|
||||
.AddScheme<AuthenticationSchemeOptions, FakeAuthenticationHandler>(FakeAuthenticationHandler.SchemeName, _ => { });
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
[CollectionDefinition(Name)]
|
||||
public sealed class ApiCollection : ICollectionFixture<ApiTestFixture>
|
||||
{
|
||||
public const string Name = "Api";
|
||||
}
|
||||
}
|
||||
|
||||
[CollectionDefinition(Name)]
|
||||
public sealed class ApiCollection : ICollectionFixture<ApiTestFixture>
|
||||
{
|
||||
public const string Name = "Api";
|
||||
}
|
||||
|
||||
@@ -4,34 +4,35 @@ using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
namespace Musify.Api.Tests.TestSupport;
|
||||
|
||||
/// <summary>
|
||||
/// Replaces the real JwtBearer handler in the test host: a request carrying the
|
||||
/// <see cref="UserIdHeader"/> header authenticates as that user id, with no real token,
|
||||
/// issuer or JWKS endpoint involved. A request without the header stays anonymous, so
|
||||
/// endpoints under <c>.RequireAuthorization()</c> correctly answer 401.
|
||||
/// </summary>
|
||||
public sealed class FakeAuthenticationHandler(
|
||||
IOptionsMonitor<AuthenticationSchemeOptions> options,
|
||||
ILoggerFactory logger,
|
||||
UrlEncoder encoder)
|
||||
: AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
|
||||
namespace Musify.Api.Tests.TestSupport
|
||||
{
|
||||
public const string SchemeName = "Test";
|
||||
public const string UserIdHeader = "X-Test-User-Id";
|
||||
|
||||
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
|
||||
/// <summary>
|
||||
/// Replaces the real JwtBearer handler in the test host: a request carrying the
|
||||
/// <see cref="UserIdHeader"/> header authenticates as that user id, with no real token,
|
||||
/// issuer or JWKS endpoint involved. A request without the header stays anonymous, so
|
||||
/// endpoints under <c>.RequireAuthorization()</c> correctly answer 401.
|
||||
/// </summary>
|
||||
public sealed class FakeAuthenticationHandler(
|
||||
IOptionsMonitor<AuthenticationSchemeOptions> options,
|
||||
ILoggerFactory logger,
|
||||
UrlEncoder encoder)
|
||||
: AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
|
||||
{
|
||||
if (!Request.Headers.TryGetValue(UserIdHeader, out var userId) || string.IsNullOrEmpty(userId))
|
||||
return Task.FromResult(AuthenticateResult.NoResult());
|
||||
public const string SchemeName = "Test";
|
||||
public const string UserIdHeader = "X-Test-User-Id";
|
||||
|
||||
var claims = new List<Claim> { new(ClaimTypes.NameIdentifier, userId!) };
|
||||
if (Request.Headers.TryGetValue("X-Test-User-Name", out var userName) && !string.IsNullOrEmpty(userName))
|
||||
claims.Add(new Claim(ClaimTypes.Name, userName!));
|
||||
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
|
||||
{
|
||||
if (!Request.Headers.TryGetValue(UserIdHeader, out var userId) || string.IsNullOrEmpty(userId))
|
||||
return Task.FromResult(AuthenticateResult.NoResult());
|
||||
|
||||
var identity = new ClaimsIdentity(claims, SchemeName);
|
||||
var ticket = new AuthenticationTicket(new ClaimsPrincipal(identity), SchemeName);
|
||||
return Task.FromResult(AuthenticateResult.Success(ticket));
|
||||
var claims = new List<Claim> { new(ClaimTypes.NameIdentifier, userId!) };
|
||||
if (Request.Headers.TryGetValue("X-Test-User-Name", out var userName) && !string.IsNullOrEmpty(userName))
|
||||
claims.Add(new Claim(ClaimTypes.Name, userName!));
|
||||
|
||||
var identity = new ClaimsIdentity(claims, SchemeName);
|
||||
var ticket = new AuthenticationTicket(new ClaimsPrincipal(identity), SchemeName);
|
||||
return Task.FromResult(AuthenticateResult.Success(ticket));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,74 +2,75 @@ using Musify.Api.DataTransferObjects.Albums;
|
||||
using Musify.Api.Validators.Albums;
|
||||
using Xunit;
|
||||
|
||||
namespace Musify.Api.Tests.Validators;
|
||||
|
||||
public sealed class CreateAlbumRequestValidatorTests
|
||||
namespace Musify.Api.Tests.Validators
|
||||
{
|
||||
private readonly CreateAlbumRequestValidator validator = new();
|
||||
|
||||
[Fact]
|
||||
public void Validate_ValidRequest_Passes()
|
||||
public sealed class CreateAlbumRequestValidatorTests
|
||||
{
|
||||
var result = validator.Validate(new CreateAlbumRequest("My Album", "A short description", 2024));
|
||||
private readonly CreateAlbumRequestValidator validator = new();
|
||||
|
||||
Assert.True(result.IsValid);
|
||||
}
|
||||
[Fact]
|
||||
public void Validate_ValidRequest_Passes()
|
||||
{
|
||||
var result = validator.Validate(new CreateAlbumRequest("My Album", "A short description", 2024));
|
||||
|
||||
[Fact]
|
||||
public void Validate_ValidRequestWithoutOptionalFields_Passes()
|
||||
{
|
||||
var result = validator.Validate(new CreateAlbumRequest("My Album", null, null));
|
||||
Assert.True(result.IsValid);
|
||||
}
|
||||
|
||||
Assert.True(result.IsValid);
|
||||
}
|
||||
[Fact]
|
||||
public void Validate_ValidRequestWithoutOptionalFields_Passes()
|
||||
{
|
||||
var result = validator.Validate(new CreateAlbumRequest("My Album", null, null));
|
||||
|
||||
[Fact]
|
||||
public void Validate_BlankTitle_Fails()
|
||||
{
|
||||
var result = validator.Validate(new CreateAlbumRequest("", null, null));
|
||||
Assert.True(result.IsValid);
|
||||
}
|
||||
|
||||
Assert.False(result.IsValid);
|
||||
Assert.Contains(result.Errors, e => e.PropertyName == nameof(CreateAlbumRequest.Title));
|
||||
}
|
||||
[Fact]
|
||||
public void Validate_BlankTitle_Fails()
|
||||
{
|
||||
var result = validator.Validate(new CreateAlbumRequest("", null, null));
|
||||
|
||||
[Fact]
|
||||
public void Validate_TitleOverMaxLength_Fails()
|
||||
{
|
||||
var result = validator.Validate(new CreateAlbumRequest(new string('a', 201), null, null));
|
||||
Assert.False(result.IsValid);
|
||||
Assert.Contains(result.Errors, e => e.PropertyName == nameof(CreateAlbumRequest.Title));
|
||||
}
|
||||
|
||||
Assert.False(result.IsValid);
|
||||
}
|
||||
[Fact]
|
||||
public void Validate_TitleOverMaxLength_Fails()
|
||||
{
|
||||
var result = validator.Validate(new CreateAlbumRequest(new string('a', 201), null, null));
|
||||
|
||||
[Fact]
|
||||
public void Validate_ReleaseYearBeforeTheEarliestBoundary_Fails()
|
||||
{
|
||||
var result = validator.Validate(new CreateAlbumRequest("Title", null, AlbumReleaseYear.Earliest - 1));
|
||||
Assert.False(result.IsValid);
|
||||
}
|
||||
|
||||
Assert.False(result.IsValid);
|
||||
}
|
||||
[Fact]
|
||||
public void Validate_ReleaseYearBeforeTheEarliestBoundary_Fails()
|
||||
{
|
||||
var result = validator.Validate(new CreateAlbumRequest("Title", null, AlbumReleaseYear.Earliest - 1));
|
||||
|
||||
[Fact]
|
||||
public void Validate_ReleaseYearAtTheEarliestBoundary_Passes()
|
||||
{
|
||||
var result = validator.Validate(new CreateAlbumRequest("Title", null, AlbumReleaseYear.Earliest));
|
||||
Assert.False(result.IsValid);
|
||||
}
|
||||
|
||||
Assert.True(result.IsValid);
|
||||
}
|
||||
[Fact]
|
||||
public void Validate_ReleaseYearAtTheEarliestBoundary_Passes()
|
||||
{
|
||||
var result = validator.Validate(new CreateAlbumRequest("Title", null, AlbumReleaseYear.Earliest));
|
||||
|
||||
[Fact]
|
||||
public void Validate_ReleaseYearAtTheLatestBoundary_Passes()
|
||||
{
|
||||
var result = validator.Validate(new CreateAlbumRequest("Title", null, AlbumReleaseYear.Latest));
|
||||
Assert.True(result.IsValid);
|
||||
}
|
||||
|
||||
Assert.True(result.IsValid);
|
||||
}
|
||||
[Fact]
|
||||
public void Validate_ReleaseYearAtTheLatestBoundary_Passes()
|
||||
{
|
||||
var result = validator.Validate(new CreateAlbumRequest("Title", null, AlbumReleaseYear.Latest));
|
||||
|
||||
[Fact]
|
||||
public void Validate_ReleaseYearPastTheLatestBoundary_Fails()
|
||||
{
|
||||
var result = validator.Validate(new CreateAlbumRequest("Title", null, AlbumReleaseYear.Latest + 1));
|
||||
Assert.True(result.IsValid);
|
||||
}
|
||||
|
||||
Assert.False(result.IsValid);
|
||||
[Fact]
|
||||
public void Validate_ReleaseYearPastTheLatestBoundary_Fails()
|
||||
{
|
||||
var result = validator.Validate(new CreateAlbumRequest("Title", null, AlbumReleaseYear.Latest + 1));
|
||||
|
||||
Assert.False(result.IsValid);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,50 +2,51 @@ using Musify.Api.DataTransferObjects.Users;
|
||||
using Musify.Api.Validators.Users;
|
||||
using Xunit;
|
||||
|
||||
namespace Musify.Api.Tests.Validators;
|
||||
|
||||
public sealed class CreateUserRequestValidatorTests
|
||||
namespace Musify.Api.Tests.Validators
|
||||
{
|
||||
private readonly CreateUserRequestValidator validator = new();
|
||||
|
||||
[Fact]
|
||||
public void Validate_ValidRequest_Passes()
|
||||
public sealed class CreateUserRequestValidatorTests
|
||||
{
|
||||
var result = validator.Validate(new CreateUserRequest(1, "Jane Doe", "Jane", "Doe"));
|
||||
private readonly CreateUserRequestValidator validator = new();
|
||||
|
||||
Assert.True(result.IsValid);
|
||||
}
|
||||
[Fact]
|
||||
public void Validate_ValidRequest_Passes()
|
||||
{
|
||||
var result = validator.Validate(new CreateUserRequest(1, "Jane Doe", "Jane", "Doe"));
|
||||
|
||||
[Fact]
|
||||
public void Validate_ZeroId_Fails()
|
||||
{
|
||||
var result = validator.Validate(new CreateUserRequest(0, "Jane Doe", null, null));
|
||||
Assert.True(result.IsValid);
|
||||
}
|
||||
|
||||
Assert.False(result.IsValid);
|
||||
Assert.Contains(result.Errors, e => e.PropertyName == nameof(CreateUserRequest.Id));
|
||||
}
|
||||
[Fact]
|
||||
public void Validate_ZeroId_Fails()
|
||||
{
|
||||
var result = validator.Validate(new CreateUserRequest(0, "Jane Doe", null, null));
|
||||
|
||||
[Fact]
|
||||
public void Validate_BlankName_Fails()
|
||||
{
|
||||
var result = validator.Validate(new CreateUserRequest(1, "", null, null));
|
||||
Assert.False(result.IsValid);
|
||||
Assert.Contains(result.Errors, e => e.PropertyName == nameof(CreateUserRequest.Id));
|
||||
}
|
||||
|
||||
Assert.False(result.IsValid);
|
||||
}
|
||||
[Fact]
|
||||
public void Validate_BlankName_Fails()
|
||||
{
|
||||
var result = validator.Validate(new CreateUserRequest(1, "", null, null));
|
||||
|
||||
[Fact]
|
||||
public void Validate_NameOverMaxLength_Fails()
|
||||
{
|
||||
var result = validator.Validate(new CreateUserRequest(1, new string('a', 49), null, null));
|
||||
Assert.False(result.IsValid);
|
||||
}
|
||||
|
||||
Assert.False(result.IsValid);
|
||||
}
|
||||
[Fact]
|
||||
public void Validate_NameOverMaxLength_Fails()
|
||||
{
|
||||
var result = validator.Validate(new CreateUserRequest(1, new string('a', 49), null, null));
|
||||
|
||||
[Fact]
|
||||
public void Validate_OptionalNamesOmitted_Passes()
|
||||
{
|
||||
var result = validator.Validate(new CreateUserRequest(1, "Jane Doe", null, null));
|
||||
Assert.False(result.IsValid);
|
||||
}
|
||||
|
||||
Assert.True(result.IsValid);
|
||||
[Fact]
|
||||
public void Validate_OptionalNamesOmitted_Passes()
|
||||
{
|
||||
var result = validator.Validate(new CreateUserRequest(1, "Jane Doe", null, null));
|
||||
|
||||
Assert.True(result.IsValid);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user