using System.Net; using System.Net.Http.Json; using System.Text.Json; using System.Xml.Linq; using Microsoft.AspNetCore.Mvc.Testing; namespace SmsSluzba.Api.Tests.Api; public sealed class ApiTests : IDisposable { private const string SendSuccessXml = """ 420603123456-20261020120000123 Test 20261020120000 +420603123456 1 0.68 453.49 """; private readonly FakeGatewayHandler _gateway = new(); private readonly SmsApiFactory _factory; private readonly HttpClient _client; public ApiTests() { _factory = new SmsApiFactory(_gateway); _client = _factory.CreateClient(); _client.DefaultRequestHeaders.Add("X-Api-Key", SmsApiFactory.ApiKey); } public void Dispose() { _client.Dispose(); _factory.Dispose(); _gateway.Dispose(); } [Fact] public async Task Health_WithoutApiKey_ReturnsOk() { using var anonymous = _factory.CreateClient(); var response = await anonymous.GetAsync(new Uri("/health", UriKind.Relative)); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Empty(_gateway.Requests); } [Fact] public async Task V1_WithWrongApiKey_Returns401WithCode() { using var anonymous = _factory.CreateClient(); anonymous.DefaultRequestHeaders.Add("X-Api-Key", "wrong"); var response = await anonymous.GetAsync(new Uri("/v1/account/credit", UriKind.Relative)); Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); Assert.Equal("unauthorized", (await ReadJson(response)).GetProperty("code").GetString()); Assert.Empty(_gateway.Requests); } [Fact] public async Task SendMessage_Success_ReturnsGatewayResultAndSendsXml() { _gateway.Enqueue(SendSuccessXml); var response = await _client.PostAsJsonAsync("/v1/messages", new { to = "+420603123456", text = "Test & co", deliveryReport = true }); Assert.Equal(HttpStatusCode.OK, response.StatusCode); var json = await ReadJson(response); Assert.Equal("420603123456-20261020120000123", json.GetProperty("id").GetString()); Assert.Equal(1, json.GetProperty("parts").GetInt32()); Assert.Equal(0.68m, json.GetProperty("price").GetDecimal()); Assert.Equal(453.49m, json.GetProperty("credit").GetDecimal()); var (uri, body) = Assert.Single(_gateway.Requests); Assert.EndsWith("/apixml30/receiver", uri.AbsolutePath, StringComparison.Ordinal); Assert.Contains("password=" + SmsApiFactory.GatewayPassword, uri.Query, StringComparison.Ordinal); var sent = XDocument.Parse(body!).Root!; Assert.Equal("Test & co", sent.Element("text")?.Value); Assert.Equal("20", sent.Element("dr_request")?.Value); } [Fact] public async Task SendMessage_InvalidRecipient_Returns400WithProviderCode() { _gateway.Enqueue("400;1Chybne telefonni cislo 77716085"); var response = await _client.PostAsJsonAsync("/v1/messages", new { to = "77716085", text = "Test" }); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); var json = await ReadJson(response); Assert.Equal("invalid_recipient", json.GetProperty("code").GetString()); Assert.Equal("400;1", json.GetProperty("providerCode").GetString()); } [Fact] public async Task SendMessage_TextTooLong_DoesNotCallGateway() { var response = await _client.PostAsJsonAsync("/v1/messages", new { to = "+420603123456", text = new string('a', 460) }); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); Assert.Equal("text_too_long", (await ReadJson(response)).GetProperty("code").GetString()); Assert.Empty(_gateway.Requests); } [Fact] public async Task SendMessage_InvalidJson_Returns400WithCode() { using var content = new StringContent("{not json", System.Text.Encoding.UTF8, "application/json"); var response = await _client.PostAsync(new Uri("/v1/messages", UriKind.Relative), content); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); Assert.Equal("validation_failed", (await ReadJson(response)).GetProperty("code").GetString()); } [Fact] public async Task SendMessage_Timeout_Returns504() { _gateway.EnqueueException(new TaskCanceledException("timeout", new TimeoutException())); var response = await _client.PostAsJsonAsync("/v1/messages", new { to = "+420603123456", text = "Test" }); Assert.Equal(HttpStatusCode.GatewayTimeout, response.StatusCode); Assert.Equal("provider_timeout", (await ReadJson(response)).GetProperty("code").GetString()); } [Fact] public async Task AuthFailure_StopsAllFurtherGatewayCalls() { _gateway.Enqueue("401Chybne prihlaseni"); var first = await _client.PostAsJsonAsync("/v1/messages", new { to = "+420603123456", text = "Test" }); var second = await _client.GetAsync(new Uri("/v1/account/credit", UriKind.Relative)); var health = await ReadJson(await _client.GetAsync(new Uri("/health", UriKind.Relative))); Assert.Equal(HttpStatusCode.ServiceUnavailable, first.StatusCode); Assert.Equal(HttpStatusCode.ServiceUnavailable, second.StatusCode); Assert.Equal("provider_auth_blocked", (await ReadJson(second)).GetProperty("code").GetString()); Assert.Equal("blocked", health.GetProperty("gateway").GetString()); Assert.Single(_gateway.Requests); } [Fact] public async Task GetEvents_ReturnsTypedEventsAndQueriesGateway() { _gateway.Enqueue(""" answer_messagein-2ANOout-1+4207771234565517 delivery_reportout-10Doručeno """); var response = await _client.GetAsync(new Uri("/v1/events?count=10", UriKind.Relative)); Assert.Equal(HttpStatusCode.OK, response.StatusCode); var events = (await ReadJson(response)).GetProperty("events"); Assert.Equal("answer", events[0].GetProperty("type").GetString()); Assert.Equal("out-1", events[0].GetProperty("inReplyTo").GetString()); Assert.Equal("deliveryReport", events[1].GetProperty("type").GetString()); Assert.Equal("out-1", events[1].GetProperty("messageId").GetString()); var query = Assert.Single(_gateway.Requests).Uri.Query; Assert.Contains("query_incoming=1", query, StringComparison.Ordinal); Assert.Contains("query_delivery_report=1", query, StringComparison.Ordinal); Assert.DoesNotContain("query_outgoing", query, StringComparison.Ordinal); Assert.Contains("count=10", query, StringComparison.Ordinal); } [Fact] public async Task ConfirmEvents_MapsTypesAndReportsFailures() { _gateway.Enqueue("200OK"); _gateway.Enqueue("503Chyba brany"); var response = await _client.PostAsJsonAsync("/v1/events/confirm", new { events = new[] { new { type = "answer", id = "in-2" }, new { type = "deliveryReport", id = "out-1" }, }, }); Assert.Equal(HttpStatusCode.OK, response.StatusCode); var json = await ReadJson(response); Assert.Equal("in-2", json.GetProperty("confirmed")[0].GetProperty("id").GetString()); Assert.Equal("provider_unavailable", json.GetProperty("failed")[0].GetProperty("code").GetString()); Assert.Contains("type=incoming_message", _gateway.Requests[0].Uri.Query, StringComparison.Ordinal); Assert.Contains("type=delivery_report", _gateway.Requests[1].Uri.Query, StringComparison.Ordinal); } [Fact] public async Task ConfirmEvents_UnknownType_Returns400WithoutGatewayCall() { var response = await _client.PostAsJsonAsync("/v1/events/confirm", new { events = new[] { new { type = "sms", id = "1" } } }); Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode); Assert.Empty(_gateway.Requests); } [Fact] public async Task DeliveryReport_NotAvailable_Returns404() { _gateway.Enqueue(""); var response = await _client.GetAsync(new Uri("/v1/messages/out-1/delivery-report", UriKind.Relative)); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); Assert.Equal("delivery_report_not_found", (await ReadJson(response)).GetProperty("code").GetString()); Assert.Contains("act=get_delivery_report", Assert.Single(_gateway.Requests).Uri.Query, StringComparison.Ordinal); } [Fact] public async Task OpenApi_DescribesApiKeyAndRelativeServer() { var json = await ReadJson(await _client.GetAsync(new Uri("/openapi/v1.json", UriKind.Relative))); Assert.Equal("/", json.GetProperty("servers")[0].GetProperty("url").GetString()); var scheme = json.GetProperty("components").GetProperty("securitySchemes").GetProperty("ApiKey"); Assert.Equal("X-Api-Key", scheme.GetProperty("name").GetString()); var send = json.GetProperty("paths").GetProperty("/v1/messages").GetProperty("post"); Assert.True(send.GetProperty("security")[0].TryGetProperty("ApiKey", out _)); } [Fact] public async Task Docs_RedirectsRelatively() { using var client = _factory.CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false }); var response = await client.GetAsync(new Uri("/docs", UriKind.Relative)); Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); Assert.Equal("docs/index.html", response.Headers.Location?.OriginalString); } private static async Task ReadJson(HttpResponseMessage response) => JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement.Clone(); }