web: unit testy přihlášení, obnovy tokenů a zpracování chyb API
Sloučení souběžných obnov tokenu, uložení tokenů v cookie, čtení ProblemDetails, přenos chyb API do formulářů a viditelnost menu podle role. Refs #21
This commit is contained in:
1 parent
36f1078b0a
commit
08ca55dd6b
5 files changed
+286
No files matched your search
@@ -0,0 +1,142 @@
|
||||
using System.Net;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using Helpdesk.Web.Api;
|
||||
using Helpdesk.Web.Auth;
|
||||
using Helpdesk.Web.Infrastructure;
|
||||
using Helpdesk.Web.Models;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Mvc.ModelBinding;
|
||||
|
||||
namespace Helpdesk.Web.Tests;
|
||||
|
||||
public class AuthCookieTests
|
||||
{
|
||||
private static readonly TokenSet Tokens = new(
|
||||
"access", new DateTimeOffset(2026, 12, 1, 10, 15, 0, TimeSpan.Zero),
|
||||
"refresh", new DateTimeOffset(2026, 12, 15, 10, 0, 0, TimeSpan.Zero));
|
||||
|
||||
[Fact]
|
||||
public void Tokeny_ulozene_v_cookie_se_prectou_zpet()
|
||||
{
|
||||
var properties = new AuthenticationProperties();
|
||||
AuthCookie.StoreTokens(properties, Tokens);
|
||||
|
||||
Assert.Equal(Tokens, AuthCookie.ReadTokens(properties));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Trvale_prihlaseni_plati_stejne_dlouho_jako_refresh_token()
|
||||
{
|
||||
var properties = new AuthenticationProperties { IsPersistent = true };
|
||||
AuthCookie.StoreTokens(properties, Tokens);
|
||||
|
||||
Assert.Equal(Tokens.RefreshTokenExpiresAt, properties.ExpiresUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Cookie_bez_tokenu_neni_platna() => Assert.Null(AuthCookie.ReadTokens(new AuthenticationProperties()));
|
||||
|
||||
[Fact]
|
||||
public void Identita_nese_roli_pro_IsInRole()
|
||||
{
|
||||
var principal = AuthCookie.CreatePrincipal(new UserDto(7, "[email protected]", "Eva", "Malá", null, UserRoles.Management, true));
|
||||
|
||||
Assert.True(principal.IsInRole(UserRoles.Management));
|
||||
Assert.Equal("Eva Malá", principal.Identity!.Name);
|
||||
Assert.Equal("7", principal.FindFirst(ClaimTypes.NameIdentifier)!.Value);
|
||||
}
|
||||
}
|
||||
|
||||
public class ApiExceptionTests
|
||||
{
|
||||
private static HttpResponseMessage Problem(HttpStatusCode status, string json) => new(status)
|
||||
{
|
||||
Content = new StringContent(json, Encoding.UTF8, "application/problem+json"),
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public async Task Validacni_chyby_z_ProblemDetails_se_nactou_podle_poli()
|
||||
{
|
||||
using var response = Problem(HttpStatusCode.BadRequest,
|
||||
"""{"title":"Neplatná vstupní data.","status":400,"errors":{"password":["Heslo je příliš krátké."]}}""");
|
||||
|
||||
var error = await ApiException.FromResponseAsync(response, CancellationToken.None);
|
||||
|
||||
Assert.Equal(HttpStatusCode.BadRequest, error.StatusCode);
|
||||
Assert.Equal("Neplatná vstupní data.", error.UserMessage);
|
||||
Assert.Equal(["Heslo je příliš krátké."], error.Errors["Password"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Odpoved_bez_tela_ma_srozumitelnou_zpravu()
|
||||
{
|
||||
using var response = new HttpResponseMessage(HttpStatusCode.TooManyRequests);
|
||||
|
||||
var error = await ApiException.FromResponseAsync(response, CancellationToken.None);
|
||||
|
||||
Assert.Equal("Příliš mnoho pokusů. Zkuste to prosím za minutu.", error.UserMessage);
|
||||
Assert.Empty(error.Errors);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Poskozeny_JSON_nezpusobi_vyjimku()
|
||||
{
|
||||
using var response = Problem(HttpStatusCode.InternalServerError, "{nejde o json");
|
||||
|
||||
var error = await ApiException.FromResponseAsync(response, CancellationToken.None);
|
||||
|
||||
Assert.Equal(HttpStatusCode.InternalServerError, error.StatusCode);
|
||||
Assert.Null(error.Title);
|
||||
}
|
||||
}
|
||||
|
||||
public class ModelStateExtensionsTests
|
||||
{
|
||||
[Fact]
|
||||
public void Chyba_pole_z_API_patri_k_vlastnosti_formulare()
|
||||
{
|
||||
var modelState = new ModelStateDictionary();
|
||||
var error = new ApiException(HttpStatusCode.BadRequest, "Neplatná vstupní data.",
|
||||
new Dictionary<string, string[]> { ["newPassword"] = ["Heslo musí mít alespoň 8 znaků."] });
|
||||
|
||||
modelState.AddApiErrors(error, typeof(ResetPasswordViewModel));
|
||||
|
||||
Assert.Equal("Heslo musí mít alespoň 8 znaků.", modelState[nameof(ResetPasswordViewModel.NewPassword)]!.Errors.Single().ErrorMessage);
|
||||
Assert.False(modelState.ContainsKey(string.Empty));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Chyba_bez_pole_jde_do_souhrnu()
|
||||
{
|
||||
var modelState = new ModelStateDictionary();
|
||||
var error = new ApiException(HttpStatusCode.Conflict, "Účet s tímto e-mailem už existuje.", new Dictionary<string, string[]>());
|
||||
|
||||
modelState.AddApiErrors(error, typeof(RegisterViewModel));
|
||||
|
||||
Assert.Equal("Účet s tímto e-mailem už existuje.", modelState[string.Empty]!.Errors.Single().ErrorMessage);
|
||||
}
|
||||
}
|
||||
|
||||
public class NavigationTests
|
||||
{
|
||||
private static ClaimsPrincipal UserWithRole(string role) =>
|
||||
new(new ClaimsIdentity([new Claim(ClaimTypes.Role, role)], "test"));
|
||||
|
||||
[Fact]
|
||||
public void Neprihlaseny_uzivatel_menu_nevidi() =>
|
||||
Assert.Empty(Navigation.For(new ClaimsPrincipal(new ClaimsIdentity())));
|
||||
|
||||
[Fact]
|
||||
public void Polozka_s_roli_je_videt_jen_te_roli()
|
||||
{
|
||||
var item = new NavItem("Statistiky", "Statistics", "Index", UserRoles.Management);
|
||||
|
||||
Assert.True(item.IsVisibleTo(UserWithRole(UserRoles.Management)));
|
||||
Assert.False(item.IsVisibleTo(UserWithRole(UserRoles.Student)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Polozka_bez_roli_je_videt_vsem_prihlasenym() =>
|
||||
Assert.True(new NavItem("Nástěnka", "Home", "Index").IsVisibleTo(UserWithRole(UserRoles.Student)));
|
||||
}
|
||||
Reference in new issue
Block a user