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 = CreateClient(SmsApiFactory.Login, SmsApiFactory.Password); } public void Dispose() { _client.Dispose(); _factory.Dispose(); _gateway.Dispose(); } [Fact] public async Task Health_WithoutAnyConfiguration_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_WithoutCredentials_Returns401WithoutGatewayCall() { using var anonymous = _factory.CreateClient(); var response = await anonymous.GetAsync(new Uri("/v1/account/credit", UriKind.Relative)); Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); Assert.Equal("missing_credentials", (await ReadJson(response)).GetProperty("code").GetString()); Assert.Empty(_gateway.Requests); } [Fact] public async Task SendMessage_Success_ForwardsCallerCredentialsAndXml() { _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.Equal("/apixml30/receiver", uri.AbsolutePath); Assert.Contains("login=" + SmsApiFactory.Login, uri.Query, StringComparison.Ordinal); Assert.Contains("password=" + SmsApiFactory.Password, 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 RejectedCredentials_AreNotSentAgain_OtherCredentialsStillWork() { _gateway.Enqueue("401Chybne prihlaseni"); _gateway.Enqueue("1111"); using var other = CreateClient("cms-login", "cms-password"); var first = await _client.GetAsync(new Uri("/v1/account/credit", UriKind.Relative)); var second = await _client.GetAsync(new Uri("/v1/account/credit", UriKind.Relative)); var otherApp = await other.GetAsync(new Uri("/v1/account/credit", UriKind.Relative)); Assert.Equal(HttpStatusCode.Unauthorized, first.StatusCode); Assert.Equal("invalid_credentials", (await ReadJson(first)).GetProperty("code").GetString()); Assert.Equal(HttpStatusCode.Unauthorized, second.StatusCode); Assert.Equal(HttpStatusCode.OK, otherApp.StatusCode); Assert.Equal(2, _gateway.Requests.Count); Assert.Contains("login=cms-login", _gateway.Requests[1].Uri.Query, StringComparison.Ordinal); } [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_DescribesCredentialHeadersAndRelativeServer() { var json = await ReadJson(await _client.GetAsync(new Uri("/openapi/v1.json", UriKind.Relative))); Assert.Equal("..", json.GetProperty("servers")[0].GetProperty("url").GetString()); var schemes = json.GetProperty("components").GetProperty("securitySchemes"); Assert.Equal("X-Sms-Login", schemes.GetProperty("SmsLogin").GetProperty("name").GetString()); Assert.Equal("X-Sms-Password", schemes.GetProperty("SmsPassword").GetProperty("name").GetString()); var requirement = json.GetProperty("paths").GetProperty("/v1/messages").GetProperty("post").GetProperty("security")[0]; Assert.True(requirement.TryGetProperty("SmsLogin", out _)); Assert.True(requirement.TryGetProperty("SmsPassword", 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 HttpClient CreateClient(string login, string password) { var client = _factory.CreateClient(); client.DefaultRequestHeaders.Add("X-Sms-Login", login); client.DefaultRequestHeaders.Add("X-Sms-Password", password); return client; } private static async Task ReadJson(HttpResponseMessage response) => JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement.Clone(); }