From 32bc5a469171f9ca956beeff90c929b4667a8e6f Mon Sep 17 00:00:00 2001 From: GonnaHetzMe Date: Wed, 2 Dec 2026 23:56:26 +0100 Subject: [PATCH] backend: Expand backend integration test coverage --- .../AdministrationTests.cs | 98 +++++++++++++++ .../AttachmentTests.cs | 95 +++++++++++++++ .../Helpdesk.IntegrationTests/AuthTests.cs | 21 ++++ .../BackendFixture.cs | 38 +++++- .../DatabaseTests.cs | 19 +++ .../IssueWorkflowTests.cs | 39 ++++-- .../NotificationTests.cs | 112 ++++++++++++++++++ .../ProposalWorkflowTests.cs | 97 +++++++++++++++ 8 files changed, 500 insertions(+), 19 deletions(-) create mode 100644 backend/tests/Helpdesk.IntegrationTests/AdministrationTests.cs create mode 100644 backend/tests/Helpdesk.IntegrationTests/AttachmentTests.cs create mode 100644 backend/tests/Helpdesk.IntegrationTests/NotificationTests.cs create mode 100644 backend/tests/Helpdesk.IntegrationTests/ProposalWorkflowTests.cs diff --git a/backend/tests/Helpdesk.IntegrationTests/AdministrationTests.cs b/backend/tests/Helpdesk.IntegrationTests/AdministrationTests.cs new file mode 100644 index 0000000..e47d05d --- /dev/null +++ b/backend/tests/Helpdesk.IntegrationTests/AdministrationTests.cs @@ -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 +{ + [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(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(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(member.GetAsync(route + "?includeInactive=true", Cancellation)); + var all = await ReadAsync(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(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(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(admin.GetAsync(route, Cancellation)); + var all = await ReadAsync(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(member.PutAsJsonAsync(profile, + request with { Phone = "invalid" }, Cancellation), HttpStatusCode.BadRequest); + Assert.Contains("phone", validation.Errors.Keys); + var updated = await ReadAsync(member.PutAsJsonAsync(profile, request, Cancellation)); + Assert.Equal(updated, await ReadAsync(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(); + var encrypted = await db.Database.SqlQuery($"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>(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); + } +} diff --git a/backend/tests/Helpdesk.IntegrationTests/AttachmentTests.cs b/backend/tests/Helpdesk.IntegrationTests/AttachmentTests.cs new file mode 100644 index 0000000..d131fa9 --- /dev/null +++ b/backend/tests/Helpdesk.IntegrationTests/AttachmentTests.cs @@ -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 +{ + [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(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(); + var store = scope.ServiceProvider.GetRequiredService(); + try + { + var issue = await ReadAsync(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(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(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(""u8); + using (var document = zip.CreateEntry("word/document.xml").Open()) + document.Write(""u8); + } + return stream.ToArray(); + } +} diff --git a/backend/tests/Helpdesk.IntegrationTests/AuthTests.cs b/backend/tests/Helpdesk.IntegrationTests/AuthTests.cs index ac6aaab..4937a4f 100644 --- a/backend/tests/Helpdesk.IntegrationTests/AuthTests.cs +++ b/backend/tests/Helpdesk.IntegrationTests/AuthTests.cs @@ -12,6 +12,27 @@ namespace Helpdesk.IntegrationTests; public sealed class AuthTests(BackendFixture fixture) : IClassFixture { + [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(anonymous.PostAsJsonAsync("/api/v1/auth/login", + new LoginRequest(user.Email, newPassword), Cancellation)); + Assert.Equal(user.Id, session.User.Id); + } + [Fact] public async Task LogoutRevokesOnlyTheCurrentSession() { diff --git a/backend/tests/Helpdesk.IntegrationTests/BackendFixture.cs b/backend/tests/Helpdesk.IntegrationTests/BackendFixture.cs index d14b510..dd8f924 100644 --- a/backend/tests/Helpdesk.IntegrationTests/BackendFixture.cs +++ b/backend/tests/Helpdesk.IntegrationTests/BackendFixture.cs @@ -6,6 +6,7 @@ using System.Net.Http.Json; using System.Security.Cryptography; using Helpdesk.Application.Abstractions; using Helpdesk.Application.Auth; +using Helpdesk.Application.Common; using Helpdesk.Application.Users; using Helpdesk.Infrastructure.Persistence; using Microsoft.AspNetCore.Hosting; @@ -73,10 +74,23 @@ public sealed class BackendFixture : IAsyncLifetime var user = await ReadAsync(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); + new EmailTokenRequest(await email.TakeTokenAsync(address, "/confirm-email")), Cancellation), HttpStatusCode.NoContent); return user; } + internal async Task 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 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 LoginAsync(HttpClient client, string address) => ReadAsync(client.PostAsJsonAsync("/api/v1/auth/login", new LoginRequest(address, Password), Cancellation)); @@ -160,20 +174,32 @@ public sealed class BackendFixture : IAsyncLifetime private sealed class TestEmailSender : IEmailSender { - private readonly ConcurrentDictionary tokens = new(); + private readonly ConcurrentDictionary<(string Address, string Path), TaskCompletionSource> tokens = new(); + internal ConcurrentDictionary Failures { get; } = new(); 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) && - link.AbsolutePath == "/confirm-email") - tokens[to] = QueryHelpers.ParseQuery(link.Query)["token"].ToString(); + link.AbsolutePath is "/confirm-email" or "/reset-password") + { + var token = QueryHelpers.ParseQuery(link.Query)["token"].ToString(); + GetTokenSlot((to, link.AbsolutePath)).TrySetResult(token); + } return Task.CompletedTask; } - internal string TakeConfirmationToken(string address) + internal async Task 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; } + + private TaskCompletionSource GetTokenSlot((string Address, string Path) key) => + tokens.GetOrAdd(key, _ => new(TaskCreationOptions.RunContinuationsAsynchronously)); } } diff --git a/backend/tests/Helpdesk.IntegrationTests/DatabaseTests.cs b/backend/tests/Helpdesk.IntegrationTests/DatabaseTests.cs index 3a985e5..1f5ca4f 100644 --- a/backend/tests/Helpdesk.IntegrationTests/DatabaseTests.cs +++ b/backend/tests/Helpdesk.IntegrationTests/DatabaseTests.cs @@ -1,4 +1,5 @@ using Helpdesk.Api.Controllers; +using System.Text.Json; using Helpdesk.Infrastructure.Persistence; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; @@ -42,6 +43,24 @@ public sealed class DatabaseTests(BackendFixture fixture) : IClassFixture(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] public async Task DatabaseRejectsAnAssignedIssueWithoutAnAssignee() { diff --git a/backend/tests/Helpdesk.IntegrationTests/IssueWorkflowTests.cs b/backend/tests/Helpdesk.IntegrationTests/IssueWorkflowTests.cs index 8d446af..8721b28 100644 --- a/backend/tests/Helpdesk.IntegrationTests/IssueWorkflowTests.cs +++ b/backend/tests/Helpdesk.IntegrationTests/IssueWorkflowTests.cs @@ -1,12 +1,10 @@ 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; @@ -20,9 +18,9 @@ public sealed class IssueWorkflowTests(BackendFixture fixture) : IClassFixture(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); await ExpectAsync(reporter.PostAsJsonAsync(path + "/assign", assign, Cancellation), HttpStatusCode.Forbidden); issue = await PostIssueAsync(manager, path + "/assign", assign); @@ -63,6 +65,10 @@ public sealed class IssueWorkflowTests(BackendFixture fixture) : IClassFixture(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 + "/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)); Assert.Equal("RESOLVED", issue.Status); var events = await ReadAsync(reporter.GetAsync(path + "/events", Cancellation)); @@ -72,14 +78,9 @@ public sealed class IssueWorkflowTests(BackendFixture fixture) : IClassFixture 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); + var rejected = await PostIssueAsync(manager, $"/api/v1/issues/{openIssue.Id}/reject", + new IssueReasonRequest(openIssue.RowVersion, "Duplicitní hlášení.")); + Assert.Equal("REJECTED", rejected.Status); } private static async Task VerifyReadsAsync(HttpClient reporter, HttpClient manager, IssueDetail resolved, IssueDetail open) @@ -105,6 +106,18 @@ public sealed class IssueWorkflowTests(BackendFixture fixture) : IClassFixture( + 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( + 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( + 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(manager.GetAsync("/api/v1/users/assignable", Cancellation)); + Assert.Contains(available, user => user.Id == resolved.AssigneeId && user.OpenIssues == 0); var trend = await ReadAsync(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)); diff --git a/backend/tests/Helpdesk.IntegrationTests/NotificationTests.cs b/backend/tests/Helpdesk.IntegrationTests/NotificationTests.cs new file mode 100644 index 0000000..e671f5e --- /dev/null +++ b/backend/tests/Helpdesk.IntegrationTests/NotificationTests.cs @@ -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 +{ + [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(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(reporter.PostAsJsonAsync("/api/v1/issues", request, Cancellation), HttpStatusCode.Created); + var notifications = await ReadAsync>(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(manager.GetAsync(inbox + "/unread-count", Cancellation))).Count); + + fixture.FailNextEmail(managerSession.User.Email, "TEST_TEMPORARY_FAILURE", retryable: true); + var secondIssue = await ReadAsync(reporter.PostAsJsonAsync("/api/v1/issues", request, Cancellation), HttpStatusCode.Created); + notifications = await ReadAsync>(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>(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(); + 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 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>(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}."); + } +} diff --git a/backend/tests/Helpdesk.IntegrationTests/ProposalWorkflowTests.cs b/backend/tests/Helpdesk.IntegrationTests/ProposalWorkflowTests.cs new file mode 100644 index 0000000..2fe0d40 --- /dev/null +++ b/backend/tests/Helpdesk.IntegrationTests/ProposalWorkflowTests.cs @@ -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 +{ + 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(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(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(author.PutAsJsonAsync(path, edit, Cancellation)); + Assert.Equal((edit.CategoryId, edit.Description, "UPDATED"), (proposal.CategoryId, proposal.Description, proposal.Events[^1].EventType)); + var other = await ReadAsync(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>(manager.GetAsync(filter + "&sort=score&pageSize=1", Cancellation)); + var second = await ReadAsync>(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>(manager.GetAsync(filter, Cancellation)); + Assert.Equal(other.Id, newest.Items[0].Id); + var outside = await ReadAsync>(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(manager.PostAsJsonAsync(path + "/status", + new ChangeProposalStatusRequest("UNDER_REVIEW", null), Cancellation)); + Assert.Equal("UNDER_REVIEW", review.Status); + var accepted = await ReadAsync(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>(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( + 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(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(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(voter.GetAsync(path, Cancellation)); + Assert.Equal(0L, detail.Score); + Assert.Null(detail.MyVote); + await ExpectAsync(voter.PutAsJsonAsync(vote, new VoteRequest(1), Cancellation), HttpStatusCode.NoContent); + } +}