Služba padala při startu kvůli povinným SMSSLUZBA_LOGIN, SMSSLUZBA_PASSWORD a API_KEYS, proto v AppFactory nefungovalo /health ani /docs (502). - vlastní API klíče služby zrušeny, login a heslo API přístupu SMS-Služby posílá každá aplikace v hlavičkách X-Sms-Login a X-Sms-Password - všechna konfigurace je volitelná, neplatná hodnota jen zaloguje varování - po odmítnutí přihlášení se blokují jen ty konkrétní údaje - Swagger: Authorize pro obě hlavičky, relativní server i bez ROOT_PATH - návod pro napojení aplikací a dokumentace podle nového přihlášení
258 lines
11 KiB
C#
258 lines
11 KiB
C#
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 = """
|
|
<messages>
|
|
<message>
|
|
<id>420603123456-20261020120000123</id>
|
|
<text>Test</text>
|
|
<send_at>20261020120000</send_at>
|
|
<recipient>+420603123456</recipient>
|
|
<parts>1</parts>
|
|
<price>0.68</price>
|
|
</message>
|
|
<credit>453.49</credit>
|
|
</messages>
|
|
""";
|
|
|
|
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("<status><id>400;1</id><message>Chybne telefonni cislo 77716085</message></status>");
|
|
|
|
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("<status><id>401</id><message>Chybne prihlaseni</message></status>");
|
|
_gateway.Enqueue("<info><credit>1</credit><price_cz_sms>1</price_cz_sms><price_sk_sms>1</price_sk_sms><price_other_sms>1</price_other_sms></info>");
|
|
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("""
|
|
<messages>
|
|
<message><type>answer_message</type><id>in-2</id><text>ANO</text><in_reply_to>out-1</in_reply_to><sender>+420777123456</sender><recipient>5517</recipient></message>
|
|
<message><type>delivery_report</type><id>out-1</id><status>0</status><description>Doručeno</description></message>
|
|
</messages>
|
|
""");
|
|
|
|
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("<status><id>200</id><message>OK</message></status>");
|
|
_gateway.Enqueue("<status><id>503</id><message>Chyba brany</message></status>");
|
|
|
|
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("<messages />");
|
|
|
|
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<JsonElement> ReadJson(HttpResponseMessage response) =>
|
|
JsonDocument.Parse(await response.Content.ReadAsStringAsync()).RootElement.Clone();
|
|
}
|