Skip to content

Commit

Permalink
Merge branch 'dev' into unit-tests
Browse files Browse the repository at this point in the history
  • Loading branch information
matt-lethargic authored Apr 14, 2022
2 parents 2f7fc0c + f45294f commit 9cc0bad
Show file tree
Hide file tree
Showing 17 changed files with 304 additions and 119 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/dotnet-core.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
branches: [ main, dev ]

jobs:
build:
Expand Down
2 changes: 1 addition & 1 deletion Nexmo.Api.Test.Unit/Nexmo.Api.Test.Unit.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFrameworks>net452;net46;net461;net462;netcoreapp2.0;netcoreapp2.1;netcoreapp2.2;net47;net471;net472;net48;netcoreapp3.0;netcoreapp3.1</TargetFrameworks>
<TargetFrameworks>net452;net46;net462;netcoreapp2.0;netcoreapp2.1;netcoreapp2.2;net47;net471;net472;net48;netcoreapp3.0;netcoreapp3.1</TargetFrameworks>
<NoWarn>1701;1702;0618</NoWarn>
<IsPackable>false</IsPackable>
<Configurations>Debug;Release;ReleaseSigned</Configurations>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"message-count": "1",
"messages": [
{
"status": "4",
"error-text": "invalid credentials"
}
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"message-count": "1",
"messages": [
{
"to": "447700900000",
"message-id": "0A0000000123ABCD1",
"status": "0",
"remaining-balance": "3.14159265",
"message-price": "0.03330000",
"network": "12345",
"account-ref": "customer1234"
}
]
}
9 changes: 9 additions & 0 deletions Vonage.Test.Unit/Data/MessagingTests/SendSmsBadResponse.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"message-count": "1",
"messages": [
{
"status": "4",
"error-text": "invalid credentials"
}
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"message-count": "1",
"messages": [
{
"to": "447700900000",
"message-id": "0A0000000123ABCD1",
"status": "0",
"remaining-balance": "3.14159265",
"message-price": "0.03330000",
"network": "12345",
"account-ref": "customer1234"
}
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"message-count": "1",
"messages": [
{
"to": "447700900000",
"message-id": "0A0000000123ABCD1",
"status": "0",
"remaining-balance": "3.14159265",
"message-price": "0.03330000",
"network": "12345",
"account-ref": "customer1234"
}
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"message-count": "1",
"messages": [
{
"status": "4",
"error-text": "invalid credentials"
}
]
}
169 changes: 97 additions & 72 deletions Vonage.Test.Unit/MessagingTests.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
using Newtonsoft.Json;
using Vonage.Messaging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Xunit;
Expand All @@ -16,28 +13,16 @@ public class MessagingTests : TestBase
[Theory]
[InlineData(false)]
[InlineData(true)]
public void KitcenSinkSendSms(bool passCreds)
public void SendSmsWithAllPropertiesSet(bool passCreds)
{
var expectedResponse = @"{
""message-count"": ""1"",
""messages"": [
{
""to"": ""447700900000"",
""message-id"": ""0A0000000123ABCD1"",
""status"": ""0"",
""remaining-balance"": ""3.14159265"",
""message-price"": ""0.03330000"",
""network"": ""12345"",
""account-ref"": ""customer1234""
}
]
}";
var expectedResponse = GetExpectedJson();
var expectedUri = $"{RestUrl}/sms/json?";
var expectedRequestContent = $"from=AcmeInc&to=447700900000&text={HttpUtility.UrlEncode("Hello World!")}" +
$"&ttl=900000&status-report-req=true&callback={HttpUtility.UrlEncode("https://example.com/sms-dlr")}&message-class=0" +
$"&type=text&vcard=none&vcal=none&body=638265253311&udh=06050415811581&protocol-id=127&title=welcome&url={HttpUtility.UrlEncode("https://example.com")}" +
$"&validity=300000&client-ref=my-personal-reference&account-ref=customer1234&entity-id=testEntity&content-id=testcontent&api_key={ApiKey}&api_secret={ApiSecret}&";
var request = new Messaging.SendSmsRequest

var request = new SendSmsRequest
{
AccountRef = "customer1234",
Body = "638265253311",
Expand All @@ -59,21 +44,68 @@ public void KitcenSinkSendSms(bool passCreds)
Url = "https://example.com",
ContentId = "testcontent",
EntityId = "testEntity"
};

var creds = Request.Credentials.FromApiKeyAndSecret(ApiKey, ApiSecret);
Setup(expectedUri, expectedResponse, expectedRequestContent);
var client = new VonageClient(creds);

var response = passCreds
? client.SmsClient.SendAnSms(request, creds)
: client.SmsClient.SendAnSms(request);

Assert.Equal("1", response.MessageCount);
Assert.Equal("447700900000", response.Messages[0].To);
Assert.Equal("0A0000000123ABCD1", response.Messages[0].MessageId);
Assert.Equal("0", response.Messages[0].Status);
Assert.Equal("3.14159265", response.Messages[0].RemainingBalance);
Assert.Equal("12345", response.Messages[0].Network);
Assert.Equal("customer1234", response.Messages[0].AccountRef);
}

[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task SendSmsAsyncWithAllPropertiesSet(bool passCreds)
{
var expectedResponse = GetExpectedJson();
var expectedUri = $"{RestUrl}/sms/json?";
var expectedRequestContent = $"from=AcmeInc&to=447700900000&text={HttpUtility.UrlEncode("Hello World!")}" +
$"&ttl=900000&status-report-req=true&callback={HttpUtility.UrlEncode("https://example.com/sms-dlr")}&message-class=0" +
$"&type=text&vcard=none&vcal=none&body=638265253311&udh=06050415811581&protocol-id=127&title=welcome&url={HttpUtility.UrlEncode("https://example.com")}" +
$"&validity=300000&client-ref=my-personal-reference&account-ref=customer1234&entity-id=testEntity&content-id=testcontent&api_key={ApiKey}&api_secret={ApiSecret}&";

var request = new SendSmsRequest
{
AccountRef = "customer1234",
Body = "638265253311",
Callback = "https://example.com/sms-dlr",
ClientRef = "my-personal-reference",
From = "AcmeInc",
To = "447700900000",
MessageClass = 0,
ProtocolId = 127,
StatusReportReq = true,
Text = "Hello World!",
Title = "welcome",
Ttl = 900000,
Type = SmsType.text,
Udh = "06050415811581",
Validity = "300000",
Vcal = "none",
Vcard = "none",
Url = "https://example.com",
ContentId = "testcontent",
EntityId = "testEntity"
};

var creds = Request.Credentials.FromApiKeyAndSecret(ApiKey, ApiSecret);
Setup(expectedUri, expectedResponse, expectedRequestContent);
var client = new VonageClient(creds);
Messaging.SendSmsResponse response;
if (passCreds)
{
response = client.SmsClient.SendAnSms(request, creds);
}
else
{
response = client.SmsClient.SendAnSms(request);
}

var response = passCreds
? await client.SmsClient.SendAnSmsAsync(request, creds)
: await client.SmsClient.SendAnSmsAsync(request);

Assert.Equal("1", response.MessageCount);
Assert.Equal("447700900000", response.Messages[0].To);
Expand Down Expand Up @@ -149,22 +181,9 @@ public void SendSmsTypicalUsageSimplified()
}

[Fact]
public async void SendSmsTypicalUsageSimplifiedAsync()
public async Task SendSmsTypicalUsageSimplifiedAsync()
{
var expectedResponse = @"{
""message-count"": ""1"",
""messages"": [
{
""to"": ""447700900000"",
""message-id"": ""0A0000000123ABCD1"",
""status"": ""0"",
""remaining-balance"": ""3.14159265"",
""message-price"": ""0.03330000"",
""network"": ""12345"",
""account-ref"": ""customer1234""
}
]
}";
var expectedResponse = GetExpectedJson();
var expectedUri = $"{RestUrl}/sms/json?";
var expectedRequestContent = $"from=AcmeInc&to=447700900000&text={HttpUtility.UrlEncode("Hello World!")}&type=text&api_key={ApiKey}&api_secret={ApiSecret}&";
Setup(expectedUri, expectedResponse, expectedRequestContent);
Expand Down Expand Up @@ -215,29 +234,35 @@ public void SendSmsUnicode()
[Fact]
public void SendSmsBadResponse()
{
var expectedResponse = @"{
""message-count"": ""1"",
""messages"": [
{
""status"": ""4"",
""error-text"":""invalid credentials""
}
]
}";
var expectedResponse = GetExpectedJson();
var expectedUri = $"{RestUrl}/sms/json?";
var expectedRequestContent = $"from=AcmeInc&to=447700900000&text={HttpUtility.UrlEncode("Hello World!")}&api_key={ApiKey}&api_secret={ApiSecret}&";
Setup(expectedUri, expectedResponse, expectedRequestContent);
var client = new VonageClient(Request.Credentials.FromApiKeyAndSecret(ApiKey, ApiSecret));
try
{
var response = client.SmsClient.SendAnSms(new Messaging.SendSmsRequest { From = "AcmeInc", To = "447700900000", Text = "Hello World!" });
Assert.True(false);
}
catch (Messaging.VonageSmsResponseException nex)
{
Assert.Equal($"SMS Request Failed with status: {nex.Response.Messages[0].Status} and error message: {nex.Response.Messages[0].ErrorText}", nex.Message);
Assert.Equal(SmsStatusCode.InvalidCredentials, nex.Response.Messages[0].StatusCode);
}

var exception = Assert.Throws<VonageSmsResponseException>(() =>
client.SmsClient.SendAnSms(new SendSmsRequest { From = "AcmeInc", To = "447700900000", Text = "Hello World!" }));

Assert.NotNull(exception);
Assert.Equal($"SMS Request Failed with status: {exception.Response.Messages[0].Status} and error message: {exception.Response.Messages[0].ErrorText}", exception.Message);
Assert.Equal(SmsStatusCode.InvalidCredentials, exception.Response.Messages[0].StatusCode);
}

[Fact]
public async Task SendSmsAsyncBadResponse()
{
var expectedResponse = GetExpectedJson();
var expectedUri = $"{RestUrl}/sms/json?";
var expectedRequestContent = $"from=AcmeInc&to=447700900000&text={HttpUtility.UrlEncode("Hello World!")}&api_key={ApiKey}&api_secret={ApiSecret}&";
Setup(expectedUri, expectedResponse, expectedRequestContent);
var client = new VonageClient(Request.Credentials.FromApiKeyAndSecret(ApiKey, ApiSecret));

var exception = await Assert.ThrowsAsync<VonageSmsResponseException>(async () =>
await client.SmsClient.SendAnSmsAsync(new SendSmsRequest { From = "AcmeInc", To = "447700900000", Text = "Hello World!" }));

Assert.NotNull(exception);
Assert.Equal($"SMS Request Failed with status: {exception.Response.Messages[0].Status} and error message: {exception.Response.Messages[0].ErrorText}", exception.Message);
Assert.Equal(SmsStatusCode.InvalidCredentials, exception.Response.Messages[0].StatusCode);
}

[Fact]
Expand All @@ -246,17 +271,15 @@ public void NullMessagesResponse()
var expectedResponse = @"";
var expectedUri = $"{RestUrl}/sms/json?";
var expectedRequestContent = $"from=AcmeInc&to=447700900000&text={HttpUtility.UrlEncode("Hello World!")}&api_key={ApiKey}&api_secret={ApiSecret}&";

Setup(expectedUri, expectedResponse, expectedRequestContent);
var client = new VonageClient(Request.Credentials.FromApiKeyAndSecret(ApiKey, ApiSecret));
try
{
var response = client.SmsClient.SendAnSms(new Messaging.SendSmsRequest { From = "AcmeInc", To = "447700900000", Text = "Hello World!" });
Assert.True(false);
}
catch (Messaging.VonageSmsResponseException nex)
{
Assert.Equal($"Encountered an Empty SMS response", nex.Message);
}

var exception = Assert.Throws<VonageSmsResponseException>(() =>
client.SmsClient.SendAnSms(new SendSmsRequest { From = "AcmeInc", To = "447700900000", Text = "Hello World!" }));

Assert.NotNull(exception);
Assert.Equal($"Encountered an Empty SMS response", exception.Message);
}

[Fact]
Expand Down Expand Up @@ -390,7 +413,9 @@ public void TestValidateSignatureMd5()
var TestSigningSecret = "Y6dI3wtDP8myVH5tnDoIaTxEvAJhgDVCczBa1mHniEqsdlnnebg";
var json = JsonConvert.SerializeObject(inboundSmsShell, Formatting.None, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore });
var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
inboundSmsShell.Sig = Cryptography.SmsSignatureGenerator.GenerateSignature(InboundSms.ConstructSignatureStringFromDictionary(dict), TestSigningSecret, Cryptography.SmsSignatureGenerator.Method.md5);

inboundSmsShell.Sig = Cryptography.SmsSignatureGenerator.GenerateSignature(Messaging.InboundSms.ConstructSignatureStringFromDictionary(dict), TestSigningSecret, Cryptography.SmsSignatureGenerator.Method.md5);

Assert.True(inboundSmsShell.ValidateSignature(TestSigningSecret, Cryptography.SmsSignatureGenerator.Method.md5));
}

Expand Down
23 changes: 11 additions & 12 deletions Vonage.Test.Unit/TestBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@
using System.Threading.Tasks;
using Moq;
using Moq.Protected;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Vonage.Test.Unit
{
Expand Down Expand Up @@ -59,18 +57,19 @@ public static string AssemblyDirectory

public void Setup(string uri, string responseContent, string requestContent = null, HttpStatusCode expectedCode = HttpStatusCode.OK)
{
typeof(Configuration).GetField("_client", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(Configuration.Instance, null);
typeof(Configuration).GetField("_client", BindingFlags.Instance | BindingFlags.NonPublic)?.SetValue(Configuration.Instance, null);
var mockHandler = new Mock<HttpMessageHandler>(MockBehavior.Strict);
mockHandler
.Protected()
.Setup<Task<HttpResponseMessage>>(MOCKED_METHOD,
ItExpr.Is<HttpRequestMessage>(
x =>
string.Equals(x.RequestUri.AbsoluteUri, uri, StringComparison.OrdinalIgnoreCase) &&
(requestContent == null) ||
(string.Equals(x.Content.ReadAsStringAsync().Result, requestContent, StringComparison.OrdinalIgnoreCase))),
ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(new HttpResponseMessage()
ItExpr.Is<HttpRequestMessage>(
x =>
string.Equals(x.RequestUri.AbsoluteUri, uri, StringComparison.OrdinalIgnoreCase) &&
requestContent == null ||
string.Equals(x.Content.ReadAsStringAsync().Result, requestContent, StringComparison.OrdinalIgnoreCase)),
ItExpr.IsAny<CancellationToken>()
)
.ReturnsAsync(new HttpResponseMessage
{
StatusCode = expectedCode,
Content = new StringContent(responseContent)
Expand All @@ -89,15 +88,15 @@ private void Setup(string uri, HttpContent httpContent, HttpStatusCode expectedC
{
typeof(Configuration).GetField("_client", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(Configuration.Instance, null);
Mock<HttpMessageHandler> mockHandler = new Mock<HttpMessageHandler>(MockBehavior.Strict);

mockHandler
.Protected()
.Setup<Task<HttpResponseMessage>>(MOCKED_METHOD,
ItExpr.Is<HttpRequestMessage>(
x => string.Equals(x.RequestUri.AbsoluteUri, uri, StringComparison.OrdinalIgnoreCase) && (requestContent == null) ||
string.Equals(x.Content.ReadAsStringAsync().Result, requestContent, StringComparison.OrdinalIgnoreCase)
),
ItExpr.IsAny<CancellationToken>()
)
ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(new HttpResponseMessage()
{
StatusCode = expectedCode,
Expand Down
Loading

0 comments on commit 9cc0bad

Please sign in to comment.