backend: Add integration tests
This commit is contained in:
1 parent
fd37986f5e
commit
def23d306e
9 files changed
+526
No files matched your search
@@ -64,6 +64,14 @@ Testy webové aplikace:
|
|||||||
dotnet test --solution web/Helpdesk.Web.sln
|
dotnet test --solution web/Helpdesk.Web.sln
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Integrační testy backendu
|
||||||
|
|
||||||
|
Vyžadují .NET SDK 10 a spuštěný Docker. Testcontainers vytvoří dočasnou MariaDB 11.4 a testy spustí skutečné migrace.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
dotnet run --project backend/tests/Helpdesk.IntegrationTests/Helpdesk.IntegrationTests.csproj
|
||||||
|
```
|
||||||
|
|
||||||
## Verzování databáze
|
## Verzování databáze
|
||||||
|
|
||||||
Schéma se mění výhradně novými číslovanými skripty `db/migrations/V{NNN}__{popis}.sql`. Provedený skript se nikdy neupravuje. Migrace spouští DbUp (`Helpdesk.Migrator`) před startem API a eviduje je v tabulce `schema_version`.
|
Schéma se mění výhradně novými číslovanými skripty `db/migrations/V{NNN}__{popis}.sql`. Provedený skript se nikdy neupravuje. Migrace spouští DbUp (`Helpdesk.Migrator`) před startem API a eviduje je v tabulce `schema_version`.
|
||||||
|
|||||||
@@ -22,7 +22,9 @@
|
|||||||
<PackageVersion Include="FluentValidation" Version="12.2.0" />
|
<PackageVersion Include="FluentValidation" Version="12.2.0" />
|
||||||
<PackageVersion Include="FluentValidation.DependencyInjectionExtensions" Version="12.2.0" />
|
<PackageVersion Include="FluentValidation.DependencyInjectionExtensions" Version="12.2.0" />
|
||||||
<!-- testy -->
|
<!-- testy -->
|
||||||
|
<PackageVersion Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.14" />
|
||||||
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.11.0" />
|
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.11.0" />
|
||||||
|
<PackageVersion Include="Testcontainers.MariaDb" Version="4.16.0" />
|
||||||
<PackageVersion Include="xunit.v3" Version="4.0.2" />
|
<PackageVersion Include="xunit.v3" Version="4.0.2" />
|
||||||
<PackageVersion Include="xunit.runner.visualstudio" Version="4.0.1" />
|
<PackageVersion Include="xunit.runner.visualstudio" Version="4.0.1" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|||||||
@@ -15,6 +15,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Helpdesk.Migrator", "src\He
|
|||||||
EndProject
|
EndProject
|
||||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Helpdesk.UnitTests", "tests\Helpdesk.UnitTests\Helpdesk.UnitTests.csproj", "{AB40F473-EB15-47C7-B179-A8EB066325EC}"
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Helpdesk.UnitTests", "tests\Helpdesk.UnitTests\Helpdesk.UnitTests.csproj", "{AB40F473-EB15-47C7-B179-A8EB066325EC}"
|
||||||
EndProject
|
EndProject
|
||||||
|
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Helpdesk.IntegrationTests", "tests\Helpdesk.IntegrationTests\Helpdesk.IntegrationTests.csproj", "{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}"
|
||||||
|
EndProject
|
||||||
Global
|
Global
|
||||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||||
Debug|Any CPU = Debug|Any CPU
|
Debug|Any CPU = Debug|Any CPU
|
||||||
@@ -97,6 +99,18 @@ Global
|
|||||||
{AB40F473-EB15-47C7-B179-A8EB066325EC}.Release|x64.Build.0 = Release|Any CPU
|
{AB40F473-EB15-47C7-B179-A8EB066325EC}.Release|x64.Build.0 = Release|Any CPU
|
||||||
{AB40F473-EB15-47C7-B179-A8EB066325EC}.Release|x86.ActiveCfg = Release|Any CPU
|
{AB40F473-EB15-47C7-B179-A8EB066325EC}.Release|x86.ActiveCfg = Release|Any CPU
|
||||||
{AB40F473-EB15-47C7-B179-A8EB066325EC}.Release|x86.Build.0 = Release|Any CPU
|
{AB40F473-EB15-47C7-B179-A8EB066325EC}.Release|x86.Build.0 = Release|Any CPU
|
||||||
|
{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||||
|
{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||||
|
{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||||
|
{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Debug|x64.Build.0 = Debug|Any CPU
|
||||||
|
{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||||
|
{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Debug|x86.Build.0 = Debug|Any CPU
|
||||||
|
{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||||
|
{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||||
|
{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Release|x64.ActiveCfg = Release|Any CPU
|
||||||
|
{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Release|x64.Build.0 = Release|Any CPU
|
||||||
|
{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Release|x86.ActiveCfg = Release|Any CPU
|
||||||
|
{B8A0D31B-C086-4E70-942C-FA0B3B7D9906}.Release|x86.Build.0 = Release|Any CPU
|
||||||
EndGlobalSection
|
EndGlobalSection
|
||||||
GlobalSection(SolutionProperties) = preSolution
|
GlobalSection(SolutionProperties) = preSolution
|
||||||
HideSolutionNode = FALSE
|
HideSolutionNode = FALSE
|
||||||
|
|||||||
@@ -0,0 +1,77 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Net.Http.Json;
|
||||||
|
using Helpdesk.Application.Auth;
|
||||||
|
using Helpdesk.Domain.Auth;
|
||||||
|
using Helpdesk.Infrastructure.Persistence;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Microsoft.IdentityModel.JsonWebTokens;
|
||||||
|
using static Helpdesk.IntegrationTests.BackendFixture;
|
||||||
|
|
||||||
|
namespace Helpdesk.IntegrationTests;
|
||||||
|
|
||||||
|
public sealed class AuthTests(BackendFixture fixture) : IClassFixture<BackendFixture>
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public async Task LogoutRevokesOnlyTheCurrentSession()
|
||||||
|
{
|
||||||
|
using var anonymous = fixture.CreateClient();
|
||||||
|
var user = await fixture.RegisterAsync(anonymous);
|
||||||
|
var session = await LoginAsync(anonymous, user.Email);
|
||||||
|
var otherSession = await LoginAsync(anonymous, user.Email);
|
||||||
|
using var client = fixture.CreateClient(session.AccessToken);
|
||||||
|
using var otherClient = fixture.CreateClient(otherSession.AccessToken);
|
||||||
|
var refresh = new RefreshTokenRequest(session.RefreshToken);
|
||||||
|
|
||||||
|
await ExpectAsync(client.PostAsJsonAsync("/api/v1/auth/logout", refresh, Cancellation), HttpStatusCode.NoContent);
|
||||||
|
|
||||||
|
await ExpectAsync(client.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.Unauthorized);
|
||||||
|
await ExpectAsync(otherClient.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.OK);
|
||||||
|
var accessId = new JsonWebToken(session.AccessToken).Id;
|
||||||
|
var refreshId = new JsonWebToken(session.RefreshToken).Id;
|
||||||
|
await using var scope = fixture.Services.CreateAsyncScope();
|
||||||
|
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
||||||
|
Assert.Equal(2, await db.AuthTokens.CountAsync(token =>
|
||||||
|
token.UserId == user.Id && (token.Jti == accessId || token.Jti == refreshId) &&
|
||||||
|
token.RevokeReason == RevokeReason.Logout, Cancellation));
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task ConcurrentRefreshRevokesTheNewPairAndOtherSessions()
|
||||||
|
{
|
||||||
|
using var anonymous = fixture.CreateClient();
|
||||||
|
var user = await fixture.RegisterAsync(anonymous);
|
||||||
|
var session = await LoginAsync(anonymous, user.Email);
|
||||||
|
var otherSession = await LoginAsync(anonymous, user.Email);
|
||||||
|
var refresh = new RefreshTokenRequest(session.RefreshToken);
|
||||||
|
|
||||||
|
var pause = fixture.TokenSaves.PauseNextSave();
|
||||||
|
Task<HttpResponseMessage> first;
|
||||||
|
Task<HttpResponseMessage> duplicate;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
first = anonymous.PostAsJsonAsync("/api/v1/auth/refresh", refresh, Cancellation);
|
||||||
|
await pause.Entered.Task.WaitAsync(TimeSpan.FromSeconds(15), Cancellation);
|
||||||
|
await using var scope = fixture.Services.CreateAsyncScope();
|
||||||
|
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
||||||
|
Assert.Equal(2, await db.AuthTokens.CountAsync(token =>
|
||||||
|
token.UserId == user.Id && token.TokenType == TokenType.Refresh && token.RevokedAt == null, Cancellation));
|
||||||
|
duplicate = anonymous.PostAsJsonAsync("/api/v1/auth/refresh", refresh, Cancellation);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
pause.Release();
|
||||||
|
}
|
||||||
|
|
||||||
|
var renewed = await ReadAsync<AuthResponse>(first);
|
||||||
|
await ExpectAsync(duplicate, HttpStatusCode.Unauthorized);
|
||||||
|
await using var after = fixture.Services.CreateAsyncScope();
|
||||||
|
var tokens = after.ServiceProvider.GetRequiredService<HelpdeskDbContext>().AuthTokens;
|
||||||
|
Assert.False(await tokens.AnyAsync(token => token.UserId == user.Id && token.RevokedAt == null, Cancellation));
|
||||||
|
|
||||||
|
using var renewedClient = fixture.CreateClient(renewed.AccessToken);
|
||||||
|
using var otherClient = fixture.CreateClient(otherSession.AccessToken);
|
||||||
|
await ExpectAsync(renewedClient.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.Unauthorized);
|
||||||
|
await ExpectAsync(otherClient.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.Unauthorized);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,179 @@
|
|||||||
|
using System.Collections.Concurrent;
|
||||||
|
using System.Diagnostics;
|
||||||
|
using System.Net;
|
||||||
|
using System.Net.Http.Headers;
|
||||||
|
using System.Net.Http.Json;
|
||||||
|
using System.Security.Cryptography;
|
||||||
|
using Helpdesk.Application.Abstractions;
|
||||||
|
using Helpdesk.Application.Auth;
|
||||||
|
using Helpdesk.Application.Users;
|
||||||
|
using Helpdesk.Infrastructure.Persistence;
|
||||||
|
using Microsoft.AspNetCore.Hosting;
|
||||||
|
using Microsoft.AspNetCore.Mvc.Testing;
|
||||||
|
using Microsoft.AspNetCore.TestHost;
|
||||||
|
using Microsoft.AspNetCore.WebUtilities;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using Microsoft.Extensions.DependencyInjection.Extensions;
|
||||||
|
using Microsoft.Extensions.Hosting;
|
||||||
|
using Testcontainers.MariaDb;
|
||||||
|
|
||||||
|
namespace Helpdesk.IntegrationTests;
|
||||||
|
|
||||||
|
public sealed class BackendFixture : IAsyncLifetime
|
||||||
|
{
|
||||||
|
internal const string AdminEmail = "[email protected]";
|
||||||
|
internal const string Password = "Integration-test-password";
|
||||||
|
internal static string MigrationsPath => Path.Combine(AppContext.BaseDirectory, "migrations");
|
||||||
|
internal static CancellationToken Cancellation => TestContext.Current.CancellationToken;
|
||||||
|
|
||||||
|
private readonly MariaDbContainer database = new MariaDbBuilder("mariadb:11.4")
|
||||||
|
.WithDatabase("helpdesk")
|
||||||
|
.WithPassword(Convert.ToHexString(RandomNumberGenerator.GetBytes(24)))
|
||||||
|
.WithCommand("--character-set-server=utf8mb4")
|
||||||
|
.Build();
|
||||||
|
private readonly TestEmailSender email = new();
|
||||||
|
private ApiFactory? factory;
|
||||||
|
|
||||||
|
internal TokenSaveGate TokenSaves { get; } = new();
|
||||||
|
internal IServiceProvider Services => factory!.Services;
|
||||||
|
|
||||||
|
public async ValueTask InitializeAsync()
|
||||||
|
{
|
||||||
|
await database.StartAsync(Cancellation);
|
||||||
|
await RunMigratorAsync(database.GetConnectionString());
|
||||||
|
factory = new ApiFactory(database.GetConnectionString(), email, TokenSaves);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async ValueTask DisposeAsync()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (factory is not null)
|
||||||
|
await factory.DisposeAsync();
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
await database.DisposeAsync();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal HttpClient CreateClient(string? accessToken = null)
|
||||||
|
{
|
||||||
|
var client = factory!.CreateClient();
|
||||||
|
if (accessToken is not null)
|
||||||
|
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
|
||||||
|
return client;
|
||||||
|
}
|
||||||
|
|
||||||
|
internal async Task<UserDto> RegisterAsync(HttpClient client)
|
||||||
|
{
|
||||||
|
var address = $"{Guid.NewGuid():N}@student.example.test";
|
||||||
|
var user = await ReadAsync<UserDto>(client.PostAsJsonAsync("/api/v1/auth/register",
|
||||||
|
new RegisterRequest(address, Password, "Test", "User"), Cancellation), HttpStatusCode.Created);
|
||||||
|
await ExpectAsync(client.PostAsJsonAsync("/api/v1/auth/confirm-email",
|
||||||
|
new EmailTokenRequest(email.TakeConfirmationToken(address)), Cancellation), HttpStatusCode.NoContent);
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static Task<AuthResponse> LoginAsync(HttpClient client, string address) =>
|
||||||
|
ReadAsync<AuthResponse>(client.PostAsJsonAsync("/api/v1/auth/login",
|
||||||
|
new LoginRequest(address, Password), Cancellation));
|
||||||
|
|
||||||
|
internal static async Task<T> ReadAsync<T>(Task<HttpResponseMessage> request, HttpStatusCode expected = HttpStatusCode.OK)
|
||||||
|
where T : class
|
||||||
|
{
|
||||||
|
using var response = await request;
|
||||||
|
Assert.Equal(expected, response.StatusCode);
|
||||||
|
return Assert.IsType<T>(await response.Content.ReadFromJsonAsync<T>(Cancellation));
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static async Task ExpectAsync(Task<HttpResponseMessage> request, HttpStatusCode expected)
|
||||||
|
{
|
||||||
|
using var response = await request;
|
||||||
|
Assert.Equal(expected, response.StatusCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task RunMigratorAsync(string connectionString)
|
||||||
|
{
|
||||||
|
var startInfo = new ProcessStartInfo(Environment.GetEnvironmentVariable("DOTNET_HOST_PATH") ?? "dotnet")
|
||||||
|
{
|
||||||
|
RedirectStandardOutput = true,
|
||||||
|
RedirectStandardError = true,
|
||||||
|
};
|
||||||
|
startInfo.ArgumentList.Add(Path.Combine(AppContext.BaseDirectory, "Helpdesk.Migrator.dll"));
|
||||||
|
startInfo.Environment["ConnectionStrings__Migrator"] = connectionString;
|
||||||
|
startInfo.Environment["MIGRATIONS_PATH"] = MigrationsPath;
|
||||||
|
using var process = Process.Start(startInfo) ?? throw new InvalidOperationException("Could not start the migrator.");
|
||||||
|
var output = process.StandardOutput.ReadToEndAsync(Cancellation);
|
||||||
|
var errors = process.StandardError.ReadToEndAsync(Cancellation);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
await process.WaitForExitAsync(Cancellation);
|
||||||
|
Assert.True(process.ExitCode == 0, $"Migrator failed with exit code {process.ExitCode}.\n{await output}\n{await errors}");
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
if (!process.HasExited)
|
||||||
|
{
|
||||||
|
process.Kill();
|
||||||
|
await process.WaitForExitAsync();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class ApiFactory(string connectionString, TestEmailSender email, TokenSaveGate tokenSaves)
|
||||||
|
: WebApplicationFactory<Program>
|
||||||
|
{
|
||||||
|
private readonly Dictionary<string, string?> settings = new()
|
||||||
|
{
|
||||||
|
["ConnectionStrings:Helpdesk"] = connectionString,
|
||||||
|
["Jwt:SigningKey"] = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)),
|
||||||
|
["Encryption:Key"] = Convert.ToBase64String(RandomNumberGenerator.GetBytes(32)),
|
||||||
|
["Registration:StudentEmailDomains:0"] = "student.example.test",
|
||||||
|
["Registration:WebBaseUrl"] = "https://helpdesk.example.test",
|
||||||
|
["ADMIN_EMAIL"] = AdminEmail,
|
||||||
|
["ADMIN_PASSWORD"] = Password,
|
||||||
|
["Firebase:ServiceAccountJson"] = "",
|
||||||
|
["Smtp:Mailbox"] = "",
|
||||||
|
["Smtp:Password"] = "",
|
||||||
|
["ReverseProxy:TrustedIp"] = "",
|
||||||
|
};
|
||||||
|
|
||||||
|
protected override IHost CreateHost(IHostBuilder builder)
|
||||||
|
{
|
||||||
|
// Program čte konfiguraci před Build(), proto musí hodnoty dostat už při startu.
|
||||||
|
builder.UseEnvironment(Environments.Development)
|
||||||
|
.ConfigureHostConfiguration(config => config.AddInMemoryCollection(settings));
|
||||||
|
return base.CreateHost(builder);
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override void ConfigureWebHost(IWebHostBuilder builder) =>
|
||||||
|
builder.ConfigureTestServices(services =>
|
||||||
|
{
|
||||||
|
services.RemoveAll<IEmailSender>();
|
||||||
|
services.AddSingleton<IEmailSender>(email);
|
||||||
|
services.AddDbContext<HelpdeskDbContext>((_, options) => options.AddInterceptors(tokenSaves));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private sealed class TestEmailSender : IEmailSender
|
||||||
|
{
|
||||||
|
private readonly ConcurrentDictionary<string, string> tokens = new();
|
||||||
|
|
||||||
|
public Task SendAsync(string to, string subject, string body, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
if (Uri.TryCreate(body[(body.LastIndexOf('\n') + 1)..], UriKind.Absolute, out var link) &&
|
||||||
|
link.AbsolutePath == "/confirm-email")
|
||||||
|
tokens[to] = QueryHelpers.ParseQuery(link.Query)["token"].ToString();
|
||||||
|
return Task.CompletedTask;
|
||||||
|
}
|
||||||
|
|
||||||
|
internal string TakeConfirmationToken(string address)
|
||||||
|
{
|
||||||
|
Assert.True(tokens.TryRemove(address, out var token), "Registration did not send a confirmation link.");
|
||||||
|
return token;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
using Helpdesk.Api.Controllers;
|
||||||
|
using Helpdesk.Infrastructure.Persistence;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
|
using MySqlConnector;
|
||||||
|
using static Helpdesk.IntegrationTests.BackendFixture;
|
||||||
|
|
||||||
|
namespace Helpdesk.IntegrationTests;
|
||||||
|
|
||||||
|
public sealed class DatabaseTests(BackendFixture fixture) : IClassFixture<BackendFixture>
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public async Task MigratorAppliesEveryScriptAndEfCanReadTheSchema()
|
||||||
|
{
|
||||||
|
using var client = fixture.CreateClient();
|
||||||
|
await using var scope = fixture.Services.CreateAsyncScope();
|
||||||
|
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
||||||
|
var expected = Directory.EnumerateFiles(MigrationsPath, "V*__*.sql")
|
||||||
|
.Select(Path.GetFileName).Order(StringComparer.Ordinal).ToArray();
|
||||||
|
var applied = await db.Database
|
||||||
|
.SqlQueryRaw<string>("SELECT scriptname AS Value FROM schema_version ORDER BY schemaversionid")
|
||||||
|
.ToListAsync(Cancellation);
|
||||||
|
Assert.Equal(expected, applied);
|
||||||
|
var health = await ReadAsync<HealthResponse>(client.GetAsync("/health", Cancellation));
|
||||||
|
Assert.Equal(new HealthResponse("Healthy", expected[^1]), health);
|
||||||
|
|
||||||
|
await db.Users.AsNoTracking().ToListAsync(Cancellation);
|
||||||
|
await db.AuthTokens.AsNoTracking().ToListAsync(Cancellation);
|
||||||
|
await db.Buildings.AsNoTracking().ToListAsync(Cancellation);
|
||||||
|
await db.IssueCategories.AsNoTracking().ToListAsync(Cancellation);
|
||||||
|
await db.ProposalCategories.AsNoTracking().ToListAsync(Cancellation);
|
||||||
|
await db.Issues.AsNoTracking().ToListAsync(Cancellation);
|
||||||
|
await db.IssueEvents.AsNoTracking().ToListAsync(Cancellation);
|
||||||
|
await db.IssueTimings.ToListAsync(Cancellation);
|
||||||
|
await db.Attachments.AsNoTracking().ToListAsync(Cancellation);
|
||||||
|
await db.Proposals.AsNoTracking().ToListAsync(Cancellation);
|
||||||
|
await db.ProposalEvents.AsNoTracking().ToListAsync(Cancellation);
|
||||||
|
await db.ProposalVotes.AsNoTracking().ToListAsync(Cancellation);
|
||||||
|
await db.ProposalScores.ToListAsync(Cancellation);
|
||||||
|
await db.Notifications.AsNoTracking().ToListAsync(Cancellation);
|
||||||
|
await db.NotificationDeliveries.AsNoTracking().ToListAsync(Cancellation);
|
||||||
|
await db.PushDevices.AsNoTracking().ToListAsync(Cancellation);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task DatabaseRejectsAnAssignedIssueWithoutAnAssignee()
|
||||||
|
{
|
||||||
|
await using var scope = fixture.Services.CreateAsyncScope();
|
||||||
|
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
|
||||||
|
var reporterId = await db.Users.Select(user => user.Id).SingleAsync(Cancellation);
|
||||||
|
var categoryId = await db.IssueCategories.MinAsync(category => category.Id, Cancellation);
|
||||||
|
|
||||||
|
var error = await Assert.ThrowsAsync<MySqlException>(() => db.Database.ExecuteSqlInterpolatedAsync($"""
|
||||||
|
INSERT INTO issue (title, description, category_id, reporter_id, status)
|
||||||
|
VALUES ('Test', 'Test', {categoryId}, {reporterId}, 'ASSIGNED')
|
||||||
|
""", Cancellation));
|
||||||
|
Assert.Contains("ck_issue_assignee", error.Message);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<IsPackable>false</IsPackable>
|
||||||
|
<OutputType>Exe</OutputType>
|
||||||
|
<UseMicrosoftTestingPlatformRunner>true</UseMicrosoftTestingPlatformRunner>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<ProjectReference Include="..\..\src\Helpdesk.Api\Helpdesk.Api.csproj" />
|
||||||
|
<ProjectReference Include="..\..\src\Helpdesk.Migrator\Helpdesk.Migrator.csproj" />
|
||||||
|
<None Include="..\..\..\db\migrations\V*__*.sql" Link="migrations\%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" />
|
||||||
|
<PackageReference Include="MySqlConnector" />
|
||||||
|
<PackageReference Include="Testcontainers.MariaDb" />
|
||||||
|
<PackageReference Include="xunit.v3" />
|
||||||
|
<Using Include="Xunit" />
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
using System.Net;
|
||||||
|
using System.Net.Http.Json;
|
||||||
|
using Helpdesk.Application.Auth;
|
||||||
|
using Helpdesk.Application.Catalogs;
|
||||||
|
using Helpdesk.Application.Common;
|
||||||
|
using Helpdesk.Application.Issues;
|
||||||
|
using Helpdesk.Application.Notifications;
|
||||||
|
using Helpdesk.Application.Statistics;
|
||||||
|
using Helpdesk.Application.Users;
|
||||||
|
using static Helpdesk.IntegrationTests.BackendFixture;
|
||||||
|
|
||||||
|
namespace Helpdesk.IntegrationTests;
|
||||||
|
|
||||||
|
public sealed class IssueWorkflowTests(BackendFixture fixture) : IClassFixture<BackendFixture>
|
||||||
|
{
|
||||||
|
[Fact]
|
||||||
|
public async Task ReporterAndAssigneesCanResolveAnIssueAndManagementCanReportOnIt()
|
||||||
|
{
|
||||||
|
using var anonymous = fixture.CreateClient();
|
||||||
|
using var admin = fixture.CreateClient((await LoginAsync(anonymous, AdminEmail)).AccessToken);
|
||||||
|
var author = await fixture.RegisterAsync(anonymous);
|
||||||
|
using var reporter = fixture.CreateClient((await LoginAsync(anonymous, author.Email)).AccessToken);
|
||||||
|
var management = await CreateStaffAsync(anonymous, admin, "MANAGEMENT");
|
||||||
|
var firstAssignee = await CreateStaffAsync(anonymous, admin, "FACILITY_MANAGER");
|
||||||
|
var secondAssignee = await CreateStaffAsync(anonymous, admin, "FACILITY_MANAGER");
|
||||||
|
using var manager = fixture.CreateClient(management.AccessToken);
|
||||||
|
using var firstSolver = fixture.CreateClient(firstAssignee.AccessToken);
|
||||||
|
using var secondSolver = fixture.CreateClient(secondAssignee.AccessToken);
|
||||||
|
|
||||||
|
var categories = await ReadAsync<CategoryDto[]>(reporter.GetAsync("/api/v1/issue-categories", Cancellation));
|
||||||
|
var buildings = await ReadAsync<BuildingDto[]>(reporter.GetAsync("/api/v1/buildings", Cancellation));
|
||||||
|
var request = new CreateIssueRequest("Nefunkční projektor", "Projektor se nezapne.", categories[0].Id, buildings[0].Id, "A101");
|
||||||
|
var issue = await PostIssueAsync(reporter, "/api/v1/issues", request, HttpStatusCode.Created);
|
||||||
|
var path = $"/api/v1/issues/{issue.Id}";
|
||||||
|
Assert.Equal("RECEIVED", issue.Status);
|
||||||
|
await ExpectAsync(anonymous.GetAsync(path, Cancellation), HttpStatusCode.Unauthorized);
|
||||||
|
|
||||||
|
var assign = new AssignIssueRequest(firstAssignee.User.Id, null, issue.RowVersion);
|
||||||
|
await ExpectAsync(reporter.PostAsJsonAsync(path + "/assign", assign, Cancellation), HttpStatusCode.Forbidden);
|
||||||
|
issue = await PostIssueAsync(manager, path + "/assign", assign);
|
||||||
|
await ExpectAsync(firstSolver.PostAsJsonAsync(path + "/start",
|
||||||
|
new IssueVersionRequest(assign.RowVersion), Cancellation), HttpStatusCode.Conflict);
|
||||||
|
|
||||||
|
var reporterNotifications = await InboxAsync(reporter, issue.Id);
|
||||||
|
Assert.Equal("ISSUE_STATUS_CHANGED", Assert.Single(reporterNotifications).Type);
|
||||||
|
issue = await PostIssueAsync(manager, path + "/assign", new AssignIssueRequest(secondAssignee.User.Id, null, issue.RowVersion));
|
||||||
|
Assert.Equal("ISSUE_ASSIGNED", Assert.Single(await InboxAsync(secondSolver, issue.Id)).Type);
|
||||||
|
Assert.Equal(reporterNotifications, await InboxAsync(reporter, issue.Id));
|
||||||
|
|
||||||
|
issue = await PostIssueAsync(secondSolver, path + "/start", new IssueVersionRequest(issue.RowVersion));
|
||||||
|
Assert.Equal("IN_PROGRESS", issue.Status);
|
||||||
|
reporterNotifications = await InboxAsync(reporter, issue.Id);
|
||||||
|
issue = await PostIssueAsync(manager, path + "/assign", new AssignIssueRequest(firstAssignee.User.Id, null, issue.RowVersion));
|
||||||
|
Assert.Equal("ASSIGNED", issue.Status);
|
||||||
|
var reassignment = Assert.Single((await InboxAsync(reporter, issue.Id)).Except(reporterNotifications));
|
||||||
|
Assert.Equal("ISSUE_STATUS_CHANGED", reassignment.Type);
|
||||||
|
Assert.Equal(2, (await InboxAsync(firstSolver, issue.Id)).Count(notification => notification.Type == "ISSUE_ASSIGNED"));
|
||||||
|
|
||||||
|
issue = await PostIssueAsync(firstSolver, path + "/start", new IssueVersionRequest(issue.RowVersion));
|
||||||
|
const string commentText = "Porucha stále trvá.";
|
||||||
|
var comment = await ReadAsync<IssueEventDto>(reporter.PostAsJsonAsync(path + "/comments",
|
||||||
|
new CommentRequest(commentText), Cancellation));
|
||||||
|
issue = await ReadAsync<IssueDetail>(firstSolver.GetAsync(path, Cancellation));
|
||||||
|
issue = await PostIssueAsync(firstSolver, path + "/submit-for-verification", new VerifyIssueRequest(issue.RowVersion, null));
|
||||||
|
Assert.Equal("PENDING_VERIFICATION", issue.Status);
|
||||||
|
issue = await PostIssueAsync(reporter, path + "/confirm", new IssueVersionRequest(issue.RowVersion));
|
||||||
|
Assert.Equal("RESOLVED", issue.Status);
|
||||||
|
var events = await ReadAsync<IssueEventDto[]>(reporter.GetAsync(path + "/events", Cancellation));
|
||||||
|
Assert.Equal(commentText, Assert.Single(events, entry => entry.Id == comment.Id).Note);
|
||||||
|
Assert.Equal("RESOLVED", events[^1].ToStatus);
|
||||||
|
|
||||||
|
var openIssue = await PostIssueAsync(reporter, "/api/v1/issues",
|
||||||
|
request with { Title = "Porucha osvětlení" }, HttpStatusCode.Created);
|
||||||
|
await VerifyReadsAsync(reporter, manager, issue, openIssue);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<AuthResponse> CreateStaffAsync(HttpClient anonymous, HttpClient admin, string role)
|
||||||
|
{
|
||||||
|
var user = await fixture.RegisterAsync(anonymous);
|
||||||
|
await ExpectAsync(admin.PutAsJsonAsync($"/api/v1/admin/users/{user.Id}/role",
|
||||||
|
new ChangeRoleRequest(role), Cancellation), HttpStatusCode.NoContent);
|
||||||
|
return await LoginAsync(anonymous, user.Email);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static async Task VerifyReadsAsync(HttpClient reporter, HttpClient manager, IssueDetail resolved, IssueDetail open)
|
||||||
|
{
|
||||||
|
var query = $"/api/v1/issues?categoryId={resolved.CategoryId}&buildingId={resolved.BuildingId}&pageSize=1";
|
||||||
|
var first = await ReadAsync<PagedResult<IssueSummary>>(manager.GetAsync(query + "&page=1", Cancellation));
|
||||||
|
var second = await ReadAsync<PagedResult<IssueSummary>>(manager.GetAsync(query + "&page=2", Cancellation));
|
||||||
|
var filtered = await ReadAsync<PagedResult<IssueSummary>>(manager.GetAsync(query + "&status=RESOLVED", Cancellation));
|
||||||
|
Assert.Equal(2, first.TotalCount);
|
||||||
|
Assert.Equal(open.Id, Assert.Single(first.Items).Id);
|
||||||
|
Assert.Equal(resolved.Id, Assert.Single(second.Items).Id);
|
||||||
|
Assert.Equal(1, filtered.TotalCount);
|
||||||
|
Assert.Equal(resolved.Id, Assert.Single(filtered.Items).Id);
|
||||||
|
|
||||||
|
const string overview = "/api/v1/statistics/overview";
|
||||||
|
await ExpectAsync(reporter.GetAsync(overview, Cancellation), HttpStatusCode.Forbidden);
|
||||||
|
var from = Uri.EscapeDataString(resolved.CreatedAt.AddMinutes(-1).ToString("O"));
|
||||||
|
var to = Uri.EscapeDataString(open.CreatedAt.AddMinutes(1).ToString("O"));
|
||||||
|
var period = $"?from={from}&to={to}";
|
||||||
|
var statistics = await ReadAsync<StatisticsOverview>(manager.GetAsync(overview + period, Cancellation));
|
||||||
|
Assert.Equal(2, statistics.TotalIssues);
|
||||||
|
Assert.Equal(1, statistics.IssuesByStatus["RESOLVED"]);
|
||||||
|
Assert.Equal(1, statistics.IssuesByStatus["RECEIVED"]);
|
||||||
|
Assert.NotNull(statistics.AverageHoursToAssignment);
|
||||||
|
Assert.NotNull(statistics.AverageHoursToClosure);
|
||||||
|
var trend = await ReadAsync<IssueTrendPoint[]>(manager.GetAsync("/api/v1/statistics/issues/trend" + period, Cancellation));
|
||||||
|
Assert.Equal(2, trend.Sum(point => point.CreatedIssues));
|
||||||
|
Assert.Equal(1, trend.Sum(point => point.ClosedIssues));
|
||||||
|
var after = await ReadAsync<StatisticsOverview>(manager.GetAsync(overview + $"?from={to}", Cancellation));
|
||||||
|
Assert.Equal(0, after.TotalIssues);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Task<IssueDetail> PostIssueAsync<T>(
|
||||||
|
HttpClient client, string path, T request, HttpStatusCode expected = HttpStatusCode.OK) =>
|
||||||
|
ReadAsync<IssueDetail>(client.PostAsJsonAsync(path, request, Cancellation), expected);
|
||||||
|
|
||||||
|
private static async Task<NotificationDto[]> InboxAsync(HttpClient client, int issueId)
|
||||||
|
{
|
||||||
|
var notifications = await ReadAsync<PagedResult<NotificationDto>>(client.GetAsync("/api/v1/notifications", Cancellation));
|
||||||
|
return notifications.Items.Where(notification => notification.IssueId == issueId).ToArray();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
using Helpdesk.Domain.Auth;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.EntityFrameworkCore.Diagnostics;
|
||||||
|
|
||||||
|
namespace Helpdesk.IntegrationTests;
|
||||||
|
|
||||||
|
internal sealed class TokenSaveGate : SaveChangesInterceptor
|
||||||
|
{
|
||||||
|
private Pause? next;
|
||||||
|
|
||||||
|
internal Pause PauseNextSave()
|
||||||
|
{
|
||||||
|
var pause = new Pause();
|
||||||
|
if (Interlocked.CompareExchange(ref next, pause, null) is not null)
|
||||||
|
throw new InvalidOperationException("A save is already scheduled to pause.");
|
||||||
|
return pause;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override async ValueTask<InterceptionResult<int>> SavingChangesAsync(
|
||||||
|
DbContextEventData eventData, InterceptionResult<int> result, CancellationToken cancellationToken = default)
|
||||||
|
{
|
||||||
|
if (Volatile.Read(ref next) is not null &&
|
||||||
|
eventData.Context!.ChangeTracker.Entries<AuthToken>()
|
||||||
|
.Any(entry => entry.State == EntityState.Added && entry.Entity.TokenType == TokenType.Refresh) &&
|
||||||
|
Interlocked.Exchange(ref next, null) is { } pause)
|
||||||
|
{
|
||||||
|
pause.Entered.TrySetResult();
|
||||||
|
await pause.Released.Task.WaitAsync(cancellationToken);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
internal sealed class Pause
|
||||||
|
{
|
||||||
|
internal TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||||
|
internal TaskCompletionSource Released { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||||
|
|
||||||
|
internal void Release() => Released.TrySetResult();
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user