backend: Expand backend integration test coverage

This commit is contained in:
GonnaHetzMe committed 2026-12-02 23:56:26 +01:00
1 parent ce04c8beb3
commit 32bc5a4691
8 files changed
+500 -19

No files matched your search

@@ -0,0 +1,98 @@
using System.Net;
using System.Net.Http.Json;
using System.Text;
using Helpdesk.Application.Auth;
using Helpdesk.Application.Catalogs;
using Helpdesk.Application.Common;
using Helpdesk.Application.Users;
using Helpdesk.Infrastructure.Persistence;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using static Helpdesk.IntegrationTests.BackendFixture;
namespace Helpdesk.IntegrationTests;
public sealed class AdministrationTests(BackendFixture fixture) : IClassFixture<BackendFixture>
{
[Theory]
[InlineData("/api/v1/issue-categories")]
[InlineData("/api/v1/proposal-categories")]
public async Task AdministratorsCanManageCategories(string route)
{
using var anonymous = fixture.CreateClient();
using var admin = fixture.CreateClient((await LoginAsync(anonymous, AdminEmail)).AccessToken);
var user = await fixture.RegisterAsync(anonymous);
using var member = fixture.CreateClient((await LoginAsync(anonymous, user.Email)).AccessToken);
var request = new SaveCategoryRequest("Testovací kategorie", "Popis");
await ExpectAsync(member.PostAsJsonAsync(route, request, Cancellation), HttpStatusCode.Forbidden);
var category = await ReadAsync<CategoryDto>(admin.PostAsJsonAsync(route, request, Cancellation), HttpStatusCode.Created);
await ExpectAsync(admin.PostAsJsonAsync(route, request, Cancellation), HttpStatusCode.Conflict);
var path = $"{route}/{category.Id}";
var edited = await ReadAsync<CategoryDto>(admin.PutAsJsonAsync(path, request with { Name = "Upravená kategorie" }, Cancellation));
Assert.Equal("Upravená kategorie", edited.Name);
await ExpectAsync(admin.DeleteAsync(path, Cancellation), HttpStatusCode.NoContent);
var active = await ReadAsync<CategoryDto[]>(member.GetAsync(route + "?includeInactive=true", Cancellation));
var all = await ReadAsync<CategoryDto[]>(admin.GetAsync(route + "?includeInactive=true", Cancellation));
Assert.DoesNotContain(active, item => item.Id == category.Id);
Assert.False(Assert.Single(all, item => item.Id == category.Id).IsActive);
}
[Fact]
public async Task BuildingCodesAreUniqueAndInactiveBuildingsStayAvailableToTheAdministrator()
{
using var anonymous = fixture.CreateClient();
using var admin = fixture.CreateClient((await LoginAsync(anonymous, AdminEmail)).AccessToken);
const string route = "/api/v1/buildings";
var request = new SaveBuildingRequest("TEST", "Testovací budova", null);
var building = await ReadAsync<BuildingDto>(admin.PostAsJsonAsync(route, request, Cancellation), HttpStatusCode.Created);
await ExpectAsync(admin.PostAsJsonAsync(route, request with { Code = " TEST " }, Cancellation), HttpStatusCode.Conflict);
var path = $"{route}/{building.Id}";
var edited = await ReadAsync<BuildingDto>(admin.PutAsJsonAsync(path, request with { Address = "Náměstí 1" }, Cancellation));
Assert.Equal("Náměstí 1", edited.Address);
await ExpectAsync(admin.DeleteAsync(path, Cancellation), HttpStatusCode.NoContent);
var active = await ReadAsync<BuildingDto[]>(admin.GetAsync(route, Cancellation));
var all = await ReadAsync<BuildingDto[]>(admin.GetAsync(route + "?includeInactive=true", Cancellation));
Assert.DoesNotContain(active, item => item.Id == building.Id);
Assert.False(Assert.Single(all, item => item.Id == building.Id).IsActive);
}
[Fact]
public async Task ProfileDataRoundTripsAndDeactivationRevokesTheSession()
{
using var anonymous = fixture.CreateClient();
using var admin = fixture.CreateClient((await LoginAsync(anonymous, AdminEmail)).AccessToken);
var user = await fixture.RegisterAsync(anonymous);
using var member = fixture.CreateClient((await LoginAsync(anonymous, user.Email)).AccessToken);
const string profile = "/api/v1/users/me";
const string phone = "+420 123 456 789";
var request = new UpdateProfileRequest("Jana", "Nováková", phone, false);
var validation = await ReadAsync<ValidationProblemDetails>(member.PutAsJsonAsync(profile,
request with { Phone = "invalid" }, Cancellation), HttpStatusCode.BadRequest);
Assert.Contains("phone", validation.Errors.Keys);
var updated = await ReadAsync<UserDto>(member.PutAsJsonAsync(profile, request, Cancellation));
Assert.Equal(updated, await ReadAsync<UserDto>(member.GetAsync(profile, Cancellation)));
Assert.Equal((request.FirstName, request.LastName, phone, false),
(updated.FirstName, updated.LastName, updated.Phone, updated.EmailNotificationsEnabled));
await using var scope = fixture.Services.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
var encrypted = await db.Database.SqlQuery<byte[]>($"SELECT phone_encrypted AS Value FROM app_user WHERE id = {user.Id}")
.SingleAsync(Cancellation);
Assert.NotEmpty(encrypted);
Assert.False(Encoding.UTF8.GetBytes(phone).SequenceEqual(encrypted));
var search = $"/api/v1/admin/users?q={Uri.EscapeDataString(user.Email)}&role=STUDENT&pageSize=1";
await ExpectAsync(member.GetAsync(search, Cancellation), HttpStatusCode.Forbidden);
var page = await ReadAsync<PagedResult<AdminUserDto>>(admin.GetAsync(search, Cancellation));
Assert.Equal(user.Id, Assert.Single(page.Items).Id);
var activation = $"/api/v1/admin/users/{user.Id}/active";
await ExpectAsync(admin.PutAsJsonAsync(activation, new SetActiveRequest(false), Cancellation), HttpStatusCode.NoContent);
await ExpectAsync(member.GetAsync(profile, Cancellation), HttpStatusCode.Unauthorized);
await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(user.Email, Password), Cancellation),
HttpStatusCode.Forbidden);
await ExpectAsync(admin.PutAsJsonAsync(activation, new SetActiveRequest(true), Cancellation), HttpStatusCode.NoContent);
Assert.Equal(user.Id, (await LoginAsync(anonymous, user.Email)).User.Id);
}
}
@@ -0,0 +1,95 @@
using System.Globalization;
using System.IO.Compression;
using System.Net;
using System.Net.Http.Json;
using Helpdesk.Application.Catalogs;
using Helpdesk.Application.Issues;
using Helpdesk.Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using static Helpdesk.IntegrationTests.BackendFixture;
namespace Helpdesk.IntegrationTests;
public sealed class AttachmentTests(BackendFixture fixture) : IClassFixture<BackendFixture>
{
[Fact]
public async Task AttachmentsRespectFormatAndAccessAndFailedBatchesAreNotSaved()
{
using var anonymous = fixture.CreateClient();
var authorUser = await fixture.RegisterAsync(anonymous);
var otherUser = await fixture.RegisterAsync(anonymous);
using var author = fixture.CreateClient((await LoginAsync(anonymous, authorUser.Email)).AccessToken);
using var other = fixture.CreateClient((await LoginAsync(anonymous, otherUser.Email)).AccessToken);
var categories = await ReadAsync<CategoryDto[]>(author.GetAsync("/api/v1/issue-categories", Cancellation));
var png = Convert.FromBase64String("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Wl6t1sAAAAASUVORK5CYII=");
using var createForm = new MultipartFormDataContent();
createForm.Add(new StringContent("Rozbitý zámek"), "title");
createForm.Add(new StringContent("Dveře nelze odemknout."), "description");
createForm.Add(new StringContent(categories[0].Id.ToString(CultureInfo.InvariantCulture)), "categoryId");
AddFile(createForm, "zamek.png", png);
await using var scope = fixture.Services.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
var store = scope.ServiceProvider.GetRequiredService<IAttachmentStore>();
try
{
var issue = await ReadAsync<IssueDetail>(author.PostAsync("/api/v1/issues", createForm, Cancellation), HttpStatusCode.Created);
var pngAttachment = Assert.Single(issue.Attachments);
var download = $"/api/v1/attachments/{pngAttachment.Id}";
using var fetched = await author.GetAsync(download, Cancellation);
Assert.Equal(HttpStatusCode.OK, fetched.StatusCode);
Assert.Equal("image/png", fetched.Content.Headers.ContentType?.MediaType);
Assert.Equal("nosniff", Assert.Single(fetched.Headers.GetValues("X-Content-Type-Options")));
Assert.Equal(png, await fetched.Content.ReadAsByteArrayAsync(Cancellation));
await ExpectAsync(other.GetAsync(download, Cancellation), HttpStatusCode.Forbidden);
var path = $"/api/v1/issues/{issue.Id}/attachments";
using var mixed = new MultipartFormDataContent();
AddFile(mixed, "spravny.pdf", "%PDF-1.7\n%%EOF"u8.ToArray());
AddFile(mixed, "podvrzeny.png", "obsah nemá formát PNG"u8.ToArray());
await ExpectAsync(author.PostAsync(path, mixed, Cancellation), HttpStatusCode.BadRequest);
using var wrongField = new MultipartFormDataContent();
wrongField.Add(new ByteArrayContent(png), "image", "zamek.png");
await ExpectAsync(author.PostAsync(path, wrongField, Cancellation), HttpStatusCode.BadRequest);
var afterFailure = await ReadAsync<IssueDetail>(author.GetAsync($"/api/v1/issues/{issue.Id}", Cancellation));
Assert.Equal(issue.RowVersion, afterFailure.RowVersion);
Assert.Equal(pngAttachment.Id, Assert.Single(afterFailure.Attachments).Id);
using var files = new MultipartFormDataContent();
AddFile(files, "protokol.pdf", "%PDF-1.7\n%%EOF"u8.ToArray());
AddFile(files, "fotka.jpg", [0xff, 0xd8, 0xff, 0xd9]);
AddFile(files, "fotka.heic", [0, 0, 0, 20, .. "ftypmif1"u8, 0, 0, 0, 0, .. "heic"u8]);
AddFile(files, "protokol.docx", Docx());
var added = await ReadAsync<AttachmentDto[]>(author.PostAsync(path, files, Cancellation));
Assert.Equal(["application/pdf", "image/jpeg", "image/heic",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document"], added.Select(item => item.ContentType));
var key = await db.Attachments.Where(item => item.Id == pngAttachment.Id).Select(item => item.StoredFileName).SingleAsync(Cancellation);
store.Delete(key);
await ExpectAsync(author.GetAsync(download, Cancellation), HttpStatusCode.NotFound);
}
finally
{
foreach (var key in await db.Attachments.Select(item => item.StoredFileName).ToListAsync(CancellationToken.None))
store.Delete(key);
}
}
private static void AddFile(MultipartFormDataContent form, string name, byte[] bytes) =>
form.Add(new ByteArrayContent(bytes), "files", name);
private static byte[] Docx()
{
using var stream = new MemoryStream();
using (var zip = new ZipArchive(stream, ZipArchiveMode.Create, leaveOpen: true))
{
using (var contentTypes = zip.CreateEntry("[Content_Types].xml").Open())
contentTypes.Write("<Types/>"u8);
using (var document = zip.CreateEntry("word/document.xml").Open())
document.Write("<document/>"u8);
}
return stream.ToArray();
}
}
@@ -12,6 +12,27 @@ namespace Helpdesk.IntegrationTests;
public sealed class AuthTests(BackendFixture fixture) : IClassFixture<BackendFixture> public sealed class AuthTests(BackendFixture fixture) : IClassFixture<BackendFixture>
{ {
[Fact]
public async Task ChangingPasswordThroughAnEmailLinkRevokesTheOldSession()
{
using var anonymous = fixture.CreateClient();
var user = await fixture.RegisterAsync(anonymous);
using var oldSession = fixture.CreateClient((await LoginAsync(anonymous, user.Email)).AccessToken);
await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/forgot-password",
new ForgotPasswordRequest(user.Email), Cancellation), HttpStatusCode.NoContent);
const string newPassword = "New-integration-password";
var reset = new ResetPasswordRequest(await fixture.TakeResetTokenAsync(user.Email), newPassword);
await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/reset-password", reset, Cancellation), HttpStatusCode.NoContent);
await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/reset-password", reset, Cancellation), HttpStatusCode.BadRequest);
await ExpectAsync(oldSession.GetAsync("/api/v1/users/me", Cancellation), HttpStatusCode.Unauthorized);
await ExpectAsync(anonymous.PostAsJsonAsync("/api/v1/auth/login",
new LoginRequest(user.Email, Password), Cancellation), HttpStatusCode.Unauthorized);
var session = await ReadAsync<AuthResponse>(anonymous.PostAsJsonAsync("/api/v1/auth/login",
new LoginRequest(user.Email, newPassword), Cancellation));
Assert.Equal(user.Id, session.User.Id);
}
[Fact] [Fact]
public async Task LogoutRevokesOnlyTheCurrentSession() public async Task LogoutRevokesOnlyTheCurrentSession()
{ {
@@ -6,6 +6,7 @@ using System.Net.Http.Json;
using System.Security.Cryptography; using System.Security.Cryptography;
using Helpdesk.Application.Abstractions; using Helpdesk.Application.Abstractions;
using Helpdesk.Application.Auth; using Helpdesk.Application.Auth;
using Helpdesk.Application.Common;
using Helpdesk.Application.Users; using Helpdesk.Application.Users;
using Helpdesk.Infrastructure.Persistence; using Helpdesk.Infrastructure.Persistence;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
@@ -73,10 +74,23 @@ public sealed class BackendFixture : IAsyncLifetime
var user = await ReadAsync<UserDto>(client.PostAsJsonAsync("/api/v1/auth/register", var user = await ReadAsync<UserDto>(client.PostAsJsonAsync("/api/v1/auth/register",
new RegisterRequest(address, Password, "Test", "User"), Cancellation), HttpStatusCode.Created); new RegisterRequest(address, Password, "Test", "User"), Cancellation), HttpStatusCode.Created);
await ExpectAsync(client.PostAsJsonAsync("/api/v1/auth/confirm-email", await ExpectAsync(client.PostAsJsonAsync("/api/v1/auth/confirm-email",
new EmailTokenRequest(email.TakeConfirmationToken(address)), Cancellation), HttpStatusCode.NoContent); new EmailTokenRequest(await email.TakeTokenAsync(address, "/confirm-email")), Cancellation), HttpStatusCode.NoContent);
return user; return user;
} }
internal async Task<AuthResponse> RegisterStaffAsync(HttpClient anonymous, HttpClient admin, string role)
{
var user = await 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);
}
internal Task<string> TakeResetTokenAsync(string address) => email.TakeTokenAsync(address, "/reset-password");
internal void FailNextEmail(string address, string reason, bool retryable) =>
email.Failures[address] = new EmailDeliveryException(reason, retryable);
internal static Task<AuthResponse> LoginAsync(HttpClient client, string address) => internal static Task<AuthResponse> LoginAsync(HttpClient client, string address) =>
ReadAsync<AuthResponse>(client.PostAsJsonAsync("/api/v1/auth/login", ReadAsync<AuthResponse>(client.PostAsJsonAsync("/api/v1/auth/login",
new LoginRequest(address, Password), Cancellation)); new LoginRequest(address, Password), Cancellation));
@@ -160,20 +174,32 @@ public sealed class BackendFixture : IAsyncLifetime
private sealed class TestEmailSender : IEmailSender private sealed class TestEmailSender : IEmailSender
{ {
private readonly ConcurrentDictionary<string, string> tokens = new(); private readonly ConcurrentDictionary<(string Address, string Path), TaskCompletionSource<string>> tokens = new();
internal ConcurrentDictionary<string, EmailDeliveryException> Failures { get; } = new();
public Task SendAsync(string to, string subject, string body, CancellationToken cancellationToken = default) public Task SendAsync(string to, string subject, string body, CancellationToken cancellationToken = default)
{ {
if (Failures.TryRemove(to, out var failure))
throw failure;
if (Uri.TryCreate(body[(body.LastIndexOf('\n') + 1)..], UriKind.Absolute, out var link) && if (Uri.TryCreate(body[(body.LastIndexOf('\n') + 1)..], UriKind.Absolute, out var link) &&
link.AbsolutePath == "/confirm-email") link.AbsolutePath is "/confirm-email" or "/reset-password")
tokens[to] = QueryHelpers.ParseQuery(link.Query)["token"].ToString(); {
var token = QueryHelpers.ParseQuery(link.Query)["token"].ToString();
GetTokenSlot((to, link.AbsolutePath)).TrySetResult(token);
}
return Task.CompletedTask; return Task.CompletedTask;
} }
internal string TakeConfirmationToken(string address) internal async Task<string> TakeTokenAsync(string address, string path)
{ {
Assert.True(tokens.TryRemove(address, out var token), "Registration did not send a confirmation link."); var key = (address, path);
var token = await GetTokenSlot(key).Task.WaitAsync(TimeSpan.FromSeconds(10), Cancellation);
tokens.TryRemove(key, out _);
return token; return token;
} }
private TaskCompletionSource<string> GetTokenSlot((string Address, string Path) key) =>
tokens.GetOrAdd(key, _ => new(TaskCreationOptions.RunContinuationsAsynchronously));
} }
} }
@@ -1,4 +1,5 @@
using Helpdesk.Api.Controllers; using Helpdesk.Api.Controllers;
using System.Text.Json;
using Helpdesk.Infrastructure.Persistence; using Helpdesk.Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
@@ -42,6 +43,24 @@ public sealed class DatabaseTests(BackendFixture fixture) : IClassFixture<Backen
await db.PushDevices.AsNoTracking().ToListAsync(Cancellation); await db.PushDevices.AsNoTracking().ToListAsync(Cancellation);
} }
[Fact]
public async Task OpenApiDescribesMultipartIssueRequests()
{
using var client = fixture.CreateClient();
using var document = await ReadAsync<JsonDocument>(client.GetAsync("/swagger/v1/swagger.json", Cancellation));
var paths = document.RootElement.GetProperty("paths");
var create = paths.GetProperty("/api/v1/issues").GetProperty("post").GetProperty("requestBody").GetProperty("content");
Assert.True(create.TryGetProperty("application/json", out _));
var createSchema = create.GetProperty("multipart/form-data").GetProperty("schema");
Assert.Contains(createSchema.GetProperty("required").EnumerateArray(), field => field.GetString() == "categoryId");
var uploadSchema = paths.GetProperty("/api/v1/issues/{id}/attachments").GetProperty("post")
.GetProperty("requestBody").GetProperty("content").GetProperty("multipart/form-data").GetProperty("schema");
Assert.Equal("files", Assert.Single(uploadSchema.GetProperty("required").EnumerateArray()).GetString());
var files = uploadSchema.GetProperty("properties").GetProperty("files");
Assert.Equal(5, files.GetProperty("maxItems").GetInt32());
Assert.Equal("binary", files.GetProperty("items").GetProperty("format").GetString());
}
[Fact] [Fact]
public async Task DatabaseRejectsAnAssignedIssueWithoutAnAssignee() public async Task DatabaseRejectsAnAssignedIssueWithoutAnAssignee()
{ {
@@ -1,12 +1,10 @@
using System.Net; using System.Net;
using System.Net.Http.Json; using System.Net.Http.Json;
using Helpdesk.Application.Auth;
using Helpdesk.Application.Catalogs; using Helpdesk.Application.Catalogs;
using Helpdesk.Application.Common; using Helpdesk.Application.Common;
using Helpdesk.Application.Issues; using Helpdesk.Application.Issues;
using Helpdesk.Application.Notifications; using Helpdesk.Application.Notifications;
using Helpdesk.Application.Statistics; using Helpdesk.Application.Statistics;
using Helpdesk.Application.Users;
using static Helpdesk.IntegrationTests.BackendFixture; using static Helpdesk.IntegrationTests.BackendFixture;
namespace Helpdesk.IntegrationTests; namespace Helpdesk.IntegrationTests;
@@ -20,9 +18,9 @@ public sealed class IssueWorkflowTests(BackendFixture fixture) : IClassFixture<B
using var admin = fixture.CreateClient((await LoginAsync(anonymous, AdminEmail)).AccessToken); using var admin = fixture.CreateClient((await LoginAsync(anonymous, AdminEmail)).AccessToken);
var author = await fixture.RegisterAsync(anonymous); var author = await fixture.RegisterAsync(anonymous);
using var reporter = fixture.CreateClient((await LoginAsync(anonymous, author.Email)).AccessToken); using var reporter = fixture.CreateClient((await LoginAsync(anonymous, author.Email)).AccessToken);
var management = await CreateStaffAsync(anonymous, admin, "MANAGEMENT"); var management = await fixture.RegisterStaffAsync(anonymous, admin, "MANAGEMENT");
var firstAssignee = await CreateStaffAsync(anonymous, admin, "FACILITY_MANAGER"); var firstAssignee = await fixture.RegisterStaffAsync(anonymous, admin, "FACILITY_MANAGER");
var secondAssignee = await CreateStaffAsync(anonymous, admin, "FACILITY_MANAGER"); var secondAssignee = await fixture.RegisterStaffAsync(anonymous, admin, "FACILITY_MANAGER");
using var manager = fixture.CreateClient(management.AccessToken); using var manager = fixture.CreateClient(management.AccessToken);
using var firstSolver = fixture.CreateClient(firstAssignee.AccessToken); using var firstSolver = fixture.CreateClient(firstAssignee.AccessToken);
using var secondSolver = fixture.CreateClient(secondAssignee.AccessToken); using var secondSolver = fixture.CreateClient(secondAssignee.AccessToken);
@@ -35,6 +33,10 @@ public sealed class IssueWorkflowTests(BackendFixture fixture) : IClassFixture<B
Assert.Equal("RECEIVED", issue.Status); Assert.Equal("RECEIVED", issue.Status);
await ExpectAsync(anonymous.GetAsync(path, Cancellation), HttpStatusCode.Unauthorized); await ExpectAsync(anonymous.GetAsync(path, Cancellation), HttpStatusCode.Unauthorized);
issue = await ReadAsync<IssueDetail>(reporter.PutAsJsonAsync(path,
new EditIssueRequest(issue.Title, "Projektor nereaguje ani po restartu.", issue.CategoryId,
issue.BuildingId, issue.LocationDetail, issue.RowVersion), Cancellation));
Assert.Equal("Projektor nereaguje ani po restartu.", issue.Description);
var assign = new AssignIssueRequest(firstAssignee.User.Id, null, issue.RowVersion); var assign = new AssignIssueRequest(firstAssignee.User.Id, null, issue.RowVersion);
await ExpectAsync(reporter.PostAsJsonAsync(path + "/assign", assign, Cancellation), HttpStatusCode.Forbidden); await ExpectAsync(reporter.PostAsJsonAsync(path + "/assign", assign, Cancellation), HttpStatusCode.Forbidden);
issue = await PostIssueAsync(manager, path + "/assign", assign); issue = await PostIssueAsync(manager, path + "/assign", assign);
@@ -63,6 +65,10 @@ public sealed class IssueWorkflowTests(BackendFixture fixture) : IClassFixture<B
issue = await ReadAsync<IssueDetail>(firstSolver.GetAsync(path, Cancellation)); issue = await ReadAsync<IssueDetail>(firstSolver.GetAsync(path, Cancellation));
issue = await PostIssueAsync(firstSolver, path + "/submit-for-verification", new VerifyIssueRequest(issue.RowVersion, null)); issue = await PostIssueAsync(firstSolver, path + "/submit-for-verification", new VerifyIssueRequest(issue.RowVersion, null));
Assert.Equal("PENDING_VERIFICATION", issue.Status); Assert.Equal("PENDING_VERIFICATION", issue.Status);
issue = await PostIssueAsync(reporter, path + "/reopen", new IssueReasonRequest(issue.RowVersion, "Porucha se vrátila."));
Assert.Equal("IN_PROGRESS", issue.Status);
Assert.Contains(await InboxAsync(firstSolver, issue.Id), notification => notification.Type == "ISSUE_REOPENED");
issue = await PostIssueAsync(firstSolver, path + "/submit-for-verification", new VerifyIssueRequest(issue.RowVersion, "Ověřeno."));
issue = await PostIssueAsync(reporter, path + "/confirm", new IssueVersionRequest(issue.RowVersion)); issue = await PostIssueAsync(reporter, path + "/confirm", new IssueVersionRequest(issue.RowVersion));
Assert.Equal("RESOLVED", issue.Status); Assert.Equal("RESOLVED", issue.Status);
var events = await ReadAsync<IssueEventDto[]>(reporter.GetAsync(path + "/events", Cancellation)); var events = await ReadAsync<IssueEventDto[]>(reporter.GetAsync(path + "/events", Cancellation));
@@ -72,14 +78,9 @@ public sealed class IssueWorkflowTests(BackendFixture fixture) : IClassFixture<B
var openIssue = await PostIssueAsync(reporter, "/api/v1/issues", var openIssue = await PostIssueAsync(reporter, "/api/v1/issues",
request with { Title = "Porucha osvětlení" }, HttpStatusCode.Created); request with { Title = "Porucha osvětlení" }, HttpStatusCode.Created);
await VerifyReadsAsync(reporter, manager, issue, openIssue); await VerifyReadsAsync(reporter, manager, issue, openIssue);
} var rejected = await PostIssueAsync(manager, $"/api/v1/issues/{openIssue.Id}/reject",
new IssueReasonRequest(openIssue.RowVersion, "Duplicitní hlášení."));
private async Task<AuthResponse> CreateStaffAsync(HttpClient anonymous, HttpClient admin, string role) Assert.Equal("REJECTED", rejected.Status);
{
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) private static async Task VerifyReadsAsync(HttpClient reporter, HttpClient manager, IssueDetail resolved, IssueDetail open)
@@ -105,6 +106,18 @@ public sealed class IssueWorkflowTests(BackendFixture fixture) : IClassFixture<B
Assert.Equal(1, statistics.IssuesByStatus["RECEIVED"]); Assert.Equal(1, statistics.IssuesByStatus["RECEIVED"]);
Assert.NotNull(statistics.AverageHoursToAssignment); Assert.NotNull(statistics.AverageHoursToAssignment);
Assert.NotNull(statistics.AverageHoursToClosure); Assert.NotNull(statistics.AverageHoursToClosure);
var byCategory = Assert.Single(await ReadAsync<IssueCategoryStatistics[]>(
manager.GetAsync("/api/v1/statistics/issues/by-category" + period, Cancellation)));
Assert.Equal((resolved.CategoryId, 2), (byCategory.CategoryId, byCategory.IssueCount));
Assert.NotNull(byCategory.AverageHoursToResolution);
var byBuilding = Assert.Single(await ReadAsync<IssueBuildingStatistics[]>(
manager.GetAsync("/api/v1/statistics/issues/by-building" + period, Cancellation)));
Assert.Equal((resolved.BuildingId, 2), (byBuilding.BuildingId, byBuilding.IssueCount));
var byAssignee = Assert.Single(await ReadAsync<IssueAssigneeStatistics[]>(
manager.GetAsync("/api/v1/statistics/issues/by-assignee" + period, Cancellation)));
Assert.Equal((resolved.AssigneeId, 1, 0), ((int?)byAssignee.AssigneeId, byAssignee.ResolvedIssues, byAssignee.OpenIssues));
var available = await ReadAsync<AssignableUserDto[]>(manager.GetAsync("/api/v1/users/assignable", Cancellation));
Assert.Contains(available, user => user.Id == resolved.AssigneeId && user.OpenIssues == 0);
var trend = await ReadAsync<IssueTrendPoint[]>(manager.GetAsync("/api/v1/statistics/issues/trend" + period, Cancellation)); var trend = await ReadAsync<IssueTrendPoint[]>(manager.GetAsync("/api/v1/statistics/issues/trend" + period, Cancellation));
Assert.Equal(2, trend.Sum(point => point.CreatedIssues)); Assert.Equal(2, trend.Sum(point => point.CreatedIssues));
Assert.Equal(1, trend.Sum(point => point.ClosedIssues)); Assert.Equal(1, trend.Sum(point => point.ClosedIssues));
@@ -0,0 +1,112 @@
using System.Net;
using System.Net.Http.Json;
using Helpdesk.Api.Controllers;
using Helpdesk.Application.Catalogs;
using Helpdesk.Application.Common;
using Helpdesk.Application.Issues;
using Helpdesk.Application.Notifications;
using Helpdesk.Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using static Helpdesk.IntegrationTests.BackendFixture;
namespace Helpdesk.IntegrationTests;
public sealed class NotificationTests(BackendFixture fixture) : IClassFixture<BackendFixture>
{
[Fact]
public async Task FailedEmailCanBeRetriedAndOnlyTheRecipientCanMarkNotificationsRead()
{
using var anonymous = fixture.CreateClient();
using var admin = fixture.CreateClient((await LoginAsync(anonymous, AdminEmail)).AccessToken);
var user = await fixture.RegisterAsync(anonymous);
using var reporter = fixture.CreateClient((await LoginAsync(anonymous, user.Email)).AccessToken);
var managerSession = await fixture.RegisterStaffAsync(anonymous, admin, "MANAGEMENT");
using var manager = fixture.CreateClient(managerSession.AccessToken);
var categories = await ReadAsync<CategoryDto[]>(reporter.GetAsync("/api/v1/issue-categories", Cancellation));
var request = new CreateIssueRequest("Porucha v učebně", "Závadu je potřeba prověřit.", categories[0].Id, null, null);
const string inbox = "/api/v1/notifications";
const string deliveries = "/api/v1/admin/notification-deliveries";
fixture.FailNextEmail(managerSession.User.Email, "TEST_RECIPIENT_REJECTED", retryable: false);
var issue = await ReadAsync<IssueDetail>(reporter.PostAsJsonAsync("/api/v1/issues", request, Cancellation), HttpStatusCode.Created);
var notifications = await ReadAsync<PagedResult<NotificationDto>>(manager.GetAsync(inbox + "?unreadOnly=true", Cancellation));
var notification = Assert.Single(notifications.Items);
Assert.Equal((issue.Id, "ISSUE_CREATED"), (notification.IssueId, notification.Type));
await ExpectAsync(reporter.PostAsync($"{inbox}/{notification.Id}/read", null, Cancellation), HttpStatusCode.NotFound);
await ExpectAsync(reporter.GetAsync(deliveries, Cancellation), HttpStatusCode.Forbidden);
await ExpectAsync(admin.GetAsync(deliveries + "?status=invalid", Cancellation), HttpStatusCode.BadRequest);
var failed = await WaitForDeliveryAsync(admin, notification.Id, "FAILED");
Assert.Equal((1, "TEST_RECIPIENT_REJECTED"), (failed.AttemptCount, failed.LastError));
Assert.Null(failed.NextAttemptAt);
var retry = $"{deliveries}/{failed.Id}/retry";
await ExpectAsync(admin.PostAsync(retry, null, Cancellation), HttpStatusCode.NoContent);
var sent = await WaitForDeliveryAsync(admin, notification.Id, "SENT");
Assert.Equal(1, sent.AttemptCount);
Assert.NotNull(sent.SentAt);
Assert.Null(sent.LastError);
await ExpectAsync(admin.PostAsync(retry, null, Cancellation), HttpStatusCode.Conflict);
await ExpectAsync(admin.PostAsync($"{deliveries}/{int.MaxValue}/retry", null, Cancellation), HttpStatusCode.NotFound);
var read = $"{inbox}/{notification.Id}/read";
await ExpectAsync(manager.PostAsync(read, null, Cancellation), HttpStatusCode.NoContent);
await ExpectAsync(manager.PostAsync(read, null, Cancellation), HttpStatusCode.NoContent);
Assert.Equal(0, (await ReadAsync<UnreadCountDto>(manager.GetAsync(inbox + "/unread-count", Cancellation))).Count);
fixture.FailNextEmail(managerSession.User.Email, "TEST_TEMPORARY_FAILURE", retryable: true);
var secondIssue = await ReadAsync<IssueDetail>(reporter.PostAsJsonAsync("/api/v1/issues", request, Cancellation), HttpStatusCode.Created);
notifications = await ReadAsync<PagedResult<NotificationDto>>(manager.GetAsync(inbox + "?unreadOnly=true", Cancellation));
notification = Assert.Single(notifications.Items);
Assert.Equal(secondIssue.Id, notification.IssueId);
var pending = await WaitForDeliveryAsync(admin, notification.Id, "PENDING", attempts: 1);
Assert.Equal("TEST_TEMPORARY_FAILURE", pending.LastError);
Assert.True(pending.NextAttemptAt > DateTime.UtcNow);
await ExpectAsync(manager.PostAsync(inbox + "/read-all", null, Cancellation), HttpStatusCode.NoContent);
Assert.Empty((await ReadAsync<PagedResult<NotificationDto>>(manager.GetAsync(inbox + "?unreadOnly=true", Cancellation))).Items);
}
[Fact]
public async Task DeviceRegistrationPreservesCaseAndTransfersOwnership()
{
using var anonymous = fixture.CreateClient();
var firstUser = await fixture.RegisterAsync(anonymous);
var secondUser = await fixture.RegisterAsync(anonymous);
using var first = fixture.CreateClient((await LoginAsync(anonymous, firstUser.Email)).AccessToken);
using var second = fixture.CreateClient((await LoginAsync(anonymous, secondUser.Email)).AccessToken);
const string route = "/api/v1/devices";
var token = new RegisterDeviceRequest("CaseSensitiveDevice");
var otherCase = new RegisterDeviceRequest("casesensitivedevice");
await ExpectAsync(first.PostAsJsonAsync(route, new RegisterDeviceRequest("invalid token"), Cancellation), HttpStatusCode.BadRequest);
await ExpectAsync(first.PostAsJsonAsync(route, token, Cancellation), HttpStatusCode.NoContent);
await ExpectAsync(first.PostAsJsonAsync(route, otherCase, Cancellation), HttpStatusCode.NoContent);
await ExpectAsync(second.PostAsJsonAsync(route, token, Cancellation), HttpStatusCode.NoContent);
await ExpectAsync(first.DeleteAsync($"{route}/{token.Token}", Cancellation), HttpStatusCode.NoContent);
await using var scope = fixture.Services.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<HelpdeskDbContext>();
var devices = await db.PushDevices.AsNoTracking().ToListAsync(Cancellation);
Assert.Equal(secondUser.Id, Assert.Single(devices, item => item.FcmToken == token.Token).UserId);
Assert.Equal(firstUser.Id, Assert.Single(devices, item => item.FcmToken == otherCase.Token).UserId);
await ExpectAsync(second.DeleteAsync($"{route}/{token.Token}", Cancellation), HttpStatusCode.NoContent);
Assert.Equal(otherCase.Token, await db.PushDevices.Select(item => item.FcmToken).SingleAsync(Cancellation));
}
private static async Task<NotificationDeliveryDto> WaitForDeliveryAsync(HttpClient client, int notificationId, string status, int attempts = 1)
{
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(Cancellation);
timeout.CancelAfter(TimeSpan.FromSeconds(15));
var path = $"/api/v1/admin/notification-deliveries?status={status}";
while (!timeout.IsCancellationRequested)
{
var page = await ReadAsync<PagedResult<NotificationDeliveryDto>>(client.GetAsync(path, timeout.Token));
var delivery = page.Items.SingleOrDefault(item =>
item.NotificationId == notificationId && item.Channel == "EMAIL" && item.AttemptCount == attempts);
if (delivery is not null)
return delivery;
await Task.Delay(TimeSpan.FromMilliseconds(100), timeout.Token);
}
throw new TimeoutException($"Notification {notificationId} did not reach {status}.");
}
}
@@ -0,0 +1,97 @@
using System.Net;
using System.Net.Http.Json;
using Helpdesk.Application.Catalogs;
using Helpdesk.Application.Common;
using Helpdesk.Application.Notifications;
using Helpdesk.Application.Proposals;
using Helpdesk.Application.Statistics;
using static Helpdesk.IntegrationTests.BackendFixture;
namespace Helpdesk.IntegrationTests;
public sealed class ProposalWorkflowTests(BackendFixture fixture) : IClassFixture<BackendFixture>
{
private const string Proposals = "/api/v1/proposals";
[Fact]
public async Task VotesAndDecisionsAreReflectedInTheProposalAndItsHistory()
{
using var anonymous = fixture.CreateClient();
using var admin = fixture.CreateClient((await LoginAsync(anonymous, AdminEmail)).AccessToken);
var authorUser = await fixture.RegisterAsync(anonymous);
using var author = fixture.CreateClient((await LoginAsync(anonymous, authorUser.Email)).AccessToken);
var managerSession = await fixture.RegisterStaffAsync(anonymous, admin, "MANAGEMENT");
using var manager = fixture.CreateClient(managerSession.AccessToken);
var categories = await ReadAsync<CategoryDto[]>(author.GetAsync("/api/v1/proposal-categories", Cancellation));
var request = new SaveProposalRequest("Prodloužení studovny", "Rozšířit večerní otevírací dobu.", categories[0].Id);
await ExpectAsync(author.PostAsJsonAsync(Proposals, request with { Title = " " }, Cancellation), HttpStatusCode.BadRequest);
await ExpectAsync(author.PostAsJsonAsync(Proposals, request with { CategoryId = int.MaxValue }, Cancellation), HttpStatusCode.BadRequest);
var proposal = await ReadAsync<ProposalDetail>(author.PostAsJsonAsync(Proposals, request, Cancellation), HttpStatusCode.Created);
Assert.Equal("SUBMITTED", proposal.Status);
var path = $"{Proposals}/{proposal.Id}";
var edit = request with { CategoryId = categories[1].Id, Description = "Otevřít do 22 hodin." };
await ExpectAsync(manager.PutAsJsonAsync(path, edit, Cancellation), HttpStatusCode.Forbidden);
proposal = await ReadAsync<ProposalDetail>(author.PutAsJsonAsync(path, edit, Cancellation));
Assert.Equal((edit.CategoryId, edit.Description, "UPDATED"), (proposal.CategoryId, proposal.Description, proposal.Events[^1].EventType));
var other = await ReadAsync<ProposalDetail>(author.PostAsJsonAsync(Proposals, edit with
{
Title = "Vybavení studovny",
}, Cancellation), HttpStatusCode.Created);
await VerifyVotesAsync(author, manager, path);
var from = Uri.EscapeDataString(proposal.CreatedAt.AddMinutes(-1).ToString("O"));
var to = Uri.EscapeDataString(other.CreatedAt.AddMinutes(1).ToString("O"));
var filter = $"{Proposals}?status=SUBMITTED&categoryId={edit.CategoryId}&authorId={authorUser.Id}&q=studovny&from={from}&to={to}";
var first = await ReadAsync<PagedResult<ProposalSummary>>(manager.GetAsync(filter + "&sort=score&pageSize=1", Cancellation));
var second = await ReadAsync<PagedResult<ProposalSummary>>(manager.GetAsync(filter + "&sort=score&pageSize=1&page=2", Cancellation));
Assert.Equal(2, first.TotalCount);
Assert.Equal(proposal.Id, Assert.Single(first.Items).Id);
Assert.Equal(other.Id, Assert.Single(second.Items).Id);
var newest = await ReadAsync<PagedResult<ProposalSummary>>(manager.GetAsync(filter, Cancellation));
Assert.Equal(other.Id, newest.Items[0].Id);
var outside = await ReadAsync<PagedResult<ProposalSummary>>(manager.GetAsync($"{Proposals}?from={to}", Cancellation));
Assert.Empty(outside.Items);
await ExpectAsync(author.PostAsJsonAsync(path + "/status", new ChangeProposalStatusRequest("ACCEPTED", null), Cancellation),
HttpStatusCode.Forbidden);
await ExpectAsync(manager.PostAsJsonAsync(path + "/status", new ChangeProposalStatusRequest("REJECTED", " "), Cancellation),
HttpStatusCode.BadRequest);
await ExpectAsync(manager.PostAsJsonAsync(path + "/status", new ChangeProposalStatusRequest("IMPLEMENTED", null), Cancellation),
HttpStatusCode.Conflict);
var review = await ReadAsync<ProposalDetail>(manager.PostAsJsonAsync(path + "/status",
new ChangeProposalStatusRequest("UNDER_REVIEW", null), Cancellation));
Assert.Equal("UNDER_REVIEW", review.Status);
var accepted = await ReadAsync<ProposalDetail>(manager.PostAsJsonAsync(path + "/status",
new ChangeProposalStatusRequest("ACCEPTED", " Schváleno. "), Cancellation));
Assert.Equal(("ACCEPTED", "Schváleno."), (accepted.Status, accepted.Events[^1].Note));
await ExpectAsync(author.PutAsJsonAsync(path, edit, Cancellation), HttpStatusCode.Conflict);
await ExpectAsync(manager.DeleteAsync(path + "/vote", Cancellation), HttpStatusCode.Conflict);
var inbox = await ReadAsync<PagedResult<NotificationDto>>(author.GetAsync("/api/v1/notifications", Cancellation));
Assert.Equal(2, inbox.Items.Count(item => item.ProposalId == proposal.Id && item.Type == "PROPOSAL_STATUS_CHANGED"));
var top = Assert.Single(await ReadAsync<TopProposal[]>(
manager.GetAsync($"/api/v1/statistics/proposals/top?limit=1&from={from}&to={to}", Cancellation)));
Assert.Equal((proposal.Id, 1L), (top.Id, top.Score));
}
private static async Task VerifyVotesAsync(HttpClient author, HttpClient voter, string path)
{
var vote = path + "/vote";
await ExpectAsync(author.PutAsJsonAsync(vote, new VoteRequest(1), Cancellation), HttpStatusCode.Forbidden);
await ExpectAsync(voter.PutAsJsonAsync(vote, new VoteRequest(0), Cancellation), HttpStatusCode.BadRequest);
await ExpectAsync(voter.PutAsJsonAsync(vote, new VoteRequest(1), Cancellation), HttpStatusCode.NoContent);
var detail = await ReadAsync<ProposalDetail>(voter.GetAsync(path, Cancellation));
Assert.Equal((1L, 0L, 1L, (int?)1), (detail.VotesFor, detail.VotesAgainst, detail.Score, detail.MyVote));
await ExpectAsync(voter.PutAsJsonAsync(vote, new VoteRequest(-1), Cancellation), HttpStatusCode.NoContent);
detail = await ReadAsync<ProposalDetail>(voter.GetAsync(path, Cancellation));
Assert.Equal((0L, 1L, -1L, (int?)-1), (detail.VotesFor, detail.VotesAgainst, detail.Score, detail.MyVote));
await ExpectAsync(voter.PutAsJsonAsync(vote, new VoteRequest(-1), Cancellation), HttpStatusCode.NoContent);
await ExpectAsync(voter.DeleteAsync(vote, Cancellation), HttpStatusCode.NoContent);
detail = await ReadAsync<ProposalDetail>(voter.GetAsync(path, Cancellation));
Assert.Equal(0L, detail.Score);
Assert.Null(detail.MyVote);
await ExpectAsync(voter.PutAsJsonAsync(vote, new VoteRequest(1), Cancellation), HttpStatusCode.NoContent);
}
}