Skeleton contracts / contracts (pull_request) Canceled after 0s
Пароли хранятся как Argon2id, сессии переживают перезапуск базы.
163 lines
6.7 KiB
C#
163 lines
6.7 KiB
C#
using System.Net;
|
|
using Messenger;
|
|
using System.Net.Http.Headers;
|
|
using System.Runtime.CompilerServices;
|
|
using System.Text;
|
|
using System.Text.Json;
|
|
using Microsoft.AspNetCore.Mvc.Testing;
|
|
using Xunit;
|
|
|
|
namespace Messenger.Tests;
|
|
|
|
internal static class TestSetup
|
|
{
|
|
[ModuleInitializer]
|
|
internal static void Init()
|
|
{
|
|
Environment.SetEnvironmentVariable("MESSENGER_TESTING", "1");
|
|
if (string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("DATABASE_URL")))
|
|
throw new InvalidOperationException("Для тестов задайте DATABASE_URL.");
|
|
}
|
|
}
|
|
|
|
public sealed class MessengerFactory : WebApplicationFactory<Program>
|
|
{
|
|
}
|
|
|
|
public sealed class ApiTests : IClassFixture<MessengerFactory>
|
|
{
|
|
private readonly HttpClient _client;
|
|
|
|
public ApiTests(MessengerFactory factory) => _client = factory.CreateClient();
|
|
|
|
[Fact]
|
|
public async Task Wrong_password_basic_on_api_and_user_id_are_401()
|
|
{
|
|
var (id, username, password, token) = await Register();
|
|
var bad = Convert.ToBase64String(Encoding.UTF8.GetBytes(username + ":wrong-password-xx"));
|
|
var login = await Send(HttpMethod.Post, "/api/v1/auth/sessions", headers: new Dictionary<string, string>
|
|
{
|
|
["Authorization"] = "Basic " + bad
|
|
});
|
|
await Error(login, HttpStatusCode.Unauthorized, "unauthorized");
|
|
Assert.StartsWith("Basic", login.Headers.WwwAuthenticate.ToString(), StringComparison.OrdinalIgnoreCase);
|
|
|
|
var basicOnApi = await Send(HttpMethod.Get, "/api/v1/users/me", headers: new Dictionary<string, string>
|
|
{
|
|
["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(username + ":" + password))
|
|
});
|
|
await Error(basicOnApi, HttpStatusCode.Unauthorized, "unauthorized");
|
|
Assert.StartsWith("Bearer", basicOnApi.Headers.WwwAuthenticate.ToString(), StringComparison.OrdinalIgnoreCase);
|
|
|
|
var onlyUser = await Send(HttpMethod.Get, "/api/v1/users/me", headers: new Dictionary<string, string>
|
|
{
|
|
["X-User-Id"] = id
|
|
});
|
|
await Error(onlyUser, HttpStatusCode.Unauthorized, "unauthorized");
|
|
|
|
var me = await Json(await Send(HttpMethod.Get, "/api/v1/users/me", token: token, headers: new Dictionary<string, string>
|
|
{
|
|
["X-User-Id"] = Guid.NewGuid().ToString("D")
|
|
}));
|
|
Assert.Equal(id, me.GetProperty("id").GetString());
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Logout_revokes_the_current_token()
|
|
{
|
|
var (_, _, _, token) = await Register();
|
|
var gone = await Send(HttpMethod.Delete, "/api/v1/auth/sessions/current", token: token);
|
|
Assert.Equal(HttpStatusCode.NoContent, gone.StatusCode);
|
|
Assert.Equal("", await gone.Content.ReadAsStringAsync());
|
|
var again = await Send(HttpMethod.Get, "/api/v1/users/me", token: token);
|
|
await Error(again, HttpStatusCode.Unauthorized, "unauthorized");
|
|
}
|
|
|
|
[Fact]
|
|
public async Task Duplicate_username_is_409_and_empty_message_is_400()
|
|
{
|
|
var (id, username, password, _) = await Register();
|
|
var again = await Post("/api/v1/users", JsonSerializer.Serialize(new
|
|
{
|
|
username,
|
|
display_name = "Ещё",
|
|
password
|
|
}));
|
|
await Error(again, HttpStatusCode.Conflict, "conflict");
|
|
|
|
var (_, token) = await Login(username, password);
|
|
var chat = await Json(await Post("/api/v1/chats", JsonSerializer.Serialize(new
|
|
{
|
|
title = "Пусто",
|
|
member_ids = new[] { id }
|
|
}), token), HttpStatusCode.Created);
|
|
var empty = await Post($"/api/v1/chats/{chat.GetProperty("id").GetString()}/messages", """{"text":" "}""", token);
|
|
await Error(empty, HttpStatusCode.BadRequest, "invalid_request");
|
|
}
|
|
|
|
private async Task<(string Id, string Username, string Password, string Token)> Register()
|
|
{
|
|
var username = "u_" + Guid.NewGuid().ToString("N")[..12];
|
|
var password = "T3st-" + Guid.NewGuid().ToString("N");
|
|
var created = await Json(await Post("/api/v1/users", JsonSerializer.Serialize(new
|
|
{
|
|
username,
|
|
display_name = "Студент",
|
|
password
|
|
})), HttpStatusCode.Created);
|
|
var (id, token) = (created.GetProperty("id").GetString()!, (await Login(username, password)).Token);
|
|
return (id, username, password, token);
|
|
}
|
|
|
|
private async Task<(string Id, string Token)> Login(string username, string password)
|
|
{
|
|
var basic = Convert.ToBase64String(Encoding.UTF8.GetBytes(username + ":" + password));
|
|
var session = await Json(await Send(HttpMethod.Post, "/api/v1/auth/sessions", headers: new Dictionary<string, string>
|
|
{
|
|
["Authorization"] = "Basic " + basic
|
|
}), HttpStatusCode.Created);
|
|
return (session.GetProperty("user").GetProperty("id").GetString()!, session.GetProperty("token").GetString()!);
|
|
}
|
|
|
|
private Task<HttpResponseMessage> Post(string path, string json, string? token = null) =>
|
|
Send(HttpMethod.Post, path, json, token);
|
|
|
|
private async Task<HttpResponseMessage> Send(
|
|
HttpMethod method,
|
|
string path,
|
|
string? json = null,
|
|
string? token = null,
|
|
Dictionary<string, string>? headers = null)
|
|
{
|
|
var request = new HttpRequestMessage(method, path);
|
|
if (json is not null)
|
|
request.Content = new StringContent(json, Encoding.UTF8, "application/json");
|
|
if (token is not null)
|
|
request.Headers.TryAddWithoutValidation("Authorization", "Bearer " + token);
|
|
if (headers is not null)
|
|
{
|
|
foreach (var pair in headers)
|
|
request.Headers.TryAddWithoutValidation(pair.Key, pair.Value);
|
|
}
|
|
|
|
return await _client.SendAsync(request);
|
|
}
|
|
|
|
private static async Task<JsonElement> Json(HttpResponseMessage response, HttpStatusCode expected = HttpStatusCode.OK)
|
|
{
|
|
var body = await response.Content.ReadAsStringAsync();
|
|
Assert.Equal(expected, response.StatusCode);
|
|
Assert.True(response.Headers.TryGetValues("X-Request-Id", out var ids) && ids.Single().Length > 0);
|
|
Assert.Equal("application/json", MediaTypeHeaderValue.Parse(response.Content.Headers.ContentType!.ToString()).MediaType);
|
|
using var document = JsonDocument.Parse(body);
|
|
return document.RootElement.Clone();
|
|
}
|
|
|
|
private static async Task Error(HttpResponseMessage response, HttpStatusCode status, string code)
|
|
{
|
|
var document = await Json(response, status);
|
|
Assert.Equal(code, document.GetProperty("error").GetProperty("code").GetString());
|
|
Assert.Equal(response.Headers.GetValues("X-Request-Id").Single(), document.GetProperty("error").GetProperty("request_id").GetString());
|
|
}
|
|
}
|