Skip to content

feat: test infrastructure consolidation — base classes, auth/response helpers, factory hooks (PR#1) - #70

Merged
zribktad merged 8 commits into
mainfrom
feature/test-explorer-categories
Apr 24, 2026
Merged

zribktad merged 8 commits into
mainfrom
feature/test-explorer-categories

Conversation

@zribktad

Copy link
Copy Markdown
Owner

Summary

  • IntegrationTestBase / IntegrationCollectionTestBase — abstract base classes that eliminate per-class Factory/Client/Ct boilerplate and centralise [Trait("Category","Integration")] + [Trait("Docker","true")] attributes; expose GetService<T>() and CreateScope()
  • HttpClientAuthExtensions — fluent AsAdmin(), AsUser(), AsTenantAdmin(), WithAuth(), WithoutAuth() wrappers over IntegrationAuthHelper; enable one-liner auth: _client.AsAdmin().GetAsync(url, ct)
  • HttpResponseTestExtensions — centralised ReadJsonAsync<T>() and ShouldBeStatusAsync() / ShouldBeOkAsync() to remove ~5-line parse boilerplate from each test
  • CustomWebApplicationFactory hooks — AdditionalServiceConfiguration and AdditionalConfiguration properties let subclasses inject config without a full ConfigureWebHost override
  • SmokeTestBase refactor — inherits IntegrationCollectionTestBase; removes duplicated _factory, Client, Ct fields
  • TestAppDbContextFactory — extracts AppDbContext + UnitOfWork creation from PostgresTestBase; base shrinks from ~110 to ~60 lines
  • .csproj — new files opted into the explicit compile allowlist

Notes

This is PR #1 of 2 (infrastructure only). No existing test class is changed here — PR #2 will migrate the 24 IClassFixture<CustomWebApplicationFactory> test classes to IntegrationTestBase and replace direct IntegrationAuthHelper.Authenticate calls with the new extension methods.

Test Plan

  • dotnet build — 0 errors, 0 warnings
  • dotnet test --filter "Category=Integration" — requires Docker (run in CI)
  • dotnet test --filter "Category=Smoke" — requires Docker (run in CI)

Copilot AI review requested due to automatic review settings April 24, 2026 17:41

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request refactors and centralizes integration testing infrastructure by introducing new base classes like IntegrationTestBase and IntegrationCollectionTestBase, a centralized TestAppDbContextFactory for Postgres tests, and several helper extensions for HttpClient and HttpResponseMessage. The feedback suggests improving consistency between the base classes by centralizing traits and service helper methods, disabling automatic redirects for the default test client, and enhancing error reporting during JSON deserialization by including the raw response body in exceptions.

Comment on lines +1 to +17
using Microsoft.AspNetCore.Mvc.Testing;
using Xunit;

namespace APITemplate.Tests.Integration;

public abstract class IntegrationCollectionTestBase
{
protected CustomWebApplicationFactory Factory { get; }
protected HttpClient Client =>
field ??= Factory.CreateClient(
new WebApplicationFactoryClientOptions { AllowAutoRedirect = false }
);
protected static CancellationToken Ct => TestContext.Current.CancellationToken;

protected IntegrationCollectionTestBase(CustomWebApplicationFactory factory) =>
Factory = factory;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

To fulfill the goal of centralizing integration test traits as mentioned in the PR description, and to provide the same utility methods as IntegrationTestBase, this class should include the category traits and the service helper methods (GetService and CreateScope).

using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.DependencyInjection;
using Xunit;

namespace APITemplate.Tests.Integration;

[Trait("Category", "Integration")]
[Trait("Docker", "true")]
public abstract class IntegrationCollectionTestBase
{
    protected CustomWebApplicationFactory Factory { get; }
    protected HttpClient Client =>
        field ??= Factory.CreateClient(
            new WebApplicationFactoryClientOptions { AllowAutoRedirect = false }
        );
    protected static CancellationToken Ct => TestContext.Current.CancellationToken;

    protected IntegrationCollectionTestBase(CustomWebApplicationFactory factory) =>
        Factory = factory;

    protected T GetService<T>()
        where T : notnull => Factory.Services.GetRequiredService<T>();

    protected IServiceScope CreateScope() => Factory.Services.CreateScope();
}

Comment on lines +1 to +11
using Microsoft.Extensions.DependencyInjection;
using Xunit;

namespace APITemplate.Tests.Integration;

[Trait("Category", "Integration")]
[Trait("Docker", "true")]
public abstract class IntegrationTestBase : IClassFixture<CustomWebApplicationFactory>
{
protected CustomWebApplicationFactory Factory { get; }
protected HttpClient Client => field ??= Factory.CreateClient();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

For consistency with IntegrationCollectionTestBase and to better support API testing (where inspecting redirect responses is often necessary), consider disabling automatic redirects for the default Client.

using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.DependencyInjection;
using Xunit;

namespace APITemplate.Tests.Integration;

[Trait("Category", "Integration")]
[Trait("Docker", "true")]
public abstract class IntegrationTestBase : IClassFixture<CustomWebApplicationFactory>
{
    protected CustomWebApplicationFactory Factory { get; }
    protected HttpClient Client => field ??= Factory.CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false });

Comment on lines +14 to +18
var body = await response.Content.ReadAsStringAsync(ct);
return JsonSerializer.Deserialize<T>(body, TestJsonOptions.CaseInsensitive)
?? throw new InvalidOperationException(
$"Response body could not be deserialized to {typeof(T).Name}. Raw: {body}"
);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

When deserialization fails (e.g., due to invalid JSON), the resulting JsonException does not typically include the response body. Wrapping this in a try-catch to provide the raw body in the exception message significantly improves the debugging experience for failed integration tests.

        var body = await response.Content.ReadAsStringAsync(ct);
        try
        {
            return JsonSerializer.Deserialize<T>(body, TestJsonOptions.CaseInsensitive)
                ?? throw new InvalidOperationException($"Response body is null. Raw: {body}");
        }
        catch (JsonException ex)
        {
            throw new InvalidOperationException($"Response body could not be deserialized to {typeof(T).Name}. Raw: {body}", ex);
        }

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Consolidates integration/smoke test infrastructure in APITemplate.Tests by introducing shared base classes and helper extensions, and by adding lightweight configuration hooks to the test WebApplicationFactory, with some Postgres test setup extraction.

Changes:

  • Added IntegrationTestBase / IntegrationCollectionTestBase plus auth/response helper extensions to reduce boilerplate across integration tests.
  • Added CustomWebApplicationFactory hooks (AdditionalConfiguration, AdditionalServiceConfiguration) to support test-specific overrides without full ConfigureWebHost overrides.
  • Extracted Postgres AppDbContext + UnitOfWork creation into TestAppDbContextFactory and refactored PostgresTestBase / SmokeTestBase accordingly.

Reviewed changes

Copilot reviewed 9 out of 9 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
tests/APITemplate.Tests/Integration/Smoke/SmokeTestBase.cs Refactors smoke base to inherit shared collection base and reuse shared Factory/Client/Ct.
tests/APITemplate.Tests/Integration/Postgres/TestAppDbContextFactory.cs New helper to create AppDbContext + UnitOfWork for Postgres tests.
tests/APITemplate.Tests/Integration/Postgres/PostgresTestBase.cs Uses TestAppDbContextFactory to reduce duplication in Postgres base.
tests/APITemplate.Tests/Integration/IntegrationTestBase.cs New base class for fixture-based integration tests + service helpers.
tests/APITemplate.Tests/Integration/IntegrationCollectionTestBase.cs New base class for collection-fixture tests with shared Client and Ct.
tests/APITemplate.Tests/Integration/Helpers/HttpResponseTestExtensions.cs Adds shared response assertions and JSON deserialization helper.
tests/APITemplate.Tests/Integration/Helpers/HttpClientAuthExtensions.cs Adds fluent HttpClient auth helpers over IntegrationAuthHelper.
tests/APITemplate.Tests/Integration/CustomWebApplicationFactory.cs Adds optional configuration/service hooks for extending factory behavior.
tests/APITemplate.Tests/APITemplate.Tests.csproj Updates explicit compile allowlist to include new helper/base files.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines 39 to 55
<Compile Include="Integration\IntegrationAuthHelper.cs" />
<Compile Include="Integration\IntegrationCollectionTestBase.cs" />
<Compile Include="Integration\IntegrationTestBase.cs" />
<Compile Include="Integration\Postgres\BffSessionPostgresTests.cs" />

Copilot AI Apr 24, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Integration\**\*.cs is removed from compilation and only explicitly included files are compiled. This PR adds Integration/Postgres/TestAppDbContextFactory.cs but it is not included here, so it will be excluded and PostgresTestBase will fail to compile. Add a <Compile Include="Integration\Postgres\TestAppDbContextFactory.cs" /> entry (or switch to a glob for the Postgres folder).

Copilot uses AI. Check for mistakes.
Comment on lines +8 to +14
public abstract class IntegrationTestBase : IClassFixture<CustomWebApplicationFactory>
{
protected CustomWebApplicationFactory Factory { get; }
protected HttpClient Client => field ??= Factory.CreateClient();
protected static CancellationToken Ct => TestContext.Current.CancellationToken;

protected IntegrationTestBase(CustomWebApplicationFactory factory) => Factory = factory;

Copilot AI Apr 24, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IntegrationTestBase hardcodes IClassFixture<CustomWebApplicationFactory>, which prevents using it with existing specialized factories that inherit from CustomWebApplicationFactory (e.g., EmptyRedisWebApplicationFactory, RateLimitingWebApplicationFactory). This also limits the usefulness of the new AdditionalConfiguration/AdditionalServiceConfiguration hooks for derived factories. Consider making the base generic (IntegrationTestBase<TFactory> : IClassFixture<TFactory> where TFactory : CustomWebApplicationFactory) so tests can opt into custom factories while still using the shared base behavior.

Suggested change
public abstract class IntegrationTestBase : IClassFixture<CustomWebApplicationFactory>
{
protected CustomWebApplicationFactory Factory { get; }
protected HttpClient Client => field ??= Factory.CreateClient();
protected static CancellationToken Ct => TestContext.Current.CancellationToken;
protected IntegrationTestBase(CustomWebApplicationFactory factory) => Factory = factory;
public abstract class IntegrationTestBase<TFactory> : IClassFixture<TFactory>
where TFactory : CustomWebApplicationFactory
{
protected TFactory Factory { get; }
protected HttpClient Client => field ??= Factory.CreateClient();
protected static CancellationToken Ct => TestContext.Current.CancellationToken;
protected IntegrationTestBase(TFactory factory) => Factory = factory;

Copilot uses AI. Check for mistakes.
tadeas.zribko added 6 commits April 24, 2026 22:23
- IntegrationTestBase / IntegrationCollectionTestBase: abstract bases that eliminate per-class Factory/Client/Ct boilerplate and centralise [Trait] attributes
- HttpClientAuthExtensions: fluent AsAdmin/AsUser/AsTenantAdmin/WithAuth/WithoutAuth wrappers over IntegrationAuthHelper
- HttpResponseTestExtensions: centralised ReadJsonAsync<T> and ShouldBeStatusAsync helpers
- CustomWebApplicationFactory: AdditionalServiceConfiguration / AdditionalConfiguration hooks for subclass customisation without full override
- SmokeTestBase: inherits IntegrationCollectionTestBase, removes duplicated fields
- TestAppDbContextFactory: extracts DbContext + UnitOfWork creation from PostgresTestBase
- .csproj: opts new files into the explicit compile allowlist
…stBase

Matches original SmokeTestBase.CreateClient() behaviour (default options).
The option was absent before the refactor — keeping it would silently change
redirect-handling for all smoke tests.
…proved JSON deserialization error handling
…ntext helpers

ToProblemDetails reads RequestServices for ErrorDocumentationOptions and
falls back to scheme+host for the Type URI. Tests were failing because
DefaultHttpContext leaves both null by default.
Previous cleanup accidentally removed files that were already updated
for the modular architecture. Re-adds them with their fixes applied
and updates csproj to explicitly include the integration test files.
@zribktad
zribktad force-pushed the feature/test-explorer-categories branch from 5cb8b88 to f9dcea2 Compare April 24, 2026 20:24
tadeas.zribko added 2 commits April 24, 2026 22:40
…antAsync helper

IdentityTokenValidatedPipeline rejects tokens whose sub claim doesn't
match a provisioned user in the DB. Tests were authenticating with a
random sub, causing 401 on every request.

Fix: RolesControllerTests now seeds an admin user via IAsyncLifetime and
authenticates with that user's KeycloakUserId as the token subject.
AssignUserRoles_Success seeds the target user inside the same tenant via
the new SeedUserInTenantAsync helper.
@zribktad
zribktad merged commit b9faf8d into main Apr 24, 2026
5 checks passed
@zribktad
zribktad deleted the feature/test-explorer-categories branch April 24, 2026 21:38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants