Commit 2637feb7 authored by Andreas Müller's avatar Andreas Müller
Browse files

Added UnitTests, fixed small issues.

parent f98f5f83
using System;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using AMWD.Net.Api.Divera.Requests;
using AMWD.Net.Api.Divera.Responses;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using Moq.Protected;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace AMWD.Net.Api.Divera.Test
{
[TestClass]
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
public class CloseAlarmTests : TestBase
{
private static readonly string jsonMimeType = "application/json";
private static readonly DateTime date = new DateTime(2022, 1, 9, 1, 2, 3, DateTimeKind.Utc);
[TestMethod]
public async Task ShouldMapFullRequest()
{
// arrange
string accessKey = "abc";
string responseJson = JsonConvert.SerializeObject(new SuccessResponse { IsSuccessful = true });
httpResponseMessage.Content = new StringContent(responseJson, Encoding.UTF8, jsonMimeType);
var request = new CloseAlarmRequest
{
Id = 123,
IsClosed = true,
Report = "That was nice",
Timestamp = date
};
var api = GetApi(accessKey);
// act
bool response = await api.CloseAlarm(request);
var callbackJson = JsonConvert.DeserializeObject<JObject>(requestCallback);
// assert
Assert.AreEqual($"{DiveraApiUrls.AlarmClose}?accesskey={accessKey}", requestCallbackUrl);
Assert.IsNotNull(requestCallback);
Assert.IsTrue(response);
Assert.AreEqual(request.Id, callbackJson["id"]);
Assert.AreEqual(request.IsClosed, callbackJson["closed"].Value<bool>());
Assert.AreEqual(request.Report, callbackJson["report"]);
Assert.AreEqual(request.TimestampUnix, callbackJson["ts"]);
httpMessageHandlerMock.Protected().Verify("SendAsync", Times.Exactly(1), ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>());
}
[TestMethod]
public async Task ShouldThrowExceptionOnMissingRequest()
{
// arrange
string accessKey = "abc";
string responseJson = JsonConvert.SerializeObject(new SuccessResponse { IsSuccessful = true });
httpResponseMessage.Content = new StringContent(responseJson, Encoding.UTF8, jsonMimeType);
var api = GetApi(accessKey);
// act + assert
try
{
bool response = await api.CloseAlarm(null);
Assert.Fail();
}
catch (ArgumentNullException)
{ /* expected behaviour */ }
httpMessageHandlerMock.Protected().Verify("SendAsync", Times.Exactly(0), ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>());
}
[TestMethod]
public async Task ShouldThrowExceptionOnMissingId()
{
// arrange
string accessKey = "abc";
string responseJson = JsonConvert.SerializeObject(new SuccessResponse { IsSuccessful = true });
httpResponseMessage.Content = new StringContent(responseJson, Encoding.UTF8, jsonMimeType);
var request = new CloseAlarmRequest();
var api = GetApi(accessKey);
// act + assert
try
{
bool response = await api.CloseAlarm(request);
Assert.Fail();
}
catch (ArgumentNullException)
{ /* expected behaviour */ }
httpMessageHandlerMock.Protected().Verify("SendAsync", Times.Exactly(0), ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>());
}
[TestMethod]
public async Task ShouldThrowExceptionOnInvalidAccessKey()
{
// arrange
string accessKey = "abc";
httpResponseMessage.StatusCode = HttpStatusCode.Forbidden;
var request = new CloseAlarmRequest { Id = 123 };
var api = GetApi(accessKey);
// act + assert
try
{
bool response = await api.CloseAlarm(request);
Assert.Fail();
}
catch (AccessKeyException)
{ /* expected behaviour */ }
httpMessageHandlerMock.Protected().Verify("SendAsync", Times.Exactly(1), ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>());
}
[TestMethod]
public async Task ShouldReturnFalseOnHttpError()
{
// arrange
string accessKey = "abc";
httpResponseMessage.StatusCode = HttpStatusCode.InternalServerError;
var request = new CloseAlarmRequest { Id = 123 };
var api = GetApi(accessKey);
// act
bool response = await api.CloseAlarm(request);
// assert
Assert.AreEqual($"{DiveraApiUrls.AlarmClose}?accesskey={accessKey}", requestCallbackUrl);
Assert.IsNotNull(requestCallback);
Assert.IsFalse(response);
httpMessageHandlerMock.Protected().Verify("SendAsync", Times.Exactly(1), ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>());
}
[TestMethod]
public async Task ShouldReturnFalseOnDiveraError()
{
// arrange
string accessKey = "abc";
string responseJson = JsonConvert.SerializeObject(new SuccessResponse { IsSuccessful = false });
httpResponseMessage.Content = new StringContent(responseJson, Encoding.UTF8, jsonMimeType);
var request = new CloseAlarmRequest { Id = 123 };
var api = GetApi(accessKey);
// act
bool response = await api.CloseAlarm(request);
// assert
Assert.AreEqual($"{DiveraApiUrls.AlarmClose}?accesskey={accessKey}", requestCallbackUrl);
Assert.IsNotNull(requestCallback);
Assert.IsFalse(response);
httpMessageHandlerMock.Protected().Verify("SendAsync", Times.Exactly(1), ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>());
}
}
}
using System;
using System.Threading.Tasks;
using AMWD.Net.Api.Divera.Requests;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace AMWD.Net.Api.Divera.Test
{
[TestClass]
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
public class ConstructorTests : TestBase
{
[TestMethod]
public void ShouldCreateDefault()
{
// arrange
// act
using var api = new DiveraApi();
// assert
Assert.IsNotNull(api);
}
[TestMethod]
public async Task ShouldThrowExceptionOnDisposed()
{
// arrange
var request = new CloseAlarmRequest
{
Id = 123,
Report = "Foo Bar"
};
var api = new DiveraApi();
// act
api.Dispose();
// assert
try
{
await api.CloseAlarm(request);
Assert.Fail();
}
catch (ObjectDisposedException)
{ /* expected behaviour */ }
}
[TestMethod]
public async Task ShouldThrowExceptionOnMissingAccessKey()
{
// arrange
var request = new CloseAlarmRequest
{
Id = 123,
Report = "Foo Bar"
};
using var api = new DiveraApi();
// act + assert
try
{
await api.CloseAlarm(request);
Assert.Fail();
}
catch (AccessKeyException)
{ /* expected behaviour */ }
}
}
}
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using AMWD.Net.Api.Divera.Requests;
using AMWD.Net.Api.Divera.Responses;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using Moq.Protected;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace AMWD.Net.Api.Divera.Test
{
[TestClass]
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
public class CreateAlarmTests : TestBase
{
private static readonly string jsonMimeType = "application/json";
[TestMethod]
public async Task ShouldMapFullRequest()
{
// arrange
string accessKey = "abc";
string responseJson = JsonConvert.SerializeObject(new SuccessResponse { IsSuccessful = true });
httpResponseMessage.Content = new StringContent(responseJson, Encoding.UTF8, jsonMimeType);
var request = new CreateAlarmRequest
{
Number = "47123",
Title = "Probealarm",
HasPriority = true,
Text = "Achtung! Dies ist ein Probealarm",
Address = "Dorfstr. 15b, 89001 Musterstadt",
Latitude = 49.12345f,
Longitude = 11.12345f,
SceneObject = "Haus",
Caller = "Max Mustermann, +4917100001",
Patient = "Maria Musterfrau",
Remark = "Zugang nur über Dachluke",
Units = "RTW, DLK",
HasDestination = true,
DestinationAddress = "Hospitalstraße 1, 89001 Musterhausen",
DestinationLatitude = 48.12345f,
DestinationLongitude = 10.12345f,
AdditionalText1 = "Erster Zusatz",
AdditionalText2 = "Zweiter Zusatz",
AdditionalText3 = "Dritter Zusatz",
Rics = new List<string> { "RTW", "DLK" },
Vehicles = new List<string> { "RTW1", "DLK2" },
Persons = new List<string> { "EFD" },
DelaySeconds = 15,
Coordinates = "gk",
CoordinatesX = 12.3456f,
CoordinatesY = 65.4321f,
IsNews = false,
Id = 123,
ClusterIds = new List<string> { "c1", "c2" },
GroupIds = new List<string> { "g1" },
UserClusterRelationIds = new List<string> { "c1g1", "c2g1" },
VehicleIds = new List<string> { "v1", "v2" },
AlarmcodeId = new List<string> { "t2" }
};
var api = GetApi(accessKey);
// act
bool response = await api.CreateAlarm(request);
var callbackJson = JsonConvert.DeserializeObject<JObject>(requestCallback);
// assert
Assert.AreEqual($"{DiveraApiUrls.Alarm}?accesskey={accessKey}", requestCallbackUrl);
Assert.IsNotNull(requestCallback);
Assert.IsTrue(response);
Assert.AreEqual(request.Number, callbackJson["number"]);
Assert.AreEqual(request.Title, callbackJson["title"]);
Assert.AreEqual(request.HasPriority, callbackJson["priority"].Value<bool>());
Assert.AreEqual(request.Text, callbackJson["text"]);
Assert.AreEqual(request.Address, callbackJson["address"]);
Assert.AreEqual(request.Latitude, callbackJson["lat"].Value<float>());
Assert.AreEqual(request.Longitude, callbackJson["lng"].Value<float>());
Assert.AreEqual(request.SceneObject, callbackJson["scene_object"]);
Assert.AreEqual(request.Caller, callbackJson["caller"]);
Assert.AreEqual(request.Patient, callbackJson["patient"]);
Assert.AreEqual(request.Remark, callbackJson["remark"]);
Assert.AreEqual(request.Units, callbackJson["units"]);
Assert.AreEqual(request.HasDestination, callbackJson["destination"].Value<bool>());
Assert.AreEqual(request.DestinationAddress, callbackJson["destination_address"]);
Assert.AreEqual(request.DestinationLatitude, callbackJson["destination_lat"].Value<float>());
Assert.AreEqual(request.DestinationLongitude, callbackJson["destination_lng"].Value<float>());
Assert.AreEqual(request.AdditionalText1, callbackJson["additional_text_1"]);
Assert.AreEqual(request.AdditionalText2, callbackJson["additional_text_2"]);
Assert.AreEqual(request.AdditionalText3, callbackJson["additional_text_3"]);
Assert.AreEqual(string.Join(",", request.Rics), callbackJson["ric"]);
Assert.AreEqual(string.Join(",", request.Vehicles), callbackJson["vehicle"]);
Assert.AreEqual(string.Join(",", request.Persons), callbackJson["person"]);
Assert.AreEqual(request.DelaySeconds, callbackJson["delay"]);
Assert.AreEqual(request.Coordinates, callbackJson["coordinates"]);
Assert.AreEqual(request.CoordinatesX, callbackJson["coordinates-x"].Value<float>());
Assert.AreEqual(request.CoordinatesY, callbackJson["coordinates-y"].Value<float>());
Assert.AreEqual(request.IsNews, callbackJson["news"].Value<bool>());
Assert.AreEqual(request.Id, callbackJson["id"]);
CollectionAssert.AreEqual(request.ClusterIds, callbackJson["cluster_ids"].ToObject<List<string>>());
CollectionAssert.AreEqual(request.GroupIds, callbackJson["group_ids"].ToObject<List<string>>());
CollectionAssert.AreEqual(request.UserClusterRelationIds, callbackJson["user_cluster_relation_ids"].ToObject<List<string>>());
CollectionAssert.AreEqual(request.VehicleIds, callbackJson["vehicle_ids"].ToObject<List<string>>());
CollectionAssert.AreEqual(request.AlarmcodeId, callbackJson["alarmcode_id"].ToObject<List<string>>());
httpMessageHandlerMock.Protected().Verify("SendAsync", Times.Exactly(1), ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>());
}
[TestMethod]
public async Task ShouldThrowExceptionOnMissingRequest()
{
// arrange
string accessKey = "abc";
string responseJson = JsonConvert.SerializeObject(new SuccessResponse { IsSuccessful = true });
httpResponseMessage.Content = new StringContent(responseJson, Encoding.UTF8, jsonMimeType);
var api = GetApi(accessKey);
// act + assert
try
{
bool response = await api.CreateAlarm(null);
Assert.Fail();
}
catch (ArgumentNullException)
{ /* expected behaviour */ }
httpMessageHandlerMock.Protected().Verify("SendAsync", Times.Exactly(0), ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>());
}
[TestMethod]
public async Task ShouldThrowExceptionOnInvalidAccessKey()
{
// arrange
string accessKey = "abc";
httpResponseMessage.StatusCode = HttpStatusCode.Forbidden;
var request = new CreateAlarmRequest
{
Number = "47123",
Title = "Probealarm"
};
var api = GetApi(accessKey);
// act + assert
try
{
bool response = await api.CreateAlarm(request);
Assert.Fail();
}
catch (AccessKeyException)
{ /* expected behaviour */ }
httpMessageHandlerMock.Protected().Verify("SendAsync", Times.Exactly(1), ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>());
}
[TestMethod]
public async Task ShouldReturnFalseOnHttpError()
{
// arrange
string accessKey = "abc";
httpResponseMessage.StatusCode = HttpStatusCode.InternalServerError;
var request = new CreateAlarmRequest
{
Number = "47123",
Title = "Probealarm"
};
var api = GetApi(accessKey);
// act
bool response = await api.CreateAlarm(request);
// assert
Assert.AreEqual($"{DiveraApiUrls.Alarm}?accesskey={accessKey}", requestCallbackUrl);
Assert.IsNotNull(requestCallback);
Assert.IsFalse(response);
httpMessageHandlerMock.Protected().Verify("SendAsync", Times.Exactly(1), ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>());
}
[TestMethod]
public async Task ShouldReturnFalseOnDiveraError()
{
// arrange
string accessKey = "abc";
string responseJson = JsonConvert.SerializeObject(new SuccessResponse { IsSuccessful = false });
httpResponseMessage.Content = new StringContent(responseJson, Encoding.UTF8, jsonMimeType);
var request = new CreateAlarmRequest
{
Number = "47123",
Title = "Probealarm"
};
var api = GetApi(accessKey);
// act
bool response = await api.CreateAlarm(request);
// assert
Assert.AreEqual($"{DiveraApiUrls.Alarm}?accesskey={accessKey}", requestCallbackUrl);
Assert.IsNotNull(requestCallback);
Assert.IsFalse(response);
httpMessageHandlerMock.Protected().Verify("SendAsync", Times.Exactly(1), ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>());
}
}
}
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using AMWD.Net.Api.Divera.Responses;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using Moq.Protected;
using Newtonsoft.Json;
namespace AMWD.Net.Api.Divera.Test
{
[TestClass]
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
public class GetLatestAlarmTests : TestBase
{
private static readonly string jsonMimeType = "application/json";
private static readonly DateTime date = new DateTime(2022, 1, 9, 1, 2, 3, DateTimeKind.Utc);
[TestMethod]
public async Task ShouldReturnFullResponse()
{
// arrange
string accessKey = "abc";
var alarmResponse = new AlarmResultResponse
{
Title = "Probealarm",
HasPriority = true,
Text = "Achtung! Dies ist ein Probealarm",
Address = "Dorfstr. 15b, 89001 Musterstadt",
Latitude = 49.12345f,
Longitude = 11.12345f,
SceneObject = "Haus",
Caller = "Max Mustermann, +4917100001",
Patient = "Maria Musterfrau",
Remark = "Zugang nur über Dachluke",
Units = "RTW, DLK",
HasDestination = true,
DestinationAddress = "Hospitalstraße 1, 89001 Musterhausen",
DestinationLatitude = 48.12345f,
DestinationLongitude = 10.12345f,
AdditionalText1 = "Erster Zusatz",
AdditionalText2 = "Zweiter Zusatz",
AdditionalText3 = "Dritter Zusatz",
Id = 123,
ClusterIds = new List<int> { 21, 42 },
GroupIds = new List<int> { 13 },
UserClusterRelationIds = new List<int> { 2113, 4213 },
VehicleIds = new List<int> { 7, 9 },
AlarmcodeId = 2,
AuthorId = 815,
CloseTimestampUnix = 123456,
CreateTimestampUnix = 234567,
Date = date,
DoSendCall = true,
DoSendMail = false,
DoSendPager = true,
DoSendPush = false,
DoSendSms = true,
ForeignId = "fk-123",
HasNotificationFilterAccess = false,
HasNotificationFilterStatus = true,
HasNotificationFilterVehicle = false,
IsAnswerable = true,
IsClosed = false,
IsDeleted = true,
IsDraft = false,
IsEditable = true,
IsNew = false,
#pragma warning disable CS0618
IsNotificationFilterStatusAccess = true,
#pragma warning restore CS0618
IsPrivateMode = false,
IsSelfAddressed = true,
NotificationFilterStatusIds = new List<int> { 1, 2, 3 },
NotificationType = Enums.DiveraNotificationType.SelectedUsers,
PublishTimestampUnix = 345678,
ReadCount = 5,
RecipientsCount = 10,
Report = "Hilfe, die Welt geht unter",
ResponseTimeMinutes = 12,
ResponseTimestampUnix = 456789,
SelfNote = "Hahaha",
SelfStatusId = 6,
UpdateTimestampUnix = 567890,
UserIdsAddressed = new List<int> { 2, 3, 4 },
UserIdsAnswered = new List<int> { 2, 4 }
};
string responseJson = JsonConvert.SerializeObject(alarmResponse);
httpResponseMessage.Content = new StringContent(responseJson, Encoding.UTF8, jsonMimeType);
var api = GetApi(accessKey);
// act
var response = await api.GetLatestAlarm();
// assert
Assert.AreEqual($"{DiveraApiUrls.AlarmLatest}?accesskey={accessKey}", requestCallbackUrl);
Assert.IsNull(requestCallback);
Assert.IsNotNull(response);
Assert.AreEqual(alarmResponse.AdditionalText1, response.AdditionalText1);
Assert.AreEqual(alarmResponse.AdditionalText2, response.AdditionalText2);
Assert.AreEqual(alarmResponse.AdditionalText3, response.AdditionalText3);
Assert.AreEqual(alarmResponse.Address, response.Address);
Assert.AreEqual(alarmResponse.AlarmcodeId, response.AlarmcodeId);
Assert.AreEqual(alarmResponse.AuthorId, response.AuthorId);
Assert.AreEqual(alarmResponse.Caller, response.Caller);
Assert.AreEqual(alarmResponse.CloseTimestampUnix, response.CloseTimestampUnix);
CollectionAssert.AreEqual(alarmResponse.ClusterIds, response.ClusterIds);
Assert.AreEqual(alarmResponse.CreateTimestampUnix, response.CreateTimestampUnix);
Assert.AreEqual(alarmResponse.DateUnix, response.DateUnix);
Assert.AreEqual(alarmResponse.DestinationAddress, response.DestinationAddress);
Assert.AreEqual(alarmResponse.DestinationLatitude, response.DestinationLatitude);
Assert.AreEqual(alarmResponse.DestinationLongitude, response.DestinationLongitude);
Assert.AreEqual(alarmResponse.DoSendCall, response.DoSendCall);
Assert.AreEqual(alarmResponse.DoSendMail, response.DoSendMail);
Assert.AreEqual(alarmResponse.DoSendPager, response.DoSendPager);
Assert.AreEqual(alarmResponse.DoSendPush, response.DoSendPush);
Assert.AreEqual(alarmResponse.DoSendSms, response.DoSendSms);
Assert.AreEqual(alarmResponse.ForeignId, response.ForeignId);
CollectionAssert.AreEqual(alarmResponse.GroupIds, response.GroupIds);
Assert.AreEqual(alarmResponse.HasDestination, response.HasDestination);
Assert.AreEqual(alarmResponse.HasNotificationFilterAccess, response.HasNotificationFilterAccess);
Assert.AreEqual(alarmResponse.HasNotificationFilterStatus, response.HasNotificationFilterStatus);
Assert.AreEqual(alarmResponse.HasNotificationFilterVehicle, response.HasNotificationFilterVehicle);
Assert.AreEqual(alarmResponse.HasPriority, response.HasPriority);