Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using APITemplate.Api.Middleware;
using Chatting;
using Wolverine.Http;
using FileStorage;
using HealthChecks.UI.Client;
using Identity.Auth.Security;
Expand All @@ -13,6 +12,7 @@
using Serilog.Events;
using SharedKernel.Application.Http;
using SharedKernel.Infrastructure.Health;
using Wolverine.Http;

namespace APITemplate.Api.Extensions.Startup;

Expand All @@ -22,6 +22,7 @@ public static WebApplication UseApiPipeline(this WebApplication app)
{
app.UseExceptionHandler();
app.UseHttpsRedirection();
app.UseCors();
// Correlation in Items + Serilog only (no Response) so Challenge runs before response headers.
app.UseMiddleware<CorrelationContextMiddleware>();
app.UseAuthentication();
Expand Down
38 changes: 17 additions & 21 deletions tests/APITemplate.Tests/APITemplate.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,9 @@
<Content Include="xunit.runner.json" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
<!--
Legacy integration tests still target the old monolith layout; they remain excluded. Modular
integration tests are opted in explicitly below (Docker / Testcontainers required).
Integration tests require Docker / Testcontainers; they are opted in explicitly below.
-->
<ItemGroup>
<Compile Remove="GlobalUsings.ApplicationFeatures.cs" />
<Compile Remove="Integration\**\*.cs" />
<Compile Include="Integration\Auth\BffSecurityTests.cs" />
<Compile Include="Integration\Composition\EmptyRedisHostTests.cs" />
Expand All @@ -46,7 +44,12 @@
<Compile Include="Integration\Helpers\TestConfigurationHelper.cs" />
<Compile Include="Integration\Helpers\TestOutputCacheStore.cs" />
<Compile Include="Integration\Helpers\TestServiceHelper.cs" />
<Compile Include="Integration\Helpers\HttpClientAuthExtensions.cs" />
<Compile Include="Integration\Helpers\HttpResponseTestExtensions.cs" />
<Compile Include="Integration\Helpers\TestJsonOptions.cs" />
<Compile Include="Integration\IntegrationAuthHelper.cs" />
<Compile Include="Integration\IntegrationCollectionTestBase.cs" />
<Compile Include="Integration\IntegrationTestBase.cs" />
<Compile Include="Integration\Postgres\BffSessionPostgresTests.cs" />
<Compile Include="Integration\Postgres\IdentityIntegrationTestProviders.cs" />
<Compile Include="Integration\Postgres\IsolatedPostgresDatabase.cs" />
Expand All @@ -59,24 +62,17 @@
<Compile Include="Integration\Smoke\ProductAndReviewSmokeTests.cs" />
<Compile Include="Integration\Smoke\ExampleFeaturesSmokeTests.cs" />
<Compile Include="Integration\Validation\BoundaryValidationIntegrationTests.cs" />
<Compile Remove="Unit\BackgroundJobs\BackgroundJobsServiceCollectionExtensionsTests.cs" />
<Compile Remove="Unit\BackgroundJobs\CleanupRecurringJobTests.cs" />
<Compile Remove="Unit\BackgroundJobs\EmailRetryRecurringJobTests.cs" />
<Compile Remove="Unit\BackgroundJobs\EmailRetryServiceTests.cs" />
<Compile Remove="Unit\BackgroundJobs\ExternalSyncRecurringJobTests.cs" />
<Compile Remove="Unit\BackgroundJobs\RedisDistributedJobCoordinatorTests.cs" />
<Compile Remove="Unit\BackgroundJobs\ReindexRecurringJobTests.cs" />
<Compile Remove="Unit\BackgroundJobs\TickerQRecurringJobRegistrarTests.cs" />
<Compile Remove="Unit\BackgroundJobs\TickerQSchedulerDbContextTests.cs" />
<Compile Remove="Unit\Common\PaginationDefaultsTests.cs" />
<Compile Remove="Unit\Email\**\*.cs" />
<Compile Remove="Unit\ErrorOrMapping\**\*.cs" />
<Compile Remove="Unit\Handlers\**\*.cs" />
<Compile Remove="Unit\Integration\**\*.cs" />
<Compile Remove="Unit\Observability\HttpRouteResolverTests.cs" />
<Compile Remove="Unit\Persistence\**\*.cs" />
<Compile Remove="Unit\Repositories\**\*.cs" />
<Compile Remove="Unit\Validation\**\*.cs" />
<Compile Include="Integration\Auth\AuthenticatedCrudTests.cs" />
<Compile Include="Integration\Auth\UnauthorizedAccessTests.cs" />
<Compile Include="Integration\Features\RolesControllerTests.cs" />
<Compile Include="Integration\Features\UsersControllerTests.cs" />
<Compile Include="Integration\Features\TenantsControllerTests.cs" />
<Compile Include="Integration\Infrastructure\CorsTests.cs" />
<!-- RateLimitingOptions removed in modular arch — test needs rewrite -->
<!--<Compile Include="Integration\Infrastructure\RateLimitingTests.cs" />-->
<Compile Include="Integration\Infrastructure\ScalarAndOpenApiTests.cs" />
<Compile Include="Integration\Infrastructure\WolverineNotificationTests.cs" />
<Compile Include="Integration\IntegrationResponseModels.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\APITemplate\Api\APITemplate.csproj" />
Expand Down
38 changes: 0 additions & 38 deletions tests/APITemplate.Tests/GlobalUsings.ApplicationFeatures.cs

This file was deleted.

39 changes: 0 additions & 39 deletions tests/APITemplate.Tests/Integration/Auth/AuthEdgeCasesTests.cs

This file was deleted.

54 changes: 48 additions & 6 deletions tests/APITemplate.Tests/Integration/Auth/AuthenticatedCrudTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,70 @@
using System.Net.Http.Json;
using System.Text.Json;
using APITemplate.Tests.Integration.Helpers;
using Identity.Directory.Entities;
using Microsoft.AspNetCore.Mvc.Testing;
using ProductCatalog.Features.Product.Shared;
using SharedKernel.Application.DTOs;
using SharedKernel.Contracts.Security;
using Shouldly;
using Xunit;

namespace APITemplate.Tests.Integration.Auth;

public class AuthenticatedCrudTests : IClassFixture<CustomWebApplicationFactory>
[Trait("Category", "Integration")]
[Trait("Docker", "true")]
public class AuthenticatedCrudTests : IClassFixture<CustomWebApplicationFactory>, IAsyncLifetime
{
private readonly CustomWebApplicationFactory _factory;
private readonly HttpClient _client;
private readonly Guid _tenantId = Guid.NewGuid();

private Tenant _adminTenant = default!;
private AppUser _adminUser = default!;

public AuthenticatedCrudTests(CustomWebApplicationFactory factory)
{
_client = factory.CreateClient();
_factory = factory;
_client = factory.CreateClient(
new WebApplicationFactoryClientOptions { AllowAutoRedirect = false }
);
}

public async ValueTask InitializeAsync()
{
CancellationToken ct = TestContext.Current.CancellationToken;
(_adminTenant, _adminUser) = await IntegrationAuthHelper.SeedTenantUserAsync(
_factory.Services,
"crud_admin",
"crud_admin@test.com",
ct: ct
);
AuthenticateAdmin();
}

public ValueTask DisposeAsync() => ValueTask.CompletedTask;

private void AuthenticateAdmin() =>
IntegrationAuthHelper.Authenticate(
_client,
userId: _adminUser.Id,
tenantId: _adminTenant.Id,
username: _adminUser.Username.Value,
role: "PlatformAdmin",
permissions:
[
Permission.Products.Read,
Permission.Products.Create,
Permission.Products.Update,
Permission.Products.Delete,
],
email: _adminUser.Email.Value,
subject: _adminUser.KeycloakUserId
);

[Fact]
public async Task FullCrudFlow_WorksWithAuthentication()
{
var ct = TestContext.Current.CancellationToken;
IntegrationAuthHelper.Authenticate(_client, tenantId: _tenantId);

// 2. Get all - empty
var getAllResponse = await _client.GetAsync("/api/v1/products", ct);
Expand Down Expand Up @@ -125,7 +169,6 @@ public async Task FullCrudFlow_WorksWithAuthentication()
public async Task GetById_NonExistentProduct_ReturnsNotFound()
{
var ct = TestContext.Current.CancellationToken;
IntegrationAuthHelper.Authenticate(_client, tenantId: _tenantId);

var response = await _client.GetAsync($"/api/v1/products/{Guid.NewGuid()}", ct);

Expand All @@ -136,7 +179,6 @@ public async Task GetById_NonExistentProduct_ReturnsNotFound()
public async Task Create_MultipleProducts_AllReturnedInGetAll()
{
var ct = TestContext.Current.CancellationToken;
IntegrationAuthHelper.Authenticate(_client, tenantId: _tenantId);

await _client.PostAsJsonAsync(
"/api/v1/products",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Testcontainers.MongoDb;
using Testcontainers.PostgreSql;
using Xunit;
Expand All @@ -19,6 +20,10 @@ public class CustomWebApplicationFactory : WebApplicationFactory<Program>, IAsyn
private PostgreSqlContainer? _postgres;
private MongoDbContainer? _mongo;

public Action<IServiceCollection>? AdditionalServiceConfiguration { get; init; }

public Dictionary<string, string?>? AdditionalConfiguration { get; init; }

public async ValueTask InitializeAsync()
{
// Required so Program.cs can complete RunJasperFxCommands under WebApplicationFactory (see JasperFx docs).
Expand Down Expand Up @@ -69,6 +74,8 @@ protected override void ConfigureWebHost(IWebHostBuilder builder)
config.Remove("MongoDB:ConnectionString");
config.Remove("MongoDB:DatabaseName");
configBuilder.AddInMemoryCollection(config);
if (AdditionalConfiguration is not null)
configBuilder.AddInMemoryCollection(AdditionalConfiguration);
}
);

Expand All @@ -81,6 +88,7 @@ protected override void ConfigureWebHost(IWebHostBuilder builder)
TestServiceHelper.ConfigureTestAuthentication(services);
TestServiceHelper.RemoveTickerQRuntimeServices(services);
TestServiceHelper.ReplaceStartupCoordinationWithNoOp(services);
AdditionalServiceConfiguration?.Invoke(services);
});

builder.UseEnvironment("Development");
Expand Down
Loading
Loading