Files
NTBug/backend/tests/Helpdesk.IntegrationTests/NotificationTests.cs
T

113 lines
7.3 KiB
C#

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}.");
}
}