diff --git a/ExampleCoreProject/ExampleCoreProject.csproj b/ExampleCoreProject/ExampleCoreProject.csproj index 0d5601d03..f179efa45 100644 --- a/ExampleCoreProject/ExampleCoreProject.csproj +++ b/ExampleCoreProject/ExampleCoreProject.csproj @@ -1,7 +1,7 @@  - netcoreapp2.1 + net8.0 Exe false diff --git a/SendGrid.sln b/SendGrid.sln index e3837c1f8..ff5d593a3 100644 --- a/SendGrid.sln +++ b/SendGrid.sln @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 16 -VisualStudioVersion = 16.0.29519.87 +# Visual Studio Version 17 +VisualStudioVersion = 17.10.35027.167 MinimumVisualStudioVersion = 10.0.40219.1 Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{71C09624-020B-410E-A8FE-1FD216A1FE31}" EndProject @@ -38,6 +38,10 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution USE_CASES.md = USE_CASES.md EndProjectSection EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SendGrid.Extensions.DependencyInjection.Net21Tests", "tests\SendGrid.Extensions.DependencyInjection.Net21Tests\SendGrid.Extensions.DependencyInjection.Net21Tests.csproj", "{24BE2F5A-2B03-4493-B518-6722556C6995}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SendGrid.Net21Tests", "tests\SendGrid.Net21Tests\SendGrid.Net21Tests.csproj", "{2F9B46FF-923A-47C4-AC52-6A621A8E0850}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -68,6 +72,14 @@ Global {C65468A6-BDE2-4FD4-9400-B668B1395B26}.Debug|Any CPU.Build.0 = Debug|Any CPU {C65468A6-BDE2-4FD4-9400-B668B1395B26}.Release|Any CPU.ActiveCfg = Release|Any CPU {C65468A6-BDE2-4FD4-9400-B668B1395B26}.Release|Any CPU.Build.0 = Release|Any CPU + {24BE2F5A-2B03-4493-B518-6722556C6995}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {24BE2F5A-2B03-4493-B518-6722556C6995}.Debug|Any CPU.Build.0 = Debug|Any CPU + {24BE2F5A-2B03-4493-B518-6722556C6995}.Release|Any CPU.ActiveCfg = Release|Any CPU + {24BE2F5A-2B03-4493-B518-6722556C6995}.Release|Any CPU.Build.0 = Release|Any CPU + {2F9B46FF-923A-47C4-AC52-6A621A8E0850}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2F9B46FF-923A-47C4-AC52-6A621A8E0850}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2F9B46FF-923A-47C4-AC52-6A621A8E0850}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2F9B46FF-923A-47C4-AC52-6A621A8E0850}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -79,6 +91,8 @@ Global {3B3F2699-F720-4498-8044-262EFE110A22} = {D3201F71-A289-4136-AC7E-E5204ACB9183} {AF9D60DF-EF22-40FD-9C56-7E7F2BCB9683} = {71C09624-020B-410E-A8FE-1FD216A1FE31} {C65468A6-BDE2-4FD4-9400-B668B1395B26} = {D06BDAE9-BE83-448F-8AD4-3044BB187C11} + {24BE2F5A-2B03-4493-B518-6722556C6995} = {D06BDAE9-BE83-448F-8AD4-3044BB187C11} + {2F9B46FF-923A-47C4-AC52-6A621A8E0850} = {D06BDAE9-BE83-448F-8AD4-3044BB187C11} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {CB90618B-6B7B-4D09-9D35-467325708BAA} diff --git a/src/SendGrid/BaseClient.cs b/src/SendGrid/BaseClient.cs index 3e2a351d6..8eecb91e7 100644 --- a/src/SendGrid/BaseClient.cs +++ b/src/SendGrid/BaseClient.cs @@ -1,4 +1,8 @@ -using Newtonsoft.Json; +#if NETSTANDARD2_0 +using System.Text.Json; +#else +using Newtonsoft.Json; +#endif using SendGrid.Helpers.Errors; using SendGrid.Helpers.Mail; using SendGrid.Helpers.Reliability; @@ -328,6 +332,42 @@ private Dictionary> ParseJson(string json) { var dict = new Dictionary>(); +#if NETSTANDARD2_0 + var reader = System.Text.Json.Nodes.JsonNode.Parse(json).AsObject(); + foreach (var v in reader) + { + var propertyName = v.Key; + switch (v.Value.GetValueKind()) + { + case JsonValueKind.Undefined: + case JsonValueKind.Object: + case JsonValueKind.Array: + case JsonValueKind.Null: + break; + case JsonValueKind.String: + dict[propertyName].Add((string)v.Value); + break; + case JsonValueKind.Number: + if (v.Value.ToString().Contains(".")) + { + dict[propertyName].Add((double)v.Value); + } + else + { + dict[propertyName].Add((int)v.Value); + } + break; + case JsonValueKind.True: + dict[propertyName].Add(true); + break; + case JsonValueKind.False: + dict[propertyName].Add(false); + break; + default: + throw new ArgumentOutOfRangeException(); + } + } +#else using (var sr = new StringReader(json)) using (var reader = new JsonTextReader(sr)) { @@ -360,6 +400,7 @@ private Dictionary> ParseJson(string json) } } } +#endif return dict; } diff --git a/src/SendGrid/Helpers/Errors/ErrorHandler.cs b/src/SendGrid/Helpers/Errors/ErrorHandler.cs index bb1204681..bf9a4473e 100644 --- a/src/SendGrid/Helpers/Errors/ErrorHandler.cs +++ b/src/SendGrid/Helpers/Errors/ErrorHandler.cs @@ -1,7 +1,14 @@ -using Newtonsoft.Json.Linq; +#if NETSTANDARD2_0 +using System.Text.Json; +using System.Text.Json.Nodes; +#else +using Newtonsoft.Json.Linq; +#endif using SendGrid.Helpers.Errors.Model; using System.Net.Http; using System.Threading.Tasks; +using System; +using System.Linq; namespace SendGrid.Helpers.Errors { @@ -103,6 +110,31 @@ private static async Task GetErrorMessage(HttpResponseMessage message) try { // Check for the presence of property called 'errors' +#if NETSTANDARD2_0 + var jObject = JsonNode.Parse(responseContent); + var errorsArray = (JsonArray)jObject["errors"]; + if (errorsArray != null && errorsArray.Count > 0) { + // Get the first error message + errorValue = (string)errorsArray[0]["message"]; + + // Check for the presence of property called 'field' + if (errorsArray[0]["field"] != null) { + fieldValue = (string)errorsArray[0]["field"]; + } + + // Check for the presence of property called 'help' + if (errorsArray[0]["help"] != null) { + helpValue = (string)errorsArray[0]["help"]; + } + } + else { + // Check for the presence of property called 'error' + var errorProperty = jObject["error"]; + if (errorProperty != null) { + errorValue = (string)errorProperty; + } + } +#else var jObject = JObject.Parse(responseContent); var errorsArray = (JArray)jObject["errors"]; if (errorsArray != null && errorsArray.Count > 0) @@ -131,6 +163,7 @@ private static async Task GetErrorMessage(HttpResponseMessage message) errorValue = errorProperty.Value(); } } +#endif } catch { @@ -148,7 +181,11 @@ private static async Task GetErrorMessage(HttpResponseMessage message) HelpLink = helpValue }; +#if NETSTANDARD2_0 + return JsonSerializer.Serialize(errorResponse); +#else return Newtonsoft.Json.JsonConvert.SerializeObject(errorResponse); +#endif } } } diff --git a/src/SendGrid/Helpers/Mail/Model/ASM.cs b/src/SendGrid/Helpers/Mail/Model/ASM.cs index 526f8714a..d1607655f 100644 --- a/src/SendGrid/Helpers/Mail/Model/ASM.cs +++ b/src/SendGrid/Helpers/Mail/Model/ASM.cs @@ -3,7 +3,11 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. // +#if NETSTANDARD2_0 +using System.Text.Json.Serialization; +#else using Newtonsoft.Json; +#endif using System.Collections.Generic; namespace SendGrid.Helpers.Mail @@ -11,20 +15,32 @@ namespace SendGrid.Helpers.Mail /// /// An object allowing you to specify how to handle unsubscribes. /// +#if NETSTANDARD2_0 + // Globally defined by setting ReferenceHandler on the JsonSerializerOptions object +#else [JsonObject(IsReference = false)] +#endif public class ASM { /// /// Gets or sets the unsubscribe group to associate with this email. /// +#if NETSTANDARD2_0 + [JsonPropertyName("group_id")] +#else [JsonProperty(PropertyName = "group_id")] +#endif public int GroupId { get; set; } /// /// Gets or sets an array containing the unsubscribe groups that you would like to be displayed on the unsubscribe preferences page. /// https://sendgrid.com/docs/User_Guide/Suppressions/recipient_subscription_preferences.html. /// +#if NETSTANDARD2_0 + [JsonPropertyName("groups_to_display")] +#else [JsonProperty(PropertyName = "groups_to_display", IsReference = false)] +#endif public List GroupsToDisplay { get; set; } } } diff --git a/src/SendGrid/Helpers/Mail/Model/Attachment.cs b/src/SendGrid/Helpers/Mail/Model/Attachment.cs index 92a0db625..c2ada75c1 100644 --- a/src/SendGrid/Helpers/Mail/Model/Attachment.cs +++ b/src/SendGrid/Helpers/Mail/Model/Attachment.cs @@ -3,44 +3,72 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. // +#if NETSTANDARD2_0 +using System.Text.Json.Serialization; +#else using Newtonsoft.Json; +#endif namespace SendGrid.Helpers.Mail { /// /// Gets or sets an array of objects in which you can specify any attachments you want to include. /// +#if NETSTANDARD2_0 + // Globally defined by setting ReferenceHandler on the JsonSerializerOptions object +#else [JsonObject(IsReference = false)] +#endif public class Attachment { /// /// Gets or sets the Base64 encoded content of the attachment. /// +#if NETSTANDARD2_0 + [JsonPropertyName("content")] +#else [JsonProperty(PropertyName = "content")] +#endif public string Content { get; set; } /// /// Gets or sets the mime type of the content you are attaching. For example, application/pdf or image/jpeg. /// +#if NETSTANDARD2_0 + [JsonPropertyName("type")] +#else [JsonProperty(PropertyName = "type")] +#endif public string Type { get; set; } /// /// Gets or sets the filename of the attachment. /// +#if NETSTANDARD2_0 + [JsonPropertyName("filename")] +#else [JsonProperty(PropertyName = "filename")] +#endif public string Filename { get; set; } /// /// Gets or sets the content-disposition of the attachment specifying how you would like the attachment to be displayed. For example, "inline" results in the attached file being displayed automatically within the message while "attachment" results in the attached file requiring some action to be taken before it is displayed (e.g. opening or downloading the file). Defaults to "attachment". Can be either "attachment" or "inline". /// +#if NETSTANDARD2_0 + [JsonPropertyName("disposition")] +#else [JsonProperty(PropertyName = "disposition")] +#endif public string Disposition { get; set; } /// /// Gets or sets a unique id that you specify for the attachment. This is used when the disposition is set to "inline" and the attachment is an image, allowing the file to be displayed within the body of your email. Ex: . /// +#if NETSTANDARD2_0 + [JsonPropertyName("content_id")] +#else [JsonProperty(PropertyName = "content_id")] +#endif public string ContentId { get; set; } } } diff --git a/src/SendGrid/Helpers/Mail/Model/BCCSettings.cs b/src/SendGrid/Helpers/Mail/Model/BCCSettings.cs index c539adef5..8586e7307 100644 --- a/src/SendGrid/Helpers/Mail/Model/BCCSettings.cs +++ b/src/SendGrid/Helpers/Mail/Model/BCCSettings.cs @@ -3,26 +3,42 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. // +#if NETSTANDARD2_0 +using System.Text.Json.Serialization; +#else using Newtonsoft.Json; +#endif namespace SendGrid.Helpers.Mail { /// /// Gets or sets the address specified in the mail_settings.bcc object will receive a blind carbon copy (BCC) of the very first personalization defined in the personalizations array. /// +#if NETSTANDARD2_0 + // Globally defined by setting ReferenceHandler on the JsonSerializerOptions object +#else [JsonObject(IsReference = false)] +#endif public class BCCSettings { /// /// Gets or sets a value indicating whether this setting is enabled. /// +#if NETSTANDARD2_0 + [JsonPropertyName("enable")] +#else [JsonProperty(PropertyName = "enable")] +#endif public bool? Enable { get; set; } /// /// Gets or sets the email address that you would like to receive the BCC. /// +#if NETSTANDARD2_0 + [JsonPropertyName("email")] +#else [JsonProperty(PropertyName = "email")] +#endif public string Email { get; set; } } } diff --git a/src/SendGrid/Helpers/Mail/Model/BypassBounceManagement.cs b/src/SendGrid/Helpers/Mail/Model/BypassBounceManagement.cs index 659e5b8f2..4b0c880bd 100644 --- a/src/SendGrid/Helpers/Mail/Model/BypassBounceManagement.cs +++ b/src/SendGrid/Helpers/Mail/Model/BypassBounceManagement.cs @@ -3,20 +3,32 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. // +#if NETSTANDARD2_0 +using System.Text.Json.Serialization; +#else using Newtonsoft.Json; +#endif namespace SendGrid.Helpers.Mail { /// /// Allows you to bypass the bounce list to ensure that the email is delivered to recipients. Spam report and unsubscribe lists will still be checked; addresses on these other lists will not receive the message. /// +#if NETSTANDARD2_0 + // Globally defined by setting ReferenceHandler on the JsonSerializerOptions object +#else [JsonObject(IsReference = false)] +#endif public class BypassBounceManagement { /// /// Gets or sets a value indicating whether this setting is enabled. /// +#if NETSTANDARD2_0 + [JsonPropertyName("enable")] +#else [JsonProperty(PropertyName = "enable")] +#endif public bool Enable { get; set; } } } diff --git a/src/SendGrid/Helpers/Mail/Model/BypassListManagement.cs b/src/SendGrid/Helpers/Mail/Model/BypassListManagement.cs index a351568a5..e2c2156be 100644 --- a/src/SendGrid/Helpers/Mail/Model/BypassListManagement.cs +++ b/src/SendGrid/Helpers/Mail/Model/BypassListManagement.cs @@ -3,20 +3,32 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. // +#if NETSTANDARD2_0 +using System.Text.Json.Serialization; +#else using Newtonsoft.Json; +#endif namespace SendGrid.Helpers.Mail { /// /// Allows you to bypass all unsubscribe groups and suppressions to ensure that the email is delivered to every single recipient. This should only be used in emergencies when it is absolutely necessary that every recipient receives your email. Ex: outage emails, or forgot password emails. /// +#if NETSTANDARD2_0 + // Globally defined by setting ReferenceHandler on the JsonSerializerOptions object +#else [JsonObject(IsReference = false)] +#endif public class BypassListManagement { /// /// Gets or sets a value indicating whether this setting is enabled. /// +#if NETSTANDARD2_0 + [JsonPropertyName("enable")] +#else [JsonProperty(PropertyName = "enable")] +#endif public bool Enable { get; set; } } } diff --git a/src/SendGrid/Helpers/Mail/Model/BypassSpamManagement.cs b/src/SendGrid/Helpers/Mail/Model/BypassSpamManagement.cs index 0ea79e4a7..a2fccb591 100644 --- a/src/SendGrid/Helpers/Mail/Model/BypassSpamManagement.cs +++ b/src/SendGrid/Helpers/Mail/Model/BypassSpamManagement.cs @@ -3,20 +3,32 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. // +#if NETSTANDARD2_0 +using System.Text.Json.Serialization; +#else using Newtonsoft.Json; +#endif namespace SendGrid.Helpers.Mail { /// /// Allows you to bypass the spam report list to ensure that the email is delivered to recipients. Bounce and unsubscribe lists will still be checked; addresses on these other lists will not receive the message. /// +#if NETSTANDARD2_0 + // Globally defined by setting ReferenceHandler on the JsonSerializerOptions object +#else [JsonObject(IsReference = false)] +#endif public class BypassSpamManagement { /// /// Gets or sets a value indicating whether this setting is enabled. /// +#if NETSTANDARD2_0 + [JsonPropertyName("enable")] +#else [JsonProperty(PropertyName = "enable")] +#endif public bool Enable { get; set; } } } diff --git a/src/SendGrid/Helpers/Mail/Model/BypassUnsubscribeManagement.cs b/src/SendGrid/Helpers/Mail/Model/BypassUnsubscribeManagement.cs index d6f565016..c73745998 100644 --- a/src/SendGrid/Helpers/Mail/Model/BypassUnsubscribeManagement.cs +++ b/src/SendGrid/Helpers/Mail/Model/BypassUnsubscribeManagement.cs @@ -3,20 +3,32 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. // +#if NETSTANDARD2_0 +using System.Text.Json.Serialization; +#else using Newtonsoft.Json; +#endif namespace SendGrid.Helpers.Mail { /// /// Allows you to bypass the global unsubscribe list to ensure that the email is delivered to recipients. Bounce and spam report lists will still be checked; addresses on these other lists will not receive the message. This filter applies only to global unsubscribes and will not bypass group unsubscribes. /// +#if NETSTANDARD2_0 + // Globally defined by setting ReferenceHandler on the JsonSerializerOptions object +#else [JsonObject(IsReference = false)] +#endif public class BypassUnsubscribeManagement { /// /// Gets or sets a value indicating whether this setting is enabled. /// +#if NETSTANDARD2_0 + [JsonPropertyName("enable")] +#else [JsonProperty(PropertyName = "enable")] +#endif public bool Enable { get; set; } } } diff --git a/src/SendGrid/Helpers/Mail/Model/ClickTracking.cs b/src/SendGrid/Helpers/Mail/Model/ClickTracking.cs index 05f9d44cd..2580edc0f 100644 --- a/src/SendGrid/Helpers/Mail/Model/ClickTracking.cs +++ b/src/SendGrid/Helpers/Mail/Model/ClickTracking.cs @@ -3,26 +3,42 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. // +#if NETSTANDARD2_0 +using System.Text.Json.Serialization; +#else using Newtonsoft.Json; +#endif namespace SendGrid.Helpers.Mail { /// /// Allows you to track whether a recipient clicked a link in your email. /// +#if NETSTANDARD2_0 + // Globally defined by setting ReferenceHandler on the JsonSerializerOptions object +#else [JsonObject(IsReference = false)] +#endif public class ClickTracking { /// /// Gets or sets a value indicating whether this setting is enabled. /// +#if NETSTANDARD2_0 + [JsonPropertyName("enable")] +#else [JsonProperty(PropertyName = "enable")] +#endif public bool? Enable { get; set; } /// /// Gets or sets if this setting should be included in the text/plain portion of your email. /// +#if NETSTANDARD2_0 + [JsonPropertyName("enable_text")] +#else [JsonProperty(PropertyName = "enable_text")] +#endif public bool? EnableText { get; set; } } } diff --git a/src/SendGrid/Helpers/Mail/Model/Content.cs b/src/SendGrid/Helpers/Mail/Model/Content.cs index 844fee8ab..12051ca73 100644 --- a/src/SendGrid/Helpers/Mail/Model/Content.cs +++ b/src/SendGrid/Helpers/Mail/Model/Content.cs @@ -3,14 +3,22 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. // +#if NETSTANDARD2_0 +using System.Text.Json.Serialization; +#else using Newtonsoft.Json; +#endif namespace SendGrid.Helpers.Mail { /// /// Specifies the content of your email. You can include multiple mime types of content, but you must specify at least one. To include more than one mime type, simply add another object to the array containing the type and value parameters. If included, text/plain and text/html must be the first indices of the array in this order. If you choose to include the text/plain or text/html mime types, they must be the first indices of the content array in the order text/plain, text/html.*Content is NOT mandatory if you using a transactional template and have defined the template_id in the Request. /// +#if NETSTANDARD2_0 + // Globally defined by setting ReferenceHandler on the JsonSerializerOptions object +#else [JsonObject(IsReference = false)] +#endif public class Content { /// @@ -34,13 +42,21 @@ public Content(string type, string value) /// /// Gets or sets the mime type of the content you are including in your email. For example, text/plain or text/html. /// +#if NETSTANDARD2_0 + [JsonPropertyName("type")] +#else [JsonProperty(PropertyName = "type")] +#endif public string Type { get; set; } /// /// Gets or sets the actual content of the specified mime type that you are including in your email. /// +#if NETSTANDARD2_0 + [JsonPropertyName("value")] +#else [JsonProperty(PropertyName = "value")] +#endif public string Value { get; set; } } } diff --git a/src/SendGrid/Helpers/Mail/Model/EmailAddress.cs b/src/SendGrid/Helpers/Mail/Model/EmailAddress.cs index cbf7baafd..53022fca2 100644 --- a/src/SendGrid/Helpers/Mail/Model/EmailAddress.cs +++ b/src/SendGrid/Helpers/Mail/Model/EmailAddress.cs @@ -3,7 +3,11 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. // +#if NETSTANDARD2_0 +using System.Text.Json.Serialization; +#else using Newtonsoft.Json; +#endif using System; namespace SendGrid.Helpers.Mail @@ -11,7 +15,11 @@ namespace SendGrid.Helpers.Mail /// /// An email object containing the email address and name of the sender or recipient. /// +#if NETSTANDARD2_0 + // Globally defined by setting ReferenceHandler on the JsonSerializerOptions object +#else [JsonObject(IsReference = false)] +#endif public class EmailAddress : IEquatable { /// @@ -35,13 +43,21 @@ public EmailAddress(string email, string name = null) /// /// Gets or sets the name of the sender or recipient. /// +#if NETSTANDARD2_0 + [JsonPropertyName("name")] +#else [JsonProperty(PropertyName = "name")] +#endif public string Name { get; set; } /// /// Gets or sets the email address of the sender or recipient. /// +#if NETSTANDARD2_0 + [JsonPropertyName("email")] +#else [JsonProperty(PropertyName = "email")] +#endif public string Email { get; set; } /// diff --git a/src/SendGrid/Helpers/Mail/Model/FooterSettings.cs b/src/SendGrid/Helpers/Mail/Model/FooterSettings.cs index 92af9487c..1d304cc1d 100644 --- a/src/SendGrid/Helpers/Mail/Model/FooterSettings.cs +++ b/src/SendGrid/Helpers/Mail/Model/FooterSettings.cs @@ -3,32 +3,52 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. // +#if NETSTANDARD2_0 +using System.Text.Json.Serialization; +#else using Newtonsoft.Json; +#endif namespace SendGrid.Helpers.Mail { /// /// The default footer that you would like appended to the bottom of every email. /// +#if NETSTANDARD2_0 + // Globally defined by setting ReferenceHandler on the JsonSerializerOptions object +#else [JsonObject(IsReference = false)] +#endif public class FooterSettings { /// /// Gets or sets a value indicating whether this setting is enabled. /// +#if NETSTANDARD2_0 + [JsonPropertyName("enable")] +#else [JsonProperty(PropertyName = "enable")] +#endif public bool Enable { get; set; } /// /// Gets or sets the plain text content of your footer. /// +#if NETSTANDARD2_0 + [JsonPropertyName("text")] +#else [JsonProperty(PropertyName = "text")] +#endif public string Text { get; set; } /// /// Gets or sets the HTML content of your footer. /// +#if NETSTANDARD2_0 + [JsonPropertyName("html")] +#else [JsonProperty(PropertyName = "html")] +#endif public string Html { get; set; } } } diff --git a/src/SendGrid/Helpers/Mail/Model/Ganalytics.cs b/src/SendGrid/Helpers/Mail/Model/Ganalytics.cs index c2a0413de..65d75c47e 100644 --- a/src/SendGrid/Helpers/Mail/Model/Ganalytics.cs +++ b/src/SendGrid/Helpers/Mail/Model/Ganalytics.cs @@ -3,50 +3,82 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. // +#if NETSTANDARD2_0 +using System.Text.Json.Serialization; +#else using Newtonsoft.Json; +#endif namespace SendGrid.Helpers.Mail { /// /// Allows you to enable tracking provided by Google Analytics. /// +#if NETSTANDARD2_0 + // Globally defined by setting ReferenceHandler on the JsonSerializerOptions object +#else [JsonObject(IsReference = false)] +#endif public class Ganalytics { /// /// Gets or sets a value indicating whether this setting is enabled. /// +#if NETSTANDARD2_0 + [JsonPropertyName("enable")] +#else [JsonProperty(PropertyName = "enable")] +#endif public bool? Enable { get; set; } /// /// Gets or sets the name of the referrer source (e.g. Google, SomeDomain.com, or Marketing Email). /// +#if NETSTANDARD2_0 + [JsonPropertyName("utm_source")] +#else [JsonProperty(PropertyName = "utm_source")] +#endif public string UtmSource { get; set; } /// /// Gets or sets the name of the marketing medium (e.g. Email). /// +#if NETSTANDARD2_0 + [JsonPropertyName("utm_medium")] +#else [JsonProperty(PropertyName = "utm_medium")] +#endif public string UtmMedium { get; set; } /// /// Gets or sets the identification of any paid keywords. /// +#if NETSTANDARD2_0 + [JsonPropertyName("utm_term")] +#else [JsonProperty(PropertyName = "utm_term")] +#endif public string UtmTerm { get; set; } /// /// Gets or sets the differentiation of your campaign from advertisements. /// +#if NETSTANDARD2_0 + [JsonPropertyName("utm_content")] +#else [JsonProperty(PropertyName = "utm_content")] +#endif public string UtmContent { get; set; } /// /// Gets or sets the name of the campaign. /// +#if NETSTANDARD2_0 + [JsonPropertyName("utm_campaign")] +#else [JsonProperty(PropertyName = "utm_campaign")] +#endif public string UtmCampaign { get; set; } } } diff --git a/src/SendGrid/Helpers/Mail/Model/HtmlContent.cs b/src/SendGrid/Helpers/Mail/Model/HtmlContent.cs index 893afcc3d..c2caf9303 100644 --- a/src/SendGrid/Helpers/Mail/Model/HtmlContent.cs +++ b/src/SendGrid/Helpers/Mail/Model/HtmlContent.cs @@ -3,14 +3,22 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. // +#if NETSTANDARD2_0 +using System.Text.Json.Serialization; +#else using Newtonsoft.Json; +#endif namespace SendGrid.Helpers.Mail.Model { /// /// Helper class for plain html mime types. /// +#if NETSTANDARD2_0 + // Globally defined by setting ReferenceHandler on the JsonSerializerOptions object +#else [JsonObject(IsReference = false)] +#endif public class HtmlContent : Content { /// diff --git a/src/SendGrid/Helpers/Mail/Model/JsonConverters.cs b/src/SendGrid/Helpers/Mail/Model/JsonConverters.cs index b199af649..be10b8027 100644 --- a/src/SendGrid/Helpers/Mail/Model/JsonConverters.cs +++ b/src/SendGrid/Helpers/Mail/Model/JsonConverters.cs @@ -3,7 +3,12 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. // +#if NETSTANDARD2_0 +using System.Text.Json; +using System.Text.Json.Serialization; +#else using Newtonsoft.Json; +#endif using System; using System.Collections.Generic; using System.Linq; @@ -18,16 +23,47 @@ namespace SendGrid.Helpers.Mail /// /// Removes duplicates when writing the JSON representation of the object. /// - public class RemoveDuplicatesConverter : JsonConverter + public class RemoveDuplicatesConverter : +#if NETSTANDARD2_0 + JsonConverter> +#else + JsonConverter +#endif { + +#if NETSTANDARD2_0 + private static readonly JsonConverter s_defaultConverter = + (JsonConverter)JsonSerializerOptions.Default.GetConverter(typeof(T)); +#endif + /// /// Determines whether this instance can convert the specified object type. /// public override bool CanConvert(Type objectType) { - return typeof(IEnumerable).GetTypeInfo().IsAssignableFrom(objectType.GetTypeInfo()); + var rc = typeof(IEnumerable).GetTypeInfo().IsAssignableFrom(objectType.GetTypeInfo()); + return rc; + } + +#if NETSTANDARD2_0 + /// + /// Writes the JSON representation of the object. + /// + public override void Write(Utf8JsonWriter writer, IEnumerable value, JsonSerializerOptions options) { + writer.WriteStartArray(); + foreach (T item in value.Distinct()) { + s_defaultConverter.Write(writer, item, options); + } + writer.WriteEndArray(); } + /// + /// Reads the JSON representation of the object. + /// + public override IEnumerable Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { + throw new NotImplementedException(); + } +#else /// /// Writes the JSON representation of the object. /// @@ -56,5 +92,6 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist { throw new NotImplementedException(); } +#endif } } diff --git a/src/SendGrid/Helpers/Mail/Model/MailSettings.cs b/src/SendGrid/Helpers/Mail/Model/MailSettings.cs index 95cf3456e..2a23d2597 100644 --- a/src/SendGrid/Helpers/Mail/Model/MailSettings.cs +++ b/src/SendGrid/Helpers/Mail/Model/MailSettings.cs @@ -3,63 +3,103 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. // +#if NETSTANDARD2_0 +using System.Text.Json.Serialization; +#else using Newtonsoft.Json; +#endif namespace SendGrid.Helpers.Mail { /// /// A collection of different mail settings that you can use to specify how you would like this email to be handled. /// +#if NETSTANDARD2_0 + // Globally defined by setting ReferenceHandler on the JsonSerializerOptions object +#else [JsonObject(IsReference = false)] +#endif public class MailSettings { /// /// Gets or sets the address specified in the mail_settings.bcc object will receive a blind carbon copy (BCC) of the very first personalization defined in the personalizations array. /// +#if NETSTANDARD2_0 + [JsonPropertyName("bcc")] +#else [JsonProperty(PropertyName = "bcc")] +#endif public BCCSettings BccSettings { get; set; } /// /// Gets or sets the bypass of all unsubscribe groups and suppressions to ensure that the email is delivered to every single recipient. This should only be used in emergencies when it is absolutely necessary that every recipient receives your email. Ex: outage emails, or forgot password emails. /// +#if NETSTANDARD2_0 + [JsonPropertyName("bypass_list_management")] +#else [JsonProperty(PropertyName = "bypass_list_management")] +#endif public BypassListManagement BypassListManagement { get; set; } /// /// Gets or sets the bypass of spam report list to ensure that the email is delivered to recipients. Bounce and unsubscribe lists will still be checked; addresses on these other lists will not receive the message. /// +#if NETSTANDARD2_0 + [JsonPropertyName("bypass_spam_management")] +#else [JsonProperty(PropertyName = "bypass_spam_management")] +#endif public BypassSpamManagement BypassSpamManagement { get; set; } /// /// Gets or sets the bypass the bounce list to ensure that the email is delivered to recipients. Spam report and unsubscribe lists will still be checked; addresses on these other lists will not receive the message. /// +#if NETSTANDARD2_0 + [JsonPropertyName("bypass_bounce_management")] +#else [JsonProperty(PropertyName = "bypass_bounce_management")] +#endif public BypassBounceManagement BypassBounceManagement { get; set; } /// /// Gets or sets the bypass the global unsubscribe list to ensure that the email is delivered to recipients. Bounce and spam report lists will still be checked; addresses on these other lists will not receive the message. This filter applies only to global unsubscribes and will not bypass group unsubscribes. /// +#if NETSTANDARD2_0 + [JsonPropertyName("bypass_unsubscribe_management")] +#else [JsonProperty(PropertyName = "bypass_unsubscribe_management")] +#endif public BypassUnsubscribeManagement BypassUnsubscribeManagement { get; set; } /// /// Gets or sets the default footer that you would like appended to the bottom of every email. /// +#if NETSTANDARD2_0 + [JsonPropertyName("footer")] +#else [JsonProperty(PropertyName = "footer")] +#endif public FooterSettings FooterSettings { get; set; } /// /// Gets or sets the ability to send a test email to ensure that your request body is valid and formatted correctly. For more information, please see our Classroom. /// https://sendgrid.com/docs/Classroom/Send/v3_Mail_Send/sandbox_mode.html. /// +#if NETSTANDARD2_0 + [JsonPropertyName("sandbox_mode")] +#else [JsonProperty(PropertyName = "sandbox_mode")] +#endif public SandboxMode SandboxMode { get; set; } /// /// Gets or sets the ability to test the content of your email for spam. /// +#if NETSTANDARD2_0 + [JsonPropertyName("spam_check")] +#else [JsonProperty(PropertyName = "spam_check")] +#endif public SpamCheck SpamCheck { get; set; } } } diff --git a/src/SendGrid/Helpers/Mail/Model/OpenTracking.cs b/src/SendGrid/Helpers/Mail/Model/OpenTracking.cs index f869686bc..b2a586954 100644 --- a/src/SendGrid/Helpers/Mail/Model/OpenTracking.cs +++ b/src/SendGrid/Helpers/Mail/Model/OpenTracking.cs @@ -3,26 +3,42 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. // +#if NETSTANDARD2_0 +using System.Text.Json.Serialization; +#else using Newtonsoft.Json; +#endif namespace SendGrid.Helpers.Mail { /// /// Allows you to track whether the email was opened or not, but including a single pixel image in the body of the content. When the pixel is loaded, we can log that the email was opened. /// +#if NETSTANDARD2_0 + // Globally defined by setting ReferenceHandler on the JsonSerializerOptions object +#else [JsonObject(IsReference = false)] +#endif public class OpenTracking { /// /// Gets or sets a value indicating whether this setting is enabled. /// +#if NETSTANDARD2_0 + [JsonPropertyName("enable")] +#else [JsonProperty(PropertyName = "enable")] +#endif public bool? Enable { get; set; } /// /// Gets or sets the ability to specify a substitution tag that you can insert in the body of your email at a location that you desire. This tag will be replaced by the open tracking pixel. /// +#if NETSTANDARD2_0 + [JsonPropertyName("substitution_tag")] +#else [JsonProperty(PropertyName = "substitution_tag")] +#endif public string SubstitutionTag { get; set; } } } diff --git a/src/SendGrid/Helpers/Mail/Model/Personalization.cs b/src/SendGrid/Helpers/Mail/Model/Personalization.cs index 6da5d2002..50e86de9a 100644 --- a/src/SendGrid/Helpers/Mail/Model/Personalization.cs +++ b/src/SendGrid/Helpers/Mail/Model/Personalization.cs @@ -3,7 +3,11 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. // +#if NETSTANDARD2_0 +using System.Text.Json.Serialization; +#else using Newtonsoft.Json; +#endif using System.Collections.Generic; namespace SendGrid.Helpers.Mail @@ -12,71 +16,115 @@ namespace SendGrid.Helpers.Mail /// An array of messages and their metadata. Each object within personalizations can be thought of as an envelope - it defines who should receive an individual message and how that message should be handled. For more information, please see our documentation on Personalizations. Parameters in personalizations will override the parameters of the same name from the message level. /// https://sendgrid.com/docs/Classroom/Send/v3_Mail_Send/personalizations.html. /// +#if NETSTANDARD2_0 + // Globally defined by setting ReferenceHandler on the JsonSerializerOptions object +#else [JsonObject(IsReference = false)] +#endif public class Personalization { /// /// Gets or sets an array of recipients. Each email object within this array may contain the recipient’s name, but must always contain the recipient’s email. /// +#if NETSTANDARD2_0 + [JsonPropertyName("to")] +#else [JsonProperty(PropertyName = "to", IsReference = false)] +#endif [JsonConverter(typeof(RemoveDuplicatesConverter))] public List Tos { get; set; } /// /// Gets or sets an array of recipients who will receive a copy of your email. Each email object within this array may contain the recipient’s name, but must always contain the recipient’s email. /// +#if NETSTANDARD2_0 + [JsonPropertyName("cc")] +#else [JsonProperty(PropertyName = "cc", IsReference = false)] +#endif [JsonConverter(typeof(RemoveDuplicatesConverter))] public List Ccs { get; set; } /// /// Gets or sets an array of recipients who will receive a blind carbon copy of your email. Each email object within this array may contain the recipient’s name, but must always contain the recipient’s email. /// +#if NETSTANDARD2_0 + [JsonPropertyName("bcc")] +#else [JsonProperty(PropertyName = "bcc", IsReference = false)] +#endif [JsonConverter(typeof(RemoveDuplicatesConverter))] public List Bccs { get; set; } /// /// Gets or sets the from email address. The domain must match the domain of the from email property specified at root level of the request body. /// +#if NETSTANDARD2_0 + [JsonPropertyName("from")] +#else [JsonProperty(PropertyName = "from")] +#endif public EmailAddress From { get; set; } /// /// Gets or sets the subject line of your email. /// +#if NETSTANDARD2_0 + [JsonPropertyName("subject")] +#else [JsonProperty(PropertyName = "subject")] +#endif public string Subject { get; set; } /// /// Gets or sets the object allowing you to specify specific handling instructions for your email. /// +#if NETSTANDARD2_0 + [JsonPropertyName("headers")] +#else [JsonProperty(PropertyName = "headers", IsReference = false)] +#endif public Dictionary Headers { get; set; } /// /// Gets or sets an object following the pattern "substitution_tag":"value to substitute". All are assumed to be strings. These substitutions will apply to the content of your email, in addition to the subject and reply-to parameters. /// You may not include more than 100 substitutions per personalization object, and the total collective size of your substitutions may not exceed 10,000 bytes per personalization object. /// +#if NETSTANDARD2_0 + [JsonPropertyName("substitutions")] +#else [JsonProperty(PropertyName = "substitutions", IsReference = false)] +#endif public Dictionary Substitutions { get; set; } /// /// Gets or sets the values that are specific to this personalization that will be carried along with the email, activity data, and links. Substitutions will not be made on custom arguments. personalizations[x].custom_args will be merged with message level custom_args, overriding any conflicting keys. The combined total size of the resulting custom arguments, after merging, for each personalization may not exceed 10,000 bytes. /// +#if NETSTANDARD2_0 + [JsonPropertyName("custom_args")] +#else [JsonProperty(PropertyName = "custom_args", IsReference = false)] +#endif public Dictionary CustomArgs { get; set; } /// /// Gets or sets a unix timestamp allowing you to specify when you want your email to be sent from Twilio SendGrid. This is not necessary if you want the email to be sent at the time of your API request. /// +#if NETSTANDARD2_0 + [JsonPropertyName("send_at")] +#else [JsonProperty(PropertyName = "send_at")] +#endif public long? SendAt { get; set; } /// /// Gets or sets the template data object following the pattern "template data key":"template data value". All are assumed to be strings. These key value pairs will apply to the content of your template email, in addition to the subject and reply-to parameters. /// +#if NETSTANDARD2_0 + [JsonPropertyName("dynamic_template_data")] +#else [JsonProperty(PropertyName = "dynamic_template_data", IsReference = false, ItemIsReference = false)] +#endif public object TemplateData { get; set; } } } diff --git a/src/SendGrid/Helpers/Mail/Model/SandboxMode.cs b/src/SendGrid/Helpers/Mail/Model/SandboxMode.cs index bf953c56f..9ae8d4cd7 100644 --- a/src/SendGrid/Helpers/Mail/Model/SandboxMode.cs +++ b/src/SendGrid/Helpers/Mail/Model/SandboxMode.cs @@ -3,7 +3,11 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. // +#if NETSTANDARD2_0 +using System.Text.Json.Serialization; +#else using Newtonsoft.Json; +#endif namespace SendGrid.Helpers.Mail { @@ -11,13 +15,21 @@ namespace SendGrid.Helpers.Mail /// This allows you to send a test email to ensure that your request body is valid and formatted correctly. For more information, please see our Classroom. /// https://sendgrid.com/docs/Classroom/Send/v3_Mail_Send/sandbox_mode.html. /// +#if NETSTANDARD2_0 + // Globally defined by setting ReferenceHandler on the JsonSerializerOptions object +#else [JsonObject(IsReference = false)] +#endif public class SandboxMode { /// /// Gets or sets a value indicating whether this setting is enabled. /// +#if NETSTANDARD2_0 + [JsonPropertyName("enable")] +#else [JsonProperty(PropertyName = "enable")] +#endif public bool? Enable { get; set; } } } diff --git a/src/SendGrid/Helpers/Mail/Model/SpamCheck.cs b/src/SendGrid/Helpers/Mail/Model/SpamCheck.cs index 0f54f57f7..a430ab28f 100644 --- a/src/SendGrid/Helpers/Mail/Model/SpamCheck.cs +++ b/src/SendGrid/Helpers/Mail/Model/SpamCheck.cs @@ -3,32 +3,52 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. // +#if NETSTANDARD2_0 +using System.Text.Json.Serialization; +#else using Newtonsoft.Json; +#endif namespace SendGrid.Helpers.Mail { /// /// This allows you to test the content of your email for spam. /// +#if NETSTANDARD2_0 + // Globally defined by setting ReferenceHandler on the JsonSerializerOptions object +#else [JsonObject(IsReference = false)] +#endif public class SpamCheck { /// /// Gets or sets a value indicating whether this setting is enabled. /// +#if NETSTANDARD2_0 + [JsonPropertyName("enable")] +#else [JsonProperty(PropertyName = "enable")] +#endif public bool? Enable { get; set; } /// /// Gets or sets the threshold used to determine if your content qualifies as spam on a scale from 1 to 10, with 10 being most strict, or most likely to be considered as spam. /// +#if NETSTANDARD2_0 + [JsonPropertyName("threshold")] +#else [JsonProperty(PropertyName = "threshold")] +#endif public int? Threshold { get; set; } /// /// Gets or sets an Inbound Parse URL that you would like a copy of your email along with the spam report to be sent to. The post_to_url parameter must start with http:// or https://. /// +#if NETSTANDARD2_0 + [JsonPropertyName("post_to_url")] +#else [JsonProperty(PropertyName = "post_to_url")] +#endif public string PostToUrl { get; set; } } } diff --git a/src/SendGrid/Helpers/Mail/Model/SubscriptionTracking.cs b/src/SendGrid/Helpers/Mail/Model/SubscriptionTracking.cs index af70ea973..8aef80e3b 100644 --- a/src/SendGrid/Helpers/Mail/Model/SubscriptionTracking.cs +++ b/src/SendGrid/Helpers/Mail/Model/SubscriptionTracking.cs @@ -3,38 +3,62 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. // +#if NETSTANDARD2_0 +using System.Text.Json.Serialization; +#else using Newtonsoft.Json; +#endif namespace SendGrid.Helpers.Mail { /// /// Allows you to insert a subscription management link at the bottom of the text and html bodies of your email. If you would like to specify the location of the link within your email, you may use the substitution_tag. /// +#if NETSTANDARD2_0 + // Globally defined by setting ReferenceHandler on the JsonSerializerOptions object +#else [JsonObject(IsReference = false)] +#endif public class SubscriptionTracking { /// /// Gets or sets a value indicating whether this setting is enabled. /// +#if NETSTANDARD2_0 + [JsonPropertyName("enable")] +#else [JsonProperty(PropertyName = "enable")] +#endif public bool Enable { get; set; } /// /// Gets or sets the text to be appended to the email, with the subscription tracking link. You may control where the link is by using the tag (percent symbol) (percent symbol). /// +#if NETSTANDARD2_0 + [JsonPropertyName("text")] +#else [JsonProperty(PropertyName = "text")] +#endif public string Text { get; set; } /// /// Gets or sets the HTML to be appended to the email, with the subscription tracking link. You may control where the link is by using the tag (percent symbol) (percent symbol). /// +#if NETSTANDARD2_0 + [JsonPropertyName("html")] +#else [JsonProperty(PropertyName = "html")] +#endif public string Html { get; set; } /// /// Gets or sets a tag that will be replaced with the unsubscribe URL. for example: [unsubscribe_url]. If this parameter is used, it will override both the textand html parameters. The URL of the link will be placed at the substitution tag’s location, with no additional formatting. /// +#if NETSTANDARD2_0 + [JsonPropertyName("substitution_tag")] +#else [JsonProperty(PropertyName = "substitution_tag")] +#endif public string SubstitutionTag { get; set; } } } diff --git a/src/SendGrid/Helpers/Mail/Model/TrackingSettings.cs b/src/SendGrid/Helpers/Mail/Model/TrackingSettings.cs index b0dc22fac..06310d406 100644 --- a/src/SendGrid/Helpers/Mail/Model/TrackingSettings.cs +++ b/src/SendGrid/Helpers/Mail/Model/TrackingSettings.cs @@ -3,38 +3,62 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. // +#if NETSTANDARD2_0 +using System.Text.Json.Serialization; +#else using Newtonsoft.Json; +#endif namespace SendGrid.Helpers.Mail { /// /// Settings to determine how you would like to track the metrics of how your recipients interact with your email. /// +#if NETSTANDARD2_0 + // Globally defined by setting ReferenceHandler on the JsonSerializerOptions object +#else [JsonObject(IsReference = false)] +#endif public class TrackingSettings { /// /// Gets or sets tracking whether a recipient clicked a link in your email. /// +#if NETSTANDARD2_0 + [JsonPropertyName("click_tracking")] +#else [JsonProperty(PropertyName = "click_tracking")] +#endif public ClickTracking ClickTracking { get; set; } /// /// Gets or sets tracking whether the email was opened or not, but including a single pixel image in the body of the content. When the pixel is loaded, we can log that the email was opened. /// +#if NETSTANDARD2_0 + [JsonPropertyName("open_tracking")] +#else [JsonProperty(PropertyName = "open_tracking")] +#endif public OpenTracking OpenTracking { get; set; } /// /// Gets or sets a subscription management link at the bottom of the text and html bodies of your email. If you would like to specify the location of the link within your email, you may use the substitution_tag. /// +#if NETSTANDARD2_0 + [JsonPropertyName("subscription_tracking")] +#else [JsonProperty(PropertyName = "subscription_tracking")] +#endif public SubscriptionTracking SubscriptionTracking { get; set; } /// /// Gets or sets tracking provided by Google Analytics. /// +#if NETSTANDARD2_0 + [JsonPropertyName("ganalytics")] +#else [JsonProperty(PropertyName = "ganalytics")] +#endif public Ganalytics Ganalytics { get; set; } } } diff --git a/src/SendGrid/Helpers/Mail/SendGridMessage.cs b/src/SendGrid/Helpers/Mail/SendGridMessage.cs index 4c62a01f3..42ba74fa8 100644 --- a/src/SendGrid/Helpers/Mail/SendGridMessage.cs +++ b/src/SendGrid/Helpers/Mail/SendGridMessage.cs @@ -3,14 +3,19 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. // +#if NETSTANDARD2_0 +using System.Text.Json; +using System.Text.Json.Serialization; +#else +using System.Text; using Newtonsoft.Json; +#endif using SendGrid.Helpers.Mail.Model; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; -using System.Text; using System.Threading; using System.Threading.Tasks; @@ -19,32 +24,52 @@ namespace SendGrid.Helpers.Mail /// /// Class SendGridMessage builds an object that sends an email through Twilio SendGrid. /// +#if NETSTANDARD2_0 + // Globally defined by setting ReferenceHandler on the JsonSerializerOptions object +#else [JsonObject(IsReference = false)] +#endif public class SendGridMessage { /// /// Gets or sets an email object containing the email address and name of the sender. Unicode encoding is not supported for the from field. /// +#if NETSTANDARD2_0 + [JsonPropertyName("from")] +#else [JsonProperty(PropertyName = "from")] +#endif public EmailAddress From { get; set; } /// /// Gets or sets the subject of your email. This may be overridden by personalizations[x].subject. /// +#if NETSTANDARD2_0 + [JsonPropertyName("subject")] +#else [JsonProperty(PropertyName = "subject")] +#endif public string Subject { get; set; } /// /// Gets or sets a list of messages and their metadata. Each object within personalizations can be thought of as an envelope - it defines who should receive an individual message and how that message should be handled. For more information, please see our documentation on Personalizations. Parameters in personalizations will override the parameters of the same name from the message level. /// https://sendgrid.com/docs/Classroom/Send/v3_Mail_Send/personalizations.html. /// +#if NETSTANDARD2_0 + [JsonPropertyName("personalizations")] +#else [JsonProperty(PropertyName = "personalizations", IsReference = false)] +#endif public List Personalizations { get; set; } /// /// Gets or sets a list in which you may specify the content of your email. You can include multiple mime types of content, but you must specify at least one. To include more than one mime type, simply add another object to the array containing the type and value parameters. If included, text/plain and text/html must be the first indices of the array in this order. If you choose to include the text/plain or text/html mime types, they must be the first indices of the content array in the order text/plain, text/html.*Content is NOT mandatory if you using a transactional template and have defined the template_id in the Request. /// +#if NETSTANDARD2_0 + [JsonPropertyName("content")] +#else [JsonProperty(PropertyName = "content", IsReference = false)] +#endif public List Contents { get; set; } /// @@ -62,86 +87,142 @@ public class SendGridMessage /// /// Gets or sets a list of objects in which you can specify any attachments you want to include. /// +#if NETSTANDARD2_0 + [JsonPropertyName("attachments")] +#else [JsonProperty(PropertyName = "attachments", IsReference = false)] +#endif public List Attachments { get; set; } /// /// Gets or sets the id of a template that you would like to use. If you use a template that contains content and a subject (either text or html), you do not need to specify those in the respective personalizations or message level parameters. /// +#if NETSTANDARD2_0 + [JsonPropertyName("template_id")] +#else [JsonProperty(PropertyName = "template_id")] +#endif public string TemplateId { get; set; } /// /// Gets or sets an object containing key/value pairs of header names and the value to substitute for them. You must ensure these are properly encoded if they contain unicode characters. Must not be any of the following reserved headers: x-sg-id, x-sg-eid, received, dkim-signature, Content-Type, Content-Transfer-Encoding, To, From, Subject, Reply-To, CC, BCC. /// +#if NETSTANDARD2_0 + [JsonPropertyName("headers")] +#else [JsonProperty(PropertyName = "headers", IsReference = false)] +#endif public Dictionary Headers { get; set; } /// /// Gets or sets an object of key/value pairs that define large blocks of content that can be inserted into your emails using substitution tags. /// +#if NETSTANDARD2_0 + [JsonPropertyName("sections")] +#else [JsonProperty(PropertyName = "sections", IsReference = false)] +#endif public Dictionary Sections { get; set; } /// /// Gets or sets a list of category names for this message. Each category name may not exceed 255 characters. You cannot have more than 10 categories per request. /// +#if NETSTANDARD2_0 + [JsonPropertyName("categories")] +#else [JsonProperty(PropertyName = "categories", IsReference = false)] +#endif public List Categories { get; set; } /// /// Gets or sets values that are specific to the entire send that will be carried along with the email and its activity data. Substitutions will not be made on custom arguments, so any string that is entered into this parameter will be assumed to be the custom argument that you would like to be used. This parameter is overridden by any conflicting personalizations[x].custom_args if that parameter has been defined. If personalizations[x].custom_args has been defined but does not conflict with the values defined within this parameter, the two will be merged. The combined total size of these custom arguments may not exceed 10,000 bytes. /// +#if NETSTANDARD2_0 + [JsonPropertyName("custom_args")] +#else [JsonProperty(PropertyName = "custom_args", IsReference = false)] +#endif public Dictionary CustomArgs { get; set; } /// /// Gets or sets a unix timestamp allowing you to specify when you want your email to be sent from SendGrid. This is not necessary if you want the email to be sent at the time of your API request. /// +#if NETSTANDARD2_0 + [JsonPropertyName("send_at")] +#else [JsonProperty(PropertyName = "send_at")] +#endif public long? SendAt { get; set; } /// /// Gets or sets an object allowing you to specify how to handle unsubscribes. /// +#if NETSTANDARD2_0 + [JsonPropertyName("asm")] +#else [JsonProperty(PropertyName = "asm")] +#endif public ASM Asm { get; set; } /// /// Gets or sets an ID that represents a batch of emails (AKA multiple sends of the same email) to be associated to each other for scheduling. Including a batch_id in your request allows you to include this email in that batch, and also enables you to cancel or pause the delivery of that entire batch. For more information, please read about Cancel Scheduled Sends. /// https://sendgrid.com/docs/API_Reference/Web_API_v3/cancel_schedule_send.html. /// +#if NETSTANDARD2_0 + [JsonPropertyName("batch_id")] +#else [JsonProperty(PropertyName = "batch_id")] +#endif public string BatchId { get; set; } /// /// Gets or sets the IP Pool that you would like to send this email from. /// +#if NETSTANDARD2_0 + [JsonPropertyName("ip_pool_name")] +#else [JsonProperty(PropertyName = "ip_pool_name")] +#endif public string IpPoolName { get; set; } /// /// Gets or sets a collection of different mail settings that you can use to specify how you would like this email to be handled. /// +#if NETSTANDARD2_0 + [JsonPropertyName("mail_settings")] +#else [JsonProperty(PropertyName = "mail_settings")] +#endif public MailSettings MailSettings { get; set; } /// /// Gets or sets settings to determine how you would like to track the metrics of how your recipients interact with your email. /// +#if NETSTANDARD2_0 + [JsonPropertyName("tracking_settings")] +#else [JsonProperty(PropertyName = "tracking_settings")] +#endif public TrackingSettings TrackingSettings { get; set; } /// /// Gets or sets an email object containing the email address and name of the individual who should receive responses to your email. /// +#if NETSTANDARD2_0 + [JsonPropertyName("reply_to")] +#else [JsonProperty(PropertyName = "reply_to")] +#endif public EmailAddress ReplyTo { get; set; } /// /// Gets or sets a list of objects of email objects containing the email address and name of the individuals who should receive responses to your email. /// +#if NETSTANDARD2_0 + [JsonPropertyName("reply_to_list")] +#else [JsonProperty(PropertyName = "reply_to_list", IsReference = false)] +#endif public List ReplyTos { get; set; } /// @@ -1185,6 +1266,14 @@ public string Serialize(bool useDefaultSerialization = true) } } +#if NETSTANDARD2_0 + var jsonSerializerOptions = new JsonSerializerOptions + { + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + }; + + return JsonSerializer.Serialize(this, jsonSerializerOptions); +#else var jsonSerializerSettings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, @@ -1212,6 +1301,7 @@ public string Serialize(bool useDefaultSerialization = true) } return textWriter.ToString(); +#endif } /// @@ -1221,6 +1311,14 @@ public string Serialize(bool useDefaultSerialization = true) /// The SendGrid.Helpers.Mail.SendGridMessage instance created from the JSON object. public static SendGridMessage Deserialize(string json) { +#if NETSTANDARD2_0 + var jsonSerializerOptions = new JsonSerializerOptions + { + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + }; + + return JsonSerializer.Deserialize(json, jsonSerializerOptions); +#else var jsonSerializerSettings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, @@ -1235,6 +1333,7 @@ public static SendGridMessage Deserialize(string json) SendGridMessage message = jsonSerializer.Deserialize(reader); return message; +#endif } } } diff --git a/src/SendGrid/Permissions/SendGridClientExtensions.cs b/src/SendGrid/Permissions/SendGridClientExtensions.cs index d86c361ba..65232e32e 100644 --- a/src/SendGrid/Permissions/SendGridClientExtensions.cs +++ b/src/SendGrid/Permissions/SendGridClientExtensions.cs @@ -1,7 +1,13 @@ using System.Linq; using System.Threading.Tasks; +#if NETSTANDARD2_0 +using System.Text.Json; +using System.Text.Json.Nodes; + +#else using Newtonsoft.Json; using Newtonsoft.Json.Linq; +#endif namespace SendGrid.Permissions { @@ -20,8 +26,13 @@ public static async Task CreateMaskedPermissionsBuil { var response = await client.RequestAsync(method: SendGridClient.Method.GET, urlPath: "scopes"); var body = await response.DeserializeResponseBodyAsync(); +#if NETSTANDARD2_0 + var userScopesJArray = ((JsonElement)body["scopes"]).EnumerateArray(); + var includedScopes = userScopesJArray.Select(z => z.GetString()).ToArray(); +#else var userScopesJArray = (body["scopes"] as JArray); var includedScopes = userScopesJArray.Values().ToArray(); +#endif var builder = new SendGridPermissionsBuilder(); builder.Exclude(scope => !includedScopes.Contains(scope)); return builder; @@ -42,7 +53,11 @@ public static async Task CreateApiKey(this ISendGridClient client, Sen name, scopes }; +#if NETSTANDARD2_0 + var data = JsonSerializer.Serialize(payload); +#else var data = JsonConvert.SerializeObject(payload); +#endif var response = await client.RequestAsync(method: SendGridClient.Method.POST, urlPath: "api_keys", requestBody: data); return response; } diff --git a/src/SendGrid/Response.cs b/src/SendGrid/Response.cs index 0eb8255df..306728fb5 100644 --- a/src/SendGrid/Response.cs +++ b/src/SendGrid/Response.cs @@ -3,7 +3,11 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. // +#if NETSTANDARD2_0 +using System.Text.Json; +#else using Newtonsoft.Json; +#endif using System.Collections.Generic; using System.Linq; using System.Net; @@ -118,7 +122,11 @@ public virtual async Task> DeserializeResponseBodyAs } var stringContent = await content.ReadAsStringAsync().ConfigureAwait(false); +#if NETSTANDARD2_0 + var dsContent = JsonSerializer.Deserialize>(stringContent); +#else var dsContent = JsonConvert.DeserializeObject>(stringContent); +#endif return dsContent; } diff --git a/src/SendGrid/SendGrid.csproj b/src/SendGrid/SendGrid.csproj index 0ca4b9254..a3e499868 100644 --- a/src/SendGrid/SendGrid.csproj +++ b/src/SendGrid/SendGrid.csproj @@ -45,10 +45,18 @@ - + + + + + + + + + diff --git a/src/SendGrid/SendGrid.sln b/src/SendGrid/SendGrid.sln new file mode 100644 index 000000000..966737173 --- /dev/null +++ b/src/SendGrid/SendGrid.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.5.002.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SendGrid", "SendGrid.csproj", "{3372B2AA-132B-4588-B7CF-57C056C8E745}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {3372B2AA-132B-4588-B7CF-57C056C8E745}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3372B2AA-132B-4588-B7CF-57C056C8E745}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3372B2AA-132B-4588-B7CF-57C056C8E745}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3372B2AA-132B-4588-B7CF-57C056C8E745}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {A6EA5161-97F0-408E-8E69-1E3B48D7CE2B} + EndGlobalSection +EndGlobal diff --git a/tests/SendGrid.Extensions.DependencyInjection.Net21Tests/SendGrid.Extensions.DependencyInjection.Net21Tests.csproj b/tests/SendGrid.Extensions.DependencyInjection.Net21Tests/SendGrid.Extensions.DependencyInjection.Net21Tests.csproj new file mode 100644 index 000000000..3b6b7d5cf --- /dev/null +++ b/tests/SendGrid.Extensions.DependencyInjection.Net21Tests/SendGrid.Extensions.DependencyInjection.Net21Tests.csproj @@ -0,0 +1,20 @@ + + + + net8.0 + true + false + + + + + + + + + + + + + + diff --git a/tests/SendGrid.Extensions.DependencyInjection.Net21Tests/ServiceCollectionExtensionsTests.cs b/tests/SendGrid.Extensions.DependencyInjection.Net21Tests/ServiceCollectionExtensionsTests.cs new file mode 100644 index 000000000..c1113dc51 --- /dev/null +++ b/tests/SendGrid.Extensions.DependencyInjection.Net21Tests/ServiceCollectionExtensionsTests.cs @@ -0,0 +1,76 @@ +using System; +using System.Linq; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; +using Xunit; + +namespace SendGrid.Extensions.DependencyInjection.Tests +{ + public class ServiceCollectionExtensionsTests + { + [Fact] + public void TestAddSendGridWithoutApiKey() + { + // Arrange + var services = new ServiceCollection().AddSendGrid(options => { }).Services.BuildServiceProvider(); + + // Act && Assert + Assert.Throws(() => services.GetRequiredService()); + } + + [Fact] + public void TestAddSendGridReturnHttpClientBuilder() + { + // Arrange + var collection = new ServiceCollection(); + + // Act + var builder = collection.AddSendGrid(options => options.ApiKey = "FAKE_API_KEY"); + + // Assert + Assert.NotNull(builder); + Assert.IsAssignableFrom(builder); + } + + [Fact] + public void TestAddSendGridRegisteredWithTransientLifeTime() + { + // Arrange + var collection = new ServiceCollection(); + + // Act + var builder = collection.AddSendGrid(options => options.ApiKey = "FAKE_API_KEY"); + + // Assert + var serviceDescriptor = collection.FirstOrDefault(x => x.ServiceType == typeof(ISendGridClient)); + Assert.NotNull(serviceDescriptor); + Assert.Equal(ServiceLifetime.Transient, serviceDescriptor.Lifetime); + } + + [Fact] + public void TestAddSendGridCanResolveSendGridClientOptions() + { + // Arrange + var services = new ServiceCollection().AddSendGrid(options => options.ApiKey = "FAKE_API_KEY").Services.BuildServiceProvider(); + + // Act + var sendGridClientOptions = services.GetService>(); + + // Assert + Assert.NotNull(sendGridClientOptions); + } + + [Fact] + public void TestAddSendGridCanResolveSendGridClient() + { + // Arrange + var services = new ServiceCollection().AddSendGrid(options => options.ApiKey = "FAKE_API_KEY").Services.BuildServiceProvider(); + + // Act + var sendGrid = services.GetService(); + + // Assert + Assert.NotNull(sendGrid); + } + } +} diff --git a/tests/SendGrid.Extensions.DependencyInjection.Tests/SendGrid.Extensions.DependencyInjection.Tests.csproj b/tests/SendGrid.Extensions.DependencyInjection.Tests/SendGrid.Extensions.DependencyInjection.Tests.csproj index 96da4a46c..053798fdf 100644 --- a/tests/SendGrid.Extensions.DependencyInjection.Tests/SendGrid.Extensions.DependencyInjection.Tests.csproj +++ b/tests/SendGrid.Extensions.DependencyInjection.Tests/SendGrid.Extensions.DependencyInjection.Tests.csproj @@ -1,7 +1,7 @@  - netcoreapp2.1 + net8.0 true false diff --git a/tests/SendGrid.Net21Tests/Helpers/EventWebhook/RequestValidatorTests.cs b/tests/SendGrid.Net21Tests/Helpers/EventWebhook/RequestValidatorTests.cs new file mode 100644 index 000000000..452100deb --- /dev/null +++ b/tests/SendGrid.Net21Tests/Helpers/EventWebhook/RequestValidatorTests.cs @@ -0,0 +1,120 @@ +using Xunit; +using Newtonsoft.Json; +using SendGrid.Helpers.EventWebhook; + +namespace SendGrid.Tests.Helpers.EventWebhook +{ + public class RequestValidatorTests + { + public class EventClass + { + [JsonProperty("email")] + public string Email; + + [JsonProperty("event")] + public string Event; + + [JsonProperty("reason")] + public string Reason; + + [JsonProperty("sg_event_id")] + public string SgEventId; + + [JsonProperty("sg_message_id")] + public string SgMessageId; + + [JsonProperty("smtp-id")] + public string SmtpId; + + [JsonProperty("timestamp")] + public long Timestamp; + } + + private const string PUBLIC_KEY = "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE83T4O/n84iotIvIW4mdBgQ/7dAfSmpqIM8kF9mN1flpVKS3GRqe62gw+2fNNRaINXvVpiglSI8eNEc6wEA3F+g=="; + private const string SIGNATURE = "MEUCIGHQVtGj+Y3LkG9fLcxf3qfI10QysgDWmMOVmxG0u6ZUAiEAyBiXDWzM+uOe5W0JuG+luQAbPIqHh89M15TluLtEZtM="; + private const string TIMESTAMP = "1600112502"; + private string PAYLOAD = JsonConvert.SerializeObject(new[]{ + new EventClass { + Email = "hello@world.com", + Event = "dropped", + Reason = "Bounced Address", + SgEventId = "ZHJvcC0xMDk5NDkxOS1MUnpYbF9OSFN0T0doUTRrb2ZTbV9BLTA", + SgMessageId = "LRzXl_NHStOGhQ4kofSm_A.filterdrecv-p3mdw1-756b745b58-kmzbl-18-5F5FC76C-9.0", + SmtpId = "", + Timestamp = 1600112492, + } + }) + "\r\n"; // Be sure to include the trailing carriage return and newline! + + [Fact] + public void TestVerifySignature() + { + var isValidSignature = Verify( + PUBLIC_KEY, + PAYLOAD, + SIGNATURE, + TIMESTAMP + ); + + Assert.True(isValidSignature); + } + + [Fact] + public void TestBadKey() + { + var isValidSignature = Verify( + "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEqTxd43gyp8IOEto2LdIfjRQrIbsd4SXZkLW6jDutdhXSJCWHw8REntlo7aNDthvj+y7GjUuFDb/R1NGe1OPzpA==", + PAYLOAD, + SIGNATURE, + TIMESTAMP + ); + + Assert.False(isValidSignature); + } + + [Fact] + public void TestBadPayload() + { + var isValidSignature = Verify( + PUBLIC_KEY, + "payload", + SIGNATURE, + TIMESTAMP + ); + + Assert.False(isValidSignature); + } + + [Fact] + public void TestBadSignature() + { + var isValidSignature = Verify( + PUBLIC_KEY, + PAYLOAD, + "MEQCIB3bJQOarffIdM7+MEee+kYAdoViz6RUoScOASwMcXQxAiAcrus/j853JUlVm5qIRfbKBJwJq89znqOTedy3RetXLQ==", + TIMESTAMP + ); + + Assert.False(isValidSignature); + } + + [Fact] + public void TestBadTimestamp() + { + var isValidSignature = Verify( + PUBLIC_KEY, + PAYLOAD, + SIGNATURE, + "timestamp" + ); + + Assert.False(isValidSignature); + } + + private bool Verify(string publicKey, string payload, string signature, string timestamp) + { + var validator = new RequestValidator(); + var ecPublicKey = validator.ConvertPublicKeyToECDSA(publicKey); + return validator.VerifySignature(ecPublicKey, payload, signature, timestamp); + } + } +} diff --git a/tests/SendGrid.Net21Tests/Helpers/Mail/EmailAddressTests.cs b/tests/SendGrid.Net21Tests/Helpers/Mail/EmailAddressTests.cs new file mode 100644 index 000000000..42c737bb4 --- /dev/null +++ b/tests/SendGrid.Net21Tests/Helpers/Mail/EmailAddressTests.cs @@ -0,0 +1,22 @@ +using SendGrid.Helpers.Mail; +using Xunit; + +namespace SendGrid.Tests.Helpers.Mail +{ + public class EmailAddressTests + { + [Fact] + public void TestEmailAddressEquality() + { + var left = new EmailAddress("test1@sendgrid.com", "test"); + var right = new EmailAddress("test1@sendGrid.com", "Test"); + var up = new EmailAddress("test2@sendgrid.com", "test"); + var down = new EmailAddress("test2@sendgrid.com", "Test"); + + Assert.True(left.Equals(left)); + Assert.True(left.Equals(right)); + Assert.False(left.Equals(up)); + Assert.False(left.Equals(down)); + } + } +} diff --git a/tests/SendGrid.Net21Tests/Helpers/Mail/MailHelperTests.cs b/tests/SendGrid.Net21Tests/Helpers/Mail/MailHelperTests.cs new file mode 100644 index 000000000..0b7c16f6f --- /dev/null +++ b/tests/SendGrid.Net21Tests/Helpers/Mail/MailHelperTests.cs @@ -0,0 +1,105 @@ +using SendGrid.Helpers.Mail; +using System.Collections.Generic; +using System.Linq; +using Xunit; + +namespace SendGrid.Tests.Helpers.Mail +{ + public class MailHelperTests + { + [Theory] + [InlineData("Name Of A Person+", "send@grid.com", "Name Of A Person+ < send@grid.com > ")] + [InlineData("", "send@grid.com", " send@grid.com ")] + [InlineData(null, "notAValidEmail", "notAValidEmail")] + public void TestStringToEmail(string expectedName, string expectedEmail, string rf2822Email) + { + var address = MailHelper.StringToEmailAddress(rf2822Email); + Assert.Equal(expectedEmail, address.Email); + Assert.Equal(expectedName, address.Name); + } + + [Fact] + public void TestCreateSingleTemplateEmail() + { + var from = new EmailAddress("from@email.com", "FromName"); + var to = new EmailAddress("to@email.com"); + var templateId = "d-template1"; + var dynamicTemplateData = new Dictionary + { + { "key1", "value1" } + }; + + var sendGridMessage = MailHelper.CreateSingleTemplateEmail( + from, + to, + templateId, + dynamicTemplateData); + + Assert.Equal(from, sendGridMessage.From); + Assert.Equal(to, sendGridMessage.Personalizations.Single().Tos.Single()); + Assert.Equal(templateId, sendGridMessage.TemplateId); + Assert.Equal(dynamicTemplateData, sendGridMessage.Personalizations.Single().TemplateData); + } + + [Fact] + public void TestCreateSingleTemplateEmailToMultipleRecipients() + { + var from = new EmailAddress("from@email.com", "FromName"); + var tos = new List + { + new EmailAddress("to1@email.com"), + new EmailAddress("to2@email.com") + }; + + var templateId = "d-template2"; + var dynamicTemplateData = new Dictionary + { + { "key1", "value1" } + }; + + var sendGridMessage = MailHelper.CreateSingleTemplateEmailToMultipleRecipients( + from, + tos, + templateId, + dynamicTemplateData); + + Assert.Equal(from, sendGridMessage.From); + Assert.Equal(tos[0], sendGridMessage.Personalizations.ElementAt(0).Tos.Single()); + Assert.Equal(tos[1], sendGridMessage.Personalizations.ElementAt(1).Tos.Single()); + Assert.Equal(templateId, sendGridMessage.TemplateId); + Assert.Equal(dynamicTemplateData, sendGridMessage.Personalizations.ElementAt(0).TemplateData); + Assert.Equal(dynamicTemplateData, sendGridMessage.Personalizations.ElementAt(1).TemplateData); + } + + [Fact] + public void TestCreateMultipleTemplateEmailsToMultipleRecipients() + { + var from = new EmailAddress("from@email.com", "FromName"); + var tos = new List + { + new EmailAddress("to1@email.com"), + new EmailAddress("to2@email.com") + }; + + var templateId = "d-template2"; + var dynamicTemplateData = new List + { + new { key1 = "value1" }, + new { key2 = "value2" } + }; + + var sendGridMessage = MailHelper.CreateMultipleTemplateEmailsToMultipleRecipients( + from, + tos, + templateId, + dynamicTemplateData); + + Assert.Equal(from, sendGridMessage.From); + Assert.Equal(tos[0], sendGridMessage.Personalizations.ElementAt(0).Tos.Single()); + Assert.Equal(tos[1], sendGridMessage.Personalizations.ElementAt(1).Tos.Single()); + Assert.Equal(templateId, sendGridMessage.TemplateId); + Assert.Equal(dynamicTemplateData[0], sendGridMessage.Personalizations.ElementAt(0).TemplateData); + Assert.Equal(dynamicTemplateData[1], sendGridMessage.Personalizations.ElementAt(1).TemplateData); + } + } +} diff --git a/tests/SendGrid.Net21Tests/Helpers/Mail/NonReadableStream.cs b/tests/SendGrid.Net21Tests/Helpers/Mail/NonReadableStream.cs new file mode 100644 index 000000000..d8aa47521 --- /dev/null +++ b/tests/SendGrid.Net21Tests/Helpers/Mail/NonReadableStream.cs @@ -0,0 +1,43 @@ +using System.IO; + +namespace SendGrid.Tests.Helpers.Mail +{ + + public class NonReadableStream : Stream + { + public override bool CanRead => false; + + public override bool CanSeek => throw new System.NotImplementedException(); + + public override bool CanWrite => throw new System.NotImplementedException(); + + public override long Length => throw new System.NotImplementedException(); + + public override long Position { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); } + + public override void Flush() + { + throw new System.NotImplementedException(); + } + + public override int Read(byte[] buffer, int offset, int count) + { + throw new System.NotImplementedException(); + } + + public override long Seek(long offset, SeekOrigin origin) + { + throw new System.NotImplementedException(); + } + + public override void SetLength(long value) + { + throw new System.NotImplementedException(); + } + + public override void Write(byte[] buffer, int offset, int count) + { + throw new System.NotImplementedException(); + } + } +} diff --git a/tests/SendGrid.Net21Tests/Helpers/Mail/SendGridMessageTests.cs b/tests/SendGrid.Net21Tests/Helpers/Mail/SendGridMessageTests.cs new file mode 100644 index 000000000..a84f22146 --- /dev/null +++ b/tests/SendGrid.Net21Tests/Helpers/Mail/SendGridMessageTests.cs @@ -0,0 +1,286 @@ +namespace SendGrid.Tests.Helpers.Mail +{ + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Text; + using System.Threading.Tasks; + using SendGrid.Helpers.Mail; + using Xunit; + + public class SendGridMessageTests + { + #region AddAttachment tests + + [Theory] + [InlineData(null, "foo")] + [InlineData("", "foo")] + [InlineData(" ", "foo")] + [InlineData("foo", null)] + [InlineData("foo", "")] + [InlineData("foo", " ")] + public void SendGridMessage_AddAttachment_Doesnt_Add_If_Filename_Or_Content_Are_Missing(string filename, string content) + { + // Arrange + var sut = new SendGridMessage(); + + // Act + sut.AddAttachment(filename, content); + + // Assert + Assert.Null(sut.Attachments); + } + + [Theory] + [InlineData("filename", "content", null, null, null)] + [InlineData("filename", "content", "type", null, null)] + [InlineData("filename", "content", "type", "disposition", null)] + [InlineData("filename", "content", "type", "disposition", "contentId")] + public void SendGridMessage_AddAttachment_Should_Add_Single_Attachment_To_Attachments(string filename, string content, string type, string disposition, string contentId) + { + // Arrange + var sut = new SendGridMessage(); + + // Act + sut.AddAttachment(filename, content, type, disposition, contentId); + + // Assert + Assert.Single(sut.Attachments); + + var attachment = sut.Attachments.First(); + + Assert.Equal(filename, attachment.Filename); + Assert.Equal(content, attachment.Content); + Assert.Equal(type, attachment.Type); + Assert.Equal(disposition, attachment.Disposition); + Assert.Equal(contentId, attachment.ContentId); + } + + [Fact] + public void SendGridMessage_AddAttachment_Doesnt_Touch_Attachment_Passed_In() + { + // Arrange + var sut = new SendGridMessage(); + + var content = "content"; + var contentId = "contentId"; + var disposition = "disposition"; + var filename = "filename"; + var type = "type"; + + var attachment = new Attachment + { + Content = content, + ContentId = contentId, + Disposition = disposition, + Filename = filename, + Type = type + }; + + // Act + sut.AddAttachment(attachment); + + // Assert + Assert.Single(sut.Attachments); + + var addedAttachment = sut.Attachments.First(); + + Assert.Same(attachment, addedAttachment); + Assert.Equal(attachment.Content, addedAttachment.Content); + Assert.Equal(attachment.ContentId, addedAttachment.ContentId); + Assert.Equal(attachment.Disposition, addedAttachment.Disposition); + Assert.Equal(attachment.Filename, addedAttachment.Filename); + Assert.Equal(attachment.Type, addedAttachment.Type); + } + + #endregion + + #region AddAttachments tests + + [Fact] + public void SendGridMessage_AddAttachments_Adds_All_Attachments() + { + // Arrange + var sut = new SendGridMessage(); + + var attachments = new[] + { + new Attachment(), + new Attachment() + }; + + // Act + sut.AddAttachments(attachments); + + // Assert + Assert.Equal(attachments.Length, sut.Attachments.Count); + } + + [Fact] + public void SendGridMessage_AddAttachments_Doesnt_Use_Provided_List_As_Property() + { + // Arrange + var sut = new SendGridMessage(); + + var attachments = new List + { + new Attachment(), + new Attachment() + }; + + // Act + sut.AddAttachments(attachments); + + // Assert + Assert.Equal(attachments.Count(), sut.Attachments.Count); + Assert.NotSame(attachments, sut.Attachments); + } + + [Fact] + public void SendGridMessage_AddAttachments_Doesnt_Touch_Attachments_Passed_In() + { + // Arrange + var sut = new SendGridMessage(); + + var content = "content"; + var contentId = "contentId"; + var disposition = "disposition"; + var filename = "filename"; + var type = "type"; + + var attachment = new Attachment + { + Content = content, + ContentId = contentId, + Disposition = disposition, + Filename = filename, + Type = type + }; + + var attachments = new[] { attachment }; + + // Act + sut.AddAttachments(attachments); + + // Assert + Assert.Single(sut.Attachments); + + var addedAttachment = sut.Attachments.First(); + + Assert.Same(attachment, addedAttachment); + Assert.Equal(attachment.Content, addedAttachment.Content); + Assert.Equal(attachment.ContentId, addedAttachment.ContentId); + Assert.Equal(attachment.Disposition, addedAttachment.Disposition); + Assert.Equal(attachment.Filename, addedAttachment.Filename); + Assert.Equal(attachment.Type, addedAttachment.Type); + } + + #endregion + + #region AddAttachmentAsync tests + + [Fact] + public async Task SendGridMessage_AddAttachmentAsync_Doesnt_Read_Non_Readable_Streams() + { + // Arrange + var sut = new SendGridMessage(); + + var stream = new NonReadableStream(); + + // Act + await sut.AddAttachmentAsync(null, stream); + + // Assert + Assert.Null(sut.Attachments); + } + + [Fact] + public async Task SendGridMessage_AddAttachmentAsync_Adds_Base64_Content_Of_Stream() + { + // Arrange + var sut = new SendGridMessage(); + + var content = "hello world"; + var contentBytes = Encoding.UTF8.GetBytes(content); + var base64EncodedContent = Convert.ToBase64String(contentBytes); + var stream = new MemoryStream(contentBytes); + + // Act + await sut.AddAttachmentAsync("filename", stream); + + // Assert + Assert.Single(sut.Attachments); + + var attachment = sut.Attachments.First(); + + Assert.Equal(attachment.Content, base64EncodedContent); + } + + [Theory] + [InlineData(null, "foo")] + [InlineData("", "foo")] + [InlineData(" ", "foo")] + public async Task SendGridMessage_AddAttachmentAsync_Doesnt_Add_If_Filename_Is_Missing(string filename, string content) + { + // Arrange + var sut = new SendGridMessage(); + + var contentBytes = Encoding.UTF8.GetBytes(content); + var base64EncodedContent = Convert.ToBase64String(contentBytes); + var contentStream = new MemoryStream(contentBytes); + + // Act + await sut.AddAttachmentAsync(filename, contentStream); + + // Assert + Assert.Null(sut.Attachments); + } + + [Fact] + public async Task SendGridMessage_AddAttachmentAsync_Doesnt_Add_If_Content_Stream_Is_Missing() + { + // Arrange + var sut = new SendGridMessage(); + + Stream contentStream = null; + + // Act + await sut.AddAttachmentAsync("filename", contentStream); + + // Assert + Assert.Null(sut.Attachments); + } + + [Theory] + [InlineData("filename", "content", null, null, null)] + [InlineData("filename", "content", "type", null, null)] + [InlineData("filename", "content", "type", "disposition", null)] + [InlineData("filename", "content", "type", "disposition", "contentId")] + public async Task SendGridMessage_AddAttachmentAsync_Should_Add_Single_Attachment_To_Attachments(string filename, string content, string type, string disposition, string contentId) + { + // Arrange + var sut = new SendGridMessage(); + + var contentBytes = Encoding.UTF8.GetBytes(content); + var base64EncodedContent = Convert.ToBase64String(contentBytes); + var contentStream = new MemoryStream(contentBytes); + + // Act + await sut.AddAttachmentAsync(filename, contentStream, type, disposition, contentId); + + // Assert + Assert.Single(sut.Attachments); + + var addedAttachment = sut.Attachments.First(); + + Assert.Equal(base64EncodedContent, addedAttachment.Content); + Assert.Equal(contentId, addedAttachment.ContentId); + Assert.Equal(disposition, addedAttachment.Disposition); + Assert.Equal(filename, addedAttachment.Filename); + Assert.Equal(type, addedAttachment.Type); + } + + #endregion + } +} diff --git a/tests/SendGrid.Net21Tests/Integration.cs b/tests/SendGrid.Net21Tests/Integration.cs new file mode 100644 index 000000000..6be4e0f6f --- /dev/null +++ b/tests/SendGrid.Net21Tests/Integration.cs @@ -0,0 +1,6330 @@ +namespace SendGrid.Tests +{ + using System; + using System.Collections.Generic; + using System.Net; + using System.Net.Http; + using System.Text; + using System.Threading; + using System.Threading.Tasks; + using Newtonsoft.Json; + using Reliability; + using SendGrid.Helpers.Errors.Model; + using SendGrid.Helpers.Mail; + using SendGrid.Helpers.Reliability; + using Xunit; + using Xunit.Abstractions; + + public class IntegrationFixture + { + public string apiKey = "SG.12345678901234567890123456789012"; + } + + public class Integration : IClassFixture + { + private const string SkipConfigureApiKey = "API key must be configured"; // change to null after configuring API key + + IntegrationFixture fixture; + private readonly ITestOutputHelper output; + + public Integration(IntegrationFixture fixture, ITestOutputHelper output) + { + this.fixture = fixture; + this.output = output; + } + + private SendGridClient GetClient(string mockStatusCode) + { + var headers = new Dictionary { { "X-Mock", mockStatusCode } }; + return new SendGridClient(fixture.apiKey, null, headers); + } + + // Base case for sending a single email + [Fact(Skip = SkipConfigureApiKey)] + public void TestSendSingleEmailWithHelper() + { + var msg = new SendGridMessage(); + msg.SetFrom(new EmailAddress("test@example.com")); + msg.AddTo(new EmailAddress("test@example.com")); + msg.SetSubject("Hello World from the Twilio SendGrid CSharp Library"); + msg.AddContent(MimeType.Text, "Textual content"); + msg.AddContent(MimeType.Html, "HTML content"); + Assert.Equal("{\"from\":{\"email\":\"test@example.com\"},\"personalizations\":[{\"to\":[{\"email\":\"test@example.com\"}],\"subject\":\"Hello World from the Twilio SendGrid CSharp Library\"}],\"content\":[{\"type\":\"text/plain\",\"value\":\"Textual content\"},{\"type\":\"text/html\",\"value\":\"HTML content\"}]}", msg.Serialize()); + + // Test Hello World Example + var from = new EmailAddress("test@example.com", "Example User"); + var subject = "Sending with Twilio SendGrid is Fun"; + var to = new EmailAddress("test@example.com", "Example User"); + var plainTextContent = "and easy to do anywhere, even with C#"; + var htmlContent = "and easy to do anywhere, even with C#"; + msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent); + + output.WriteLine(msg.Serialize()); + + Assert.Equal("{\"from\":{\"name\":\"Example User\",\"email\":\"test@example.com\"},\"personalizations\":[{\"to\":[{\"name\":\"Example User\",\"email\":\"test@example.com\"}],\"subject\":\"Sending with Twilio SendGrid is Fun\"}],\"content\":[{\"type\":\"text/plain\",\"value\":\"and easy to do anywhere, even with C#\"},{\"type\":\"text/html\",\"value\":\"\\u003cstrong\\u003eand easy to do anywhere, even with C#\\u003c/strong\\u003e\"}]}", msg.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestSendSingleEmailWithHelperWithOutEmailObject() + { + var msg = new SendGridMessage(); + msg.SetFrom(new EmailAddress("test@example.com")); + msg.AddTo("test@example.com"); + msg.SetSubject("Hello World from the Twilio SendGrid CSharp Library"); + msg.AddContent(MimeType.Text, "Textual content"); + msg.AddContent(MimeType.Html, "HTML content"); + Assert.Equal("{\"from\":{\"email\":\"test@example.com\"},\"personalizations\":[{\"to\":[{\"email\":\"test@example.com\"}],\"subject\":\"Hello World from the Twilio SendGrid CSharp Library\"}],\"content\":[{\"type\":\"text/plain\",\"value\":\"Textual content\"},{\"type\":\"text/html\",\"value\":\"HTML content\"}]}", msg.Serialize()); + + msg = new SendGridMessage(); + msg.SetFrom(new EmailAddress("test@example.com")); + msg.AddTo("test@example.com"); + msg.SetSubject("Hello World from the Twilio SendGrid CSharp Library"); + msg.AddContent(MimeType.Html, "HTML content"); + Console.WriteLine(msg.Serialize()); + } + + // All paramaters available for sending an email + [Fact(Skip = SkipConfigureApiKey)] + public void TestKitchenSink() + { + TestKitchenSinkInternal(); + } + + // All paramaters available for sending an email + private void TestKitchenSinkInternal(bool useDefaultSerialization = true) + { + var msg = new SendGridMessage(); + msg.SetFrom(new EmailAddress("test1@example.com", "Example User1")); + msg.SetGlobalSubject("Hello World from the Twilio SendGrid CSharp Library"); + msg.AddTo(new EmailAddress("test2@example.com", "Example User2")); + msg.AddTo("test-2@example.com", "Example User-2"); + msg.AddTo(new EmailAddress("test3@example.com", "Example User3")); + var emails = new List + { + new EmailAddress("test4@example.com", "Example User4"), + new EmailAddress("test5@example.com", "Example User5") + }; + msg.AddTos(emails); + msg.AddCc(new EmailAddress("test6@example.com", "Example User6")); + msg.AddCc(new EmailAddress("test7@example.com", "Example User7")); + emails = new List + { + new EmailAddress("test8@example.com", "Example User8"), + new EmailAddress("test9@example.com", "Example User9") + }; + msg.AddCcs(emails); + msg.AddCc("test-9@example.com", "Example User-9"); + msg.AddBcc(new EmailAddress("test10example.com", "Example User10")); + msg.AddBcc(new EmailAddress("test11@example.com", "Example User11")); + + emails = new List + { + new EmailAddress("test12@example.com", "Example User12"), + new EmailAddress("test13@example.com", "Example User13") + }; + msg.AddBccs(emails); + msg.AddBcc("test-13@example.com", "Example User-13"); + msg.SetSubject("Thank you for signing up, % name %"); + msg.AddHeader("X-Test1", "True1"); + msg.AddHeader("X-Test2", "Test2"); + var headers = new Dictionary() + { + { "X-Test3", "True3" }, + { "X-Test4", "True4" } + }; + msg.AddHeaders(headers); + msg.AddSubstitution("%name1%", "Example User1"); + msg.AddSubstitution("%city2%", "Denver1"); + var substitutions = new Dictionary() + { + { "%name3%", "Example User2" }, + { "%city4%", "Orange1" } + }; + msg.AddSubstitutions(substitutions); + msg.AddCustomArg("marketing1", "false"); + msg.AddCustomArg("transactional1", "true"); + var customArgs = new Dictionary() + { + { "marketing2", "true" }, + { "transactional2", "false" } + }; + msg.AddCustomArgs(customArgs); + msg.SetSendAt(1461775051); + + msg.AddTo(new EmailAddress("test14@example.com", "Example User14"), 1); + msg.AddTo(new EmailAddress("test15@example.com", "Example User15"), 1); + emails = new List + { + new EmailAddress("test16@example.com", "Example User16"), + new EmailAddress("test17@example.com", "Example User17") + }; + msg.AddTos(emails, 1); + msg.AddCc(new EmailAddress("test18@example.com", "Example User18"), 1); + msg.AddCc(new EmailAddress("test19@example.com", "Example User19"), 1); + emails = new List + { + new EmailAddress("test20@example.com", "Example User20"), + new EmailAddress("test21@example.com", "Example User21") + }; + msg.AddCcs(emails, 1); + msg.AddBcc(new EmailAddress("test22example.com", "Example User22"), 1); + msg.AddBcc(new EmailAddress("test23@example.com", "Example User23"), 1); + emails = new List + { + new EmailAddress("test24@example.com", "Example User24"), + new EmailAddress("test25@example.com", "Example User25") + }; + msg.AddBccs(emails, 1); + msg.SetSubject("Thank you for signing up, % name % 2", 1); + msg.AddHeader("X-Test5", "True5", 1); + msg.AddHeader("X-Test6", "Test6", 1); + headers = new Dictionary() + { + { "X-Test7", "True7" }, + { "X-Test8", "True8" } + }; + msg.AddHeaders(headers, 1); + msg.AddSubstitution("%name5%", "Example User5", 1); + msg.AddSubstitution("%city6%", "Denver6", 1); + substitutions = new Dictionary() + { + { "%name7%", "Example User7" }, + { "%city8%", "Orange8" } + }; + msg.AddSubstitutions(substitutions, 1); + msg.AddCustomArg("marketing3", "false", 1); + msg.AddCustomArg("transactional3", "true", 1); + customArgs = new Dictionary() + { + { "marketing4", "true" }, + { "transactional4", "false" } + }; + msg.AddCustomArgs(customArgs, 1); + msg.SetSendAt(1461775052, 1); + + msg.AddTo(new EmailAddress("test26@example.com", "Example User26"), 2); + msg.AddTo(new EmailAddress("test27@example.com", "Example User27"), 2); + emails = new List + { + new EmailAddress("test28@example.com", "Example User28"), + new EmailAddress("test29@example.com", "Example User29") + }; + msg.AddTos(emails, 2); + msg.AddCc(new EmailAddress("test30@example.com", "Example User30"), 2); + msg.AddCc(new EmailAddress("test31@example.com", "Example User31"), 2); + emails = new List + { + new EmailAddress("test32@example.com", "Example User32"), + new EmailAddress("test33@example.com", "Example User33") + }; + msg.AddCcs(emails, 2); + msg.AddBcc(new EmailAddress("test34example.com", "Example User34"), 2); + msg.AddBcc(new EmailAddress("test35@example.com", "Example User35"), 2); + + emails = new List + { + new EmailAddress("test36@example.com", "Example User36"), + new EmailAddress("test37@example.com", "Example User37") + }; + msg.AddBccs(emails, 2); + msg.SetSubject("Thank you for signing up, % name % 3", 2); + msg.AddHeader("X-Test7", "True7", 2); + msg.AddHeader("X-Test8", "Test8", 2); + headers = new Dictionary() + { + { "X-Test9", "True9" }, + { "X-Test10", "True10" } + }; + msg.AddHeaders(headers, 2); + msg.AddSubstitution("%name9%", "Example User9", 2); + msg.AddSubstitution("%city10%", "Denver10", 2); + substitutions = new Dictionary() + { + { "%name11%", "Example User11" }, + { "%city12%", "Orange12" } + }; + msg.AddSubstitutions(substitutions, 2); + msg.AddCustomArg("marketing5", "false", 2); + msg.AddCustomArg("transactional5", "true", 2); + customArgs = new Dictionary() + { + { "marketing6", "true" }, + { "transactional6", "false" } + }; + msg.AddCustomArgs(customArgs, 2); + msg.SetSendAt(1461775053, 2); + + var contents = new List(); + var content = new Content() + { + Type = "text/calendar", + Value = "Party Time!!" + }; + contents.Add(content); + content = new Content() + { + Type = "text/calendar2", + Value = "Party Time2!!" + }; + contents.Add(content); + msg.AddContents(contents); + msg.AddContent(MimeType.Html, "HTML content"); + msg.AddContent(MimeType.Text, "Textual content"); + + msg.AddAttachment("balance_001.pdf", + "TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gQ3JhcyBwdW12", + "application/pdf", + "attachment", + "Balance Sheet"); + var attachments = new List(); + var attachment = new Attachment() + { + Content = "BwdW", + Type = "image/png", + Filename = "banner.png", + Disposition = "inline", + ContentId = "Banner" + }; + attachments.Add(attachment); + attachment = new Attachment() + { + Content = "BwdW2", + Type = "image/png", + Filename = "banner2.png", + Disposition = "inline", + ContentId = "Banner 2" + }; + attachments.Add(attachment); + msg.AddAttachments(attachments); + msg.SetTemplateId("13b8f94f-bcae-4ec6-b752-70d6cb59f932"); + msg.AddGlobalHeader("X-Day", "Monday"); + var globalHeaders = new Dictionary { { "X-Month", "January" }, { "X-Year", "2017" } }; + msg.AddGlobalHeaders(globalHeaders); + msg.AddSection("%section1", "Substitution for Section 1 Tag"); + var sections = new Dictionary + { + {"%section2%", "Substitution for Section 2 Tag"}, + {"%section3%", "Substitution for Section 3 Tag"} + }; + msg.AddSections(sections); + msg.AddCategory("customer"); + var categories = new List { "vip", "new_account" }; + msg.AddCategories(categories); + msg.AddGlobalCustomArg("campaign", "welcome"); + var globalCustomArgs = new Dictionary { { "sequence2", "2" }, { "sequence3", "3" } }; + msg.AddGlobalCustomArgs(globalCustomArgs); + msg.SetAsm(3, new List() { 1, 4, 5 }); + msg.SetGlobalSendAt(1461775051); + msg.SetIpPoolName("23"); + // This must be a valid [batch ID](https://sendgrid.com/docs/API_Reference/SMTP_API/scheduling_parameters.html) + msg.SetBatchId("some_batch_id"); + msg.SetBccSetting(true, "test@example.com"); + msg.SetBypassListManagement(true); + msg.SetBypassSpamManagement(true); + msg.SetBypassBounceManagement(true); + msg.SetBypassUnsubscribeManagement(true); + msg.SetFooterSetting(true, "Some Footer HTML", "Some Footer Text"); + msg.SetSandBoxMode(true); + msg.SetSpamCheck(true, 1, "https://gotchya.example.com"); + msg.SetClickTracking(true, false); + msg.SetOpenTracking(true, "Optional tag to replace with the open image in the body of the message"); + msg.SetSubscriptionTracking(true, + "HTML to insert into the text / html portion of the message", + "text to insert into the text/plain portion of the message", + "substitution tag"); + msg.SetGoogleAnalytics(true, + "some campaign", + "some content", + "some medium", + "some source", + "some term"); + msg.SetReplyTo(new EmailAddress("test+reply@example.com", "Reply To Me")); + Assert.Equal("{\"from\":{\"name\":\"Example User1\",\"email\":\"test1@example.com\"},\"subject\":\"Hello World from the Twilio SendGrid CSharp Library\",\"personalizations\":[{\"to\":[{\"name\":\"Example User2\",\"email\":\"test2@example.com\"},{\"name\":\"Example User-2\",\"email\":\"test-2@example.com\"},{\"name\":\"Example User3\",\"email\":\"test3@example.com\"},{\"name\":\"Example User4\",\"email\":\"test4@example.com\"},{\"name\":\"Example User5\",\"email\":\"test5@example.com\"}],\"cc\":[{\"name\":\"Example User6\",\"email\":\"test6@example.com\"},{\"name\":\"Example User7\",\"email\":\"test7@example.com\"},{\"name\":\"Example User8\",\"email\":\"test8@example.com\"},{\"name\":\"Example User9\",\"email\":\"test9@example.com\"},{\"name\":\"Example User-9\",\"email\":\"test-9@example.com\"}],\"bcc\":[{\"name\":\"Example User10\",\"email\":\"test10example.com\"},{\"name\":\"Example User11\",\"email\":\"test11@example.com\"},{\"name\":\"Example User12\",\"email\":\"test12@example.com\"},{\"name\":\"Example User13\",\"email\":\"test13@example.com\"},{\"name\":\"Example User-13\",\"email\":\"test-13@example.com\"}],\"subject\":\"Thank you for signing up, % name %\",\"headers\":{\"X-Test1\":\"True1\",\"X-Test2\":\"Test2\",\"X-Test3\":\"True3\",\"X-Test4\":\"True4\"},\"substitutions\":{\"%name1%\":\"Example User1\",\"%city2%\":\"Denver1\",\"%name3%\":\"Example User2\",\"%city4%\":\"Orange1\"},\"custom_args\":{\"marketing1\":\"false\",\"transactional1\":\"true\",\"marketing2\":\"true\",\"transactional2\":\"false\"},\"send_at\":1461775051},{\"to\":[{\"name\":\"Example User14\",\"email\":\"test14@example.com\"},{\"name\":\"Example User15\",\"email\":\"test15@example.com\"},{\"name\":\"Example User16\",\"email\":\"test16@example.com\"},{\"name\":\"Example User17\",\"email\":\"test17@example.com\"}],\"cc\":[{\"name\":\"Example User18\",\"email\":\"test18@example.com\"},{\"name\":\"Example User19\",\"email\":\"test19@example.com\"},{\"name\":\"Example User20\",\"email\":\"test20@example.com\"},{\"name\":\"Example User21\",\"email\":\"test21@example.com\"}],\"bcc\":[{\"name\":\"Example User22\",\"email\":\"test22example.com\"},{\"name\":\"Example User23\",\"email\":\"test23@example.com\"},{\"name\":\"Example User24\",\"email\":\"test24@example.com\"},{\"name\":\"Example User25\",\"email\":\"test25@example.com\"}],\"subject\":\"Thank you for signing up, % name % 2\",\"headers\":{\"X-Test5\":\"True5\",\"X-Test6\":\"Test6\",\"X-Test7\":\"True7\",\"X-Test8\":\"True8\"},\"substitutions\":{\"%name5%\":\"Example User5\",\"%city6%\":\"Denver6\",\"%name7%\":\"Example User7\",\"%city8%\":\"Orange8\"},\"custom_args\":{\"marketing3\":\"false\",\"transactional3\":\"true\",\"marketing4\":\"true\",\"transactional4\":\"false\"},\"send_at\":1461775052},{\"to\":[{\"name\":\"Example User26\",\"email\":\"test26@example.com\"},{\"name\":\"Example User27\",\"email\":\"test27@example.com\"},{\"name\":\"Example User28\",\"email\":\"test28@example.com\"},{\"name\":\"Example User29\",\"email\":\"test29@example.com\"}],\"cc\":[{\"name\":\"Example User30\",\"email\":\"test30@example.com\"},{\"name\":\"Example User31\",\"email\":\"test31@example.com\"},{\"name\":\"Example User32\",\"email\":\"test32@example.com\"},{\"name\":\"Example User33\",\"email\":\"test33@example.com\"}],\"bcc\":[{\"name\":\"Example User34\",\"email\":\"test34example.com\"},{\"name\":\"Example User35\",\"email\":\"test35@example.com\"},{\"name\":\"Example User36\",\"email\":\"test36@example.com\"},{\"name\":\"Example User37\",\"email\":\"test37@example.com\"}],\"subject\":\"Thank you for signing up, % name % 3\",\"headers\":{\"X-Test7\":\"True7\",\"X-Test8\":\"Test8\",\"X-Test9\":\"True9\",\"X-Test10\":\"True10\"},\"substitutions\":{\"%name9%\":\"Example User9\",\"%city10%\":\"Denver10\",\"%name11%\":\"Example User11\",\"%city12%\":\"Orange12\"},\"custom_args\":{\"marketing5\":\"false\",\"transactional5\":\"true\",\"marketing6\":\"true\",\"transactional6\":\"false\"},\"send_at\":1461775053}],\"content\":[{\"type\":\"text/plain\",\"value\":\"Textual content\"},{\"type\":\"text/html\",\"value\":\"HTML content\"},{\"type\":\"text/calendar\",\"value\":\"Party Time!!\"},{\"type\":\"text/calendar2\",\"value\":\"Party Time2!!\"}],\"attachments\":[{\"content\":\"TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gQ3JhcyBwdW12\",\"type\":\"application/pdf\",\"filename\":\"balance_001.pdf\",\"disposition\":\"attachment\",\"content_id\":\"Balance Sheet\"},{\"content\":\"BwdW\",\"type\":\"image/png\",\"filename\":\"banner.png\",\"disposition\":\"inline\",\"content_id\":\"Banner\"},{\"content\":\"BwdW2\",\"type\":\"image/png\",\"filename\":\"banner2.png\",\"disposition\":\"inline\",\"content_id\":\"Banner 2\"}],\"template_id\":\"13b8f94f-bcae-4ec6-b752-70d6cb59f932\",\"headers\":{\"X-Day\":\"Monday\",\"X-Month\":\"January\",\"X-Year\":\"2017\"},\"sections\":{\"%section1\":\"Substitution for Section 1 Tag\",\"%section2%\":\"Substitution for Section 2 Tag\",\"%section3%\":\"Substitution for Section 3 Tag\"},\"categories\":[\"customer\",\"vip\",\"new_account\"],\"custom_args\":{\"campaign\":\"welcome\",\"sequence2\":\"2\",\"sequence3\":\"3\"},\"send_at\":1461775051,\"asm\":{\"group_id\":3,\"groups_to_display\":[1,4,5]},\"batch_id\":\"some_batch_id\",\"ip_pool_name\":\"23\",\"mail_settings\":{\"bcc\":{\"enable\":true,\"email\":\"test@example.com\"},\"bypass_list_management\":{\"enable\":true},\"bypass_spam_management\":{\"enable\":true},\"bypass_bounce_management\":{\"enable\":true},\"bypass_unsubscribe_management\":{\"enable\":true},\"footer\":{\"enable\":true,\"text\":\"Some Footer Text\",\"html\":\"Some Footer HTML\"},\"sandbox_mode\":{\"enable\":true},\"spam_check\":{\"enable\":true,\"threshold\":1,\"post_to_url\":\"https://gotchya.example.com\"}},\"tracking_settings\":{\"click_tracking\":{\"enable\":true,\"enable_text\":false},\"open_tracking\":{\"enable\":true,\"substitution_tag\":\"Optional tag to replace with the open image in the body of the message\"},\"subscription_tracking\":{\"enable\":true,\"text\":\"text to insert into the text/plain portion of the message\",\"html\":\"HTML to insert into the text / html portion of the message\",\"substitution_tag\":\"substitution tag\"},\"ganalytics\":{\"enable\":true,\"utm_source\":\"some source\",\"utm_medium\":\"some medium\",\"utm_term\":\"some term\",\"utm_content\":\"some content\",\"utm_campaign\":\"some campaign\"}},\"reply_to\":{\"name\":\"Reply To Me\",\"email\":\"test+reply@example.com\"}}", msg.Serialize(useDefaultSerialization)); + + // Ensure serializing a SendGridMessage from deserialization generates the same JSON object to send to Twilio SendGrid. + var json = msg.Serialize(useDefaultSerialization); + var msg2 = SendGridMessage.Deserialize(json); + Assert.Equal(json, msg2.Serialize(useDefaultSerialization)); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestKitchenSinkIsUnaffectedByCustomContractResolver() + { + var originalGetDefaults = JsonConvert.DefaultSettings; + + JsonConvert.DefaultSettings = () => new JsonSerializerSettings + { + ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver() + }; + + try + { + TestKitchenSinkInternal(false); + + // Ensure default behavior is not broken + var testObject = new + { + PropertyName = "PropertyValue", + Dictionary = new Dictionary { { "DictionaryKey", "DictionaryValue" } } + }; + Assert.Equal("{\"propertyName\":\"PropertyValue\",\"dictionary\":{\"dictionaryKey\":\"DictionaryValue\"}}", JsonConvert.SerializeObject(testObject)); + } + finally + { + JsonConvert.DefaultSettings = originalGetDefaults; + } + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestCreateSingleEmail() + { + var msg = MailHelper.CreateSingleEmail(new EmailAddress("test@example.com", "Example User"), + new EmailAddress("test@example.com"), + "Test Subject", + "Plain Text Content", + "HTML Content"); + Assert.Equal("{\"from\":{\"name\":\"Example User\",\"email\":\"test@example.com\"},\"personalizations\":[{\"to\":[{\"email\":\"test@example.com\"}],\"subject\":\"Test Subject\"}],\"content\":[{\"type\":\"text/plain\",\"value\":\"Plain Text Content\"},{\"type\":\"text/html\",\"value\":\"HTML Content\"}]}", msg.Serialize()); + + var msg2 = MailHelper.CreateSingleEmail(new EmailAddress("test@example.com", "Example User"), + new EmailAddress("test@example.com"), + "Test Subject", + null, + "HTML Content"); + Assert.Equal("{\"from\":{\"name\":\"Example User\",\"email\":\"test@example.com\"},\"personalizations\":[{\"to\":[{\"email\":\"test@example.com\"}],\"subject\":\"Test Subject\"}],\"content\":[{\"type\":\"text/html\",\"value\":\"HTML Content\"}]}", msg2.Serialize()); + + var msg3 = MailHelper.CreateSingleEmail(new EmailAddress("test@example.com", "Example User"), + new EmailAddress("test@example.com"), + "Test Subject", + "Plain Text Content", + null); + Assert.Equal("{\"from\":{\"name\":\"Example User\",\"email\":\"test@example.com\"},\"personalizations\":[{\"to\":[{\"email\":\"test@example.com\"}],\"subject\":\"Test Subject\"}],\"content\":[{\"type\":\"text/plain\",\"value\":\"Plain Text Content\"}]}", msg3.Serialize()); + + var msg4 = MailHelper.CreateSingleEmail(new EmailAddress("test@example.com", "Example User"), + new EmailAddress("test@example.com"), + "Test Subject", + "", + "HTML Content"); + Assert.Equal("{\"from\":{\"name\":\"Example User\",\"email\":\"test@example.com\"},\"personalizations\":[{\"to\":[{\"email\":\"test@example.com\"}],\"subject\":\"Test Subject\"}],\"content\":[{\"type\":\"text/html\",\"value\":\"HTML Content\"}]}", msg4.Serialize()); + + var msg5 = MailHelper.CreateSingleEmail(new EmailAddress("test@example.com", "Example User"), + new EmailAddress("test@example.com"), + "Test Subject", + "Plain Text Content", + ""); + Assert.Equal("{\"from\":{\"name\":\"Example User\",\"email\":\"test@example.com\"},\"personalizations\":[{\"to\":[{\"email\":\"test@example.com\"}],\"subject\":\"Test Subject\"}],\"content\":[{\"type\":\"text/plain\",\"value\":\"Plain Text Content\"}]}", msg5.Serialize()); + + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestCreateSingleEmailToMultipleRecipients() + { + var emails = new List + { + new EmailAddress("test1@example.com"), + new EmailAddress("test2@example.com"), + new EmailAddress("test3@example.com") + }; + var msg = MailHelper.CreateSingleEmailToMultipleRecipients(new EmailAddress("test@example.com", "Example User"), + emails, + "Test Subject", + "Plain Text Content", + "HTML Content" + ); + Assert.Equal("{\"from\":{\"name\":\"Example User\",\"email\":\"test@example.com\"},\"subject\":\"Test Subject\",\"personalizations\":[{\"to\":[{\"email\":\"test1@example.com\"}]},{\"to\":[{\"email\":\"test2@example.com\"}]},{\"to\":[{\"email\":\"test3@example.com\"}]}],\"content\":[{\"type\":\"text/plain\",\"value\":\"Plain Text Content\"},{\"type\":\"text/html\",\"value\":\"HTML Content\"}]}", msg.Serialize()); + + var msg2 = MailHelper.CreateSingleEmailToMultipleRecipients(new EmailAddress("test@example.com", "Example User"), + emails, + "Test Subject", + null, + "HTML Content" + ); + Assert.Equal("{\"from\":{\"name\":\"Example User\",\"email\":\"test@example.com\"},\"subject\":\"Test Subject\",\"personalizations\":[{\"to\":[{\"email\":\"test1@example.com\"}]},{\"to\":[{\"email\":\"test2@example.com\"}]},{\"to\":[{\"email\":\"test3@example.com\"}]}],\"content\":[{\"type\":\"text/html\",\"value\":\"HTML Content\"}]}", msg2.Serialize()); + + var msg3 = MailHelper.CreateSingleEmailToMultipleRecipients(new EmailAddress("test@example.com", "Example User"), + emails, + "Test Subject", + "Plain Text Content", + null + ); + Assert.Equal("{\"from\":{\"name\":\"Example User\",\"email\":\"test@example.com\"},\"subject\":\"Test Subject\",\"personalizations\":[{\"to\":[{\"email\":\"test1@example.com\"}]},{\"to\":[{\"email\":\"test2@example.com\"}]},{\"to\":[{\"email\":\"test3@example.com\"}]}],\"content\":[{\"type\":\"text/plain\",\"value\":\"Plain Text Content\"}]}", msg3.Serialize()); + + var msg4 = MailHelper.CreateSingleEmailToMultipleRecipients(new EmailAddress("test@example.com", "Example User"), + emails, + "Test Subject", + "", + "HTML Content" + ); + Assert.Equal("{\"from\":{\"name\":\"Example User\",\"email\":\"test@example.com\"},\"subject\":\"Test Subject\",\"personalizations\":[{\"to\":[{\"email\":\"test1@example.com\"}]},{\"to\":[{\"email\":\"test2@example.com\"}]},{\"to\":[{\"email\":\"test3@example.com\"}]}],\"content\":[{\"type\":\"text/html\",\"value\":\"HTML Content\"}]}", msg4.Serialize()); + + var msg5 = MailHelper.CreateSingleEmailToMultipleRecipients(new EmailAddress("test@example.com", "Example User"), + emails, + "Test Subject", + "Plain Text Content", + "" + ); + Assert.Equal("{\"from\":{\"name\":\"Example User\",\"email\":\"test@example.com\"},\"subject\":\"Test Subject\",\"personalizations\":[{\"to\":[{\"email\":\"test1@example.com\"}]},{\"to\":[{\"email\":\"test2@example.com\"}]},{\"to\":[{\"email\":\"test3@example.com\"}]}],\"content\":[{\"type\":\"text/plain\",\"value\":\"Plain Text Content\"}]}", msg5.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestCreateSingleEmailToMultipleRecipientsToggleRecipientDisplay() + { + var emails = new List + { + new EmailAddress("test1@example.com"), + new EmailAddress("test2@example.com"), + new EmailAddress("test3@example.com") + }; + var msg = MailHelper.CreateSingleEmailToMultipleRecipients(new EmailAddress("test@example.com", "Example User"), + emails, + "Test Subject", + "Plain Text Content", + "HTML Content" + ); + Assert.Equal("{\"from\":{\"name\":\"Example User\",\"email\":\"test@example.com\"},\"subject\":\"Test Subject\",\"personalizations\":[{\"to\":[{\"email\":\"test1@example.com\"}]},{\"to\":[{\"email\":\"test2@example.com\"}]},{\"to\":[{\"email\":\"test3@example.com\"}]}],\"content\":[{\"type\":\"text/plain\",\"value\":\"Plain Text Content\"},{\"type\":\"text/html\",\"value\":\"HTML Content\"}]}", msg.Serialize()); + + var msg2 = MailHelper.CreateSingleEmailToMultipleRecipients(new EmailAddress("test@example.com", "Example User"), + emails, + "Test Subject", + null, + "HTML Content" + ); + Assert.Equal("{\"from\":{\"name\":\"Example User\",\"email\":\"test@example.com\"},\"subject\":\"Test Subject\",\"personalizations\":[{\"to\":[{\"email\":\"test1@example.com\"}]},{\"to\":[{\"email\":\"test2@example.com\"}]},{\"to\":[{\"email\":\"test3@example.com\"}]}],\"content\":[{\"type\":\"text/html\",\"value\":\"HTML Content\"}]}", msg2.Serialize()); + + var msg3 = MailHelper.CreateSingleEmailToMultipleRecipients(new EmailAddress("test@example.com", "Example User"), + emails, + "Test Subject", + "Plain Text Content", + null + ); + Assert.Equal("{\"from\":{\"name\":\"Example User\",\"email\":\"test@example.com\"},\"subject\":\"Test Subject\",\"personalizations\":[{\"to\":[{\"email\":\"test1@example.com\"}]},{\"to\":[{\"email\":\"test2@example.com\"}]},{\"to\":[{\"email\":\"test3@example.com\"}]}],\"content\":[{\"type\":\"text/plain\",\"value\":\"Plain Text Content\"}]}", msg3.Serialize()); + + var msg4 = MailHelper.CreateSingleEmailToMultipleRecipients(new EmailAddress("test@example.com", "Example User"), + emails, + "Test Subject", + "", + "HTML Content" + ); + Assert.Equal("{\"from\":{\"name\":\"Example User\",\"email\":\"test@example.com\"},\"subject\":\"Test Subject\",\"personalizations\":[{\"to\":[{\"email\":\"test1@example.com\"}]},{\"to\":[{\"email\":\"test2@example.com\"}]},{\"to\":[{\"email\":\"test3@example.com\"}]}],\"content\":[{\"type\":\"text/html\",\"value\":\"HTML Content\"}]}", msg4.Serialize()); + + var msg5 = MailHelper.CreateSingleEmailToMultipleRecipients(new EmailAddress("test@example.com", "Example User"), + emails, + "Test Subject", + "Plain Text Content", + "" + ); + Assert.Equal("{\"from\":{\"name\":\"Example User\",\"email\":\"test@example.com\"},\"subject\":\"Test Subject\",\"personalizations\":[{\"to\":[{\"email\":\"test1@example.com\"}]},{\"to\":[{\"email\":\"test2@example.com\"}]},{\"to\":[{\"email\":\"test3@example.com\"}]}],\"content\":[{\"type\":\"text/plain\",\"value\":\"Plain Text Content\"}]}", msg5.Serialize()); + + var msg6 = MailHelper.CreateSingleEmailToMultipleRecipients(new EmailAddress("test@example.com", "Example User"), + emails, + "Test Subject", + "Plain Text Content", + "HTML Content", + true + ); + Assert.Equal("{\"from\":{\"name\":\"Example User\",\"email\":\"test@example.com\"},\"subject\":\"Test Subject\",\"personalizations\":[{\"to\":[{\"email\":\"test1@example.com\"},{\"email\":\"test2@example.com\"},{\"email\":\"test3@example.com\"}]}],\"content\":[{\"type\":\"text/plain\",\"value\":\"Plain Text Content\"},{\"type\":\"text/html\",\"value\":\"HTML Content\"}]}", msg6.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestCreateMultipleEmailsToMultipleRecipients() + { + var emails = new List + { + new EmailAddress("test1@example.com"), + new EmailAddress("test2@example.com"), + new EmailAddress("test3@example.com") + }; + var subjects = new List { "Test Subject1", "Test Subject2", "Test Subject3" }; + var plainTextContent = "Hello -name-"; + var htmlContent = "Goodbye -name-"; + var substitutions = new List> + { + new Dictionary() {{"-name-", "Name1"}}, + new Dictionary() {{"-name-", "Name1"}}, + new Dictionary() {{"-name-", "Name1"}} + }; + var msg = MailHelper.CreateMultipleEmailsToMultipleRecipients(new EmailAddress("test@example.com", "Example User"), + emails, + subjects, + plainTextContent, + htmlContent, + substitutions + ); + Assert.Equal("{\"from\":{\"name\":\"Example User\",\"email\":\"test@example.com\"},\"personalizations\":[{\"to\":[{\"email\":\"test1@example.com\"}],\"subject\":\"Test Subject1\",\"substitutions\":{\"-name-\":\"Name1\"}},{\"to\":[{\"email\":\"test2@example.com\"}],\"subject\":\"Test Subject2\",\"substitutions\":{\"-name-\":\"Name1\"}},{\"to\":[{\"email\":\"test3@example.com\"}],\"subject\":\"Test Subject3\",\"substitutions\":{\"-name-\":\"Name1\"}}],\"content\":[{\"type\":\"text/plain\",\"value\":\"Hello -name-\"},{\"type\":\"text/html\",\"value\":\"Goodbye -name-\"}]}", msg.Serialize()); + + plainTextContent = null; + htmlContent = "Goodbye -name-"; + var msg2 = MailHelper.CreateMultipleEmailsToMultipleRecipients(new EmailAddress("test@example.com", "Example User"), + emails, + subjects, + plainTextContent, + htmlContent, + substitutions + ); + Assert.Equal("{\"from\":{\"name\":\"Example User\",\"email\":\"test@example.com\"},\"personalizations\":[{\"to\":[{\"email\":\"test1@example.com\"}],\"subject\":\"Test Subject1\",\"substitutions\":{\"-name-\":\"Name1\"}},{\"to\":[{\"email\":\"test2@example.com\"}],\"subject\":\"Test Subject2\",\"substitutions\":{\"-name-\":\"Name1\"}},{\"to\":[{\"email\":\"test3@example.com\"}],\"subject\":\"Test Subject3\",\"substitutions\":{\"-name-\":\"Name1\"}}],\"content\":[{\"type\":\"text/html\",\"value\":\"Goodbye -name-\"}]}", msg2.Serialize()); + + plainTextContent = "Hello -name-"; + htmlContent = null; + var msg3 = MailHelper.CreateMultipleEmailsToMultipleRecipients(new EmailAddress("test@example.com", "Example User"), + emails, + subjects, + plainTextContent, + htmlContent, + substitutions + ); + Assert.Equal("{\"from\":{\"name\":\"Example User\",\"email\":\"test@example.com\"},\"personalizations\":[{\"to\":[{\"email\":\"test1@example.com\"}],\"subject\":\"Test Subject1\",\"substitutions\":{\"-name-\":\"Name1\"}},{\"to\":[{\"email\":\"test2@example.com\"}],\"subject\":\"Test Subject2\",\"substitutions\":{\"-name-\":\"Name1\"}},{\"to\":[{\"email\":\"test3@example.com\"}],\"subject\":\"Test Subject3\",\"substitutions\":{\"-name-\":\"Name1\"}}],\"content\":[{\"type\":\"text/plain\",\"value\":\"Hello -name-\"}]}", msg3.Serialize()); + + plainTextContent = ""; + htmlContent = "Goodbye -name-"; + var msg4 = MailHelper.CreateMultipleEmailsToMultipleRecipients(new EmailAddress("test@example.com", "Example User"), + emails, + subjects, + plainTextContent, + htmlContent, + substitutions + ); + Assert.Equal("{\"from\":{\"name\":\"Example User\",\"email\":\"test@example.com\"},\"personalizations\":[{\"to\":[{\"email\":\"test1@example.com\"}],\"subject\":\"Test Subject1\",\"substitutions\":{\"-name-\":\"Name1\"}},{\"to\":[{\"email\":\"test2@example.com\"}],\"subject\":\"Test Subject2\",\"substitutions\":{\"-name-\":\"Name1\"}},{\"to\":[{\"email\":\"test3@example.com\"}],\"subject\":\"Test Subject3\",\"substitutions\":{\"-name-\":\"Name1\"}}],\"content\":[{\"type\":\"text/html\",\"value\":\"Goodbye -name-\"}]}", msg4.Serialize()); + + plainTextContent = "Hello -name-"; + htmlContent = ""; + var msg5 = MailHelper.CreateMultipleEmailsToMultipleRecipients(new EmailAddress("test@example.com", "Example User"), + emails, + subjects, + plainTextContent, + htmlContent, + substitutions + ); + Assert.Equal("{\"from\":{\"name\":\"Example User\",\"email\":\"test@example.com\"},\"personalizations\":[{\"to\":[{\"email\":\"test1@example.com\"}],\"subject\":\"Test Subject1\",\"substitutions\":{\"-name-\":\"Name1\"}},{\"to\":[{\"email\":\"test2@example.com\"}],\"subject\":\"Test Subject2\",\"substitutions\":{\"-name-\":\"Name1\"}},{\"to\":[{\"email\":\"test3@example.com\"}],\"subject\":\"Test Subject3\",\"substitutions\":{\"-name-\":\"Name1\"}}],\"content\":[{\"type\":\"text/plain\",\"value\":\"Hello -name-\"}]}", msg5.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestAddFrom() + { + // Personalization not passed in, Personalization does not exist + var msg = new SendGridMessage(); + msg.AddTo(new EmailAddress("test001@example.com", "Example User")); + msg.SetFrom(new EmailAddress("test002@example.com", "Example User")); + Assert.Equal("{\"from\":{\"name\":\"Example User\",\"email\":\"test002@example.com\"},\"personalizations\":[{\"to\":[{\"name\":\"Example User\",\"email\":\"test001@example.com\"}]}]}", msg.Serialize()); + + // Personalization passed in, no Personalizations + msg = new SendGridMessage(); + var toEmail = new EmailAddress("test002@example.com", "Example User"); + var fromEmail = new EmailAddress("test001@example.com", "Example User"); + var personalization = new Personalization() + { + Tos = new List() + { + toEmail + }, + From = fromEmail + }; + msg.AddTo(new EmailAddress("test003@example.com", "Example User"), 0, personalization); + Assert.Equal("{\"personalizations\":[{\"to\":[{\"name\":\"Example User\",\"email\":\"test002@example.com\"}," + + "{\"name\":\"Example User\",\"email\":\"test003@example.com\"}]," + + "\"from\":{\"name\":\"Example User\",\"email\":\"test001@example.com\"}}]}", msg.Serialize()); + + // Personalization passed in, Personalization exists + msg = new SendGridMessage(); + toEmail = new EmailAddress("test004@example.com", "Example User"); + fromEmail = new EmailAddress("test005@example.com", "Example User"); + msg.Personalizations = new List() { + new Personalization() { + Tos = new List() + { + toEmail + }, + From = fromEmail + } + }; + toEmail = new EmailAddress("test006@example.com", "Example User"); + fromEmail = new EmailAddress("test007@example.com", "Example User"); + personalization = new Personalization() + { + Tos = new List() + { + toEmail + }, + From = fromEmail + }; + msg.AddTo(toEmail, 1, personalization); + Assert.Equal("{\"personalizations\":[{\"to\":[{\"name\":\"Example User\",\"email\":\"test004@example.com\"}]," + + "\"from\":{\"name\":\"Example User\",\"email\":\"test005@example.com\"}}," + + "{\"to\":[{\"name\":\"Example User\",\"email\":\"test006@example.com\"}]," + + "\"from\":{\"name\":\"Example User\",\"email\":\"test007@example.com\"}}]}", msg.Serialize()); + + + // Personalization not passed in Personalizations exists + msg = new SendGridMessage(); + toEmail = new EmailAddress("test009@example.com", "Example User"); + fromEmail = new EmailAddress("test010@example.com", "Example User"); + msg.Personalizations = new List() { + new Personalization() { + Tos = new List() + { + toEmail + }, + From = fromEmail + } + }; + toEmail = new EmailAddress("test011@example.com", "Example User"); + fromEmail = new EmailAddress("test012@example.com", "Example User"); + personalization = new Personalization() + { + Tos = new List() + { + toEmail + }, + From = fromEmail + }; + msg.Personalizations.Add(personalization); + msg.AddTo(new EmailAddress("test013@example.com", "Example User")); + Assert.Equal("{\"personalizations\":[{\"to\":[{\"name\":\"Example User\",\"email\":\"test009@example.com\"},{\"name\":\"Example User\",\"email\":\"test013@example.com\"}]," + + "\"from\":{\"name\":\"Example User\",\"email\":\"test010@example.com\"}},{\"to\":[{\"name\":\"Example User\",\"email\":\"test011@example.com\"}]," + + "\"from\":{\"name\":\"Example User\",\"email\":\"test012@example.com\"}}]}", msg.Serialize()); + } + [Fact(Skip = SkipConfigureApiKey)] + public void TestAddTo() + { + // Personalization not passed in, Personalization does not exist + var msg = new SendGridMessage(); + msg.AddTo(new EmailAddress("test001@example.com", "Example User")); + Assert.Equal("{\"personalizations\":[{\"to\":[{\"name\":\"Example User\",\"email\":\"test001@example.com\"}]}]}", msg.Serialize()); + + // Personalization passed in, no Personalizations + msg = new SendGridMessage(); + var email = new EmailAddress("test002@example.com", "Example User"); + var personalization = new Personalization() + { + Tos = new List() + { + email + } + }; + msg.AddTo(new EmailAddress("test003@example.com", "Example User"), 0, personalization); + Assert.Equal("{\"personalizations\":[{\"to\":[{\"name\":\"Example User\",\"email\":\"test002@example.com\"},{\"name\":\"Example User\",\"email\":\"test003@example.com\"}]}]}", msg.Serialize()); + + // Personalization passed in, Personalization exists + msg = new SendGridMessage(); + email = new EmailAddress("test004@example.com", "Example User"); + msg.Personalizations = new List() { + new Personalization() { + Tos = new List() + { + email + } + } + }; + email = new EmailAddress("test005@example.com", "Example User"); + personalization = new Personalization() + { + Tos = new List() + { + email + } + }; + msg.AddTo(new EmailAddress("test006@example.com", "Example User"), 1, personalization); + Assert.Equal("{\"personalizations\":[{\"to\":[{\"name\":\"Example User\",\"email\":\"test004@example.com\"}]},{\"to\":[{\"name\":\"Example User\",\"email\":\"test005@example.com\"},{\"name\":\"Example User\",\"email\":\"test006@example.com\"}]}]}", msg.Serialize()); + + // Personalization not passed in Personalization exists + msg = new SendGridMessage(); + email = new EmailAddress("test007@example.com", "Example User"); + msg.Personalizations = new List() { + new Personalization() { + Tos = new List() + { + email + } + } + }; + msg.AddTo(new EmailAddress("test008@example.com", "Example User")); + Assert.Equal("{\"personalizations\":[{\"to\":[{\"name\":\"Example User\",\"email\":\"test007@example.com\"},{\"name\":\"Example User\",\"email\":\"test008@example.com\"}]}]}", msg.Serialize()); + + + // Personalization not passed in Personalizations exists + msg = new SendGridMessage(); + email = new EmailAddress("test009@example.com", "Example User"); + msg.Personalizations = new List() { + new Personalization() { + Tos = new List() + { + email + } + } + }; + email = new EmailAddress("test010@example.com", "Example User"); + personalization = new Personalization() + { + Tos = new List() + { + email + } + }; + msg.Personalizations.Add(personalization); + msg.AddTo(new EmailAddress("test011@example.com", "Example User")); + Assert.Equal("{\"personalizations\":[{\"to\":[{\"name\":\"Example User\",\"email\":\"test009@example.com\"},{\"name\":\"Example User\",\"email\":\"test011@example.com\"}]},{\"to\":[{\"name\":\"Example User\",\"email\":\"test010@example.com\"}]}]}", msg.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestAddToWithOutEmailAddressObject() + { + var msg = new SendGridMessage(); + msg.AddTo("test001@example.com", "Example User"); + Assert.Equal("{\"personalizations\":[{\"to\":[{\"name\":\"Example User\",\"email\":\"test001@example.com\"}]}]}", msg.Serialize()); + + msg = new SendGridMessage(); + msg.AddTo("test001@example.com"); + Assert.Equal("{\"personalizations\":[{\"to\":[{\"email\":\"test001@example.com\"}]}]}", msg.Serialize()); + + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestAddToArgumentNullExceptionIfNullEmailAddressIsSupplied() + { + var msg = new SendGridMessage(); + Assert.Throws(() => msg.AddTo(null, "Example User")); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestAddToArgumentNullExceptionIfNoEmailAddressIsSupplied() + { + var msg = new SendGridMessage(); + Assert.Throws(() => msg.AddTo(string.Empty, "Example User")); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestAddTos() + { + // Personalization not passed in, Personalization does not exist + var msg = new SendGridMessage(); + var emails = new List + { + new EmailAddress("test012@example.com", "Example User"), + new EmailAddress("test013@example.com", "Example User") + }; + msg.AddTos(emails); + Assert.Equal("{\"personalizations\":[{\"to\":[{\"name\":\"Example User\",\"email\":\"test012@example.com\"},{\"name\":\"Example User\",\"email\":\"test013@example.com\"}]}]}", msg.Serialize()); + + // Personalization passed in, no Personalizations + msg = new SendGridMessage(); + emails = new List + { + new EmailAddress("test014@example.com", "Example User"), + new EmailAddress("test015@example.com", "Example User") + }; + var personalization = new Personalization() + { + Tos = emails + }; + emails = new List + { + new EmailAddress("test016@example.com", "Example User"), + new EmailAddress("test017@example.com", "Example User") + }; + msg.AddTos(emails, 0, personalization); + Assert.Equal("{\"personalizations\":[{\"to\":[{\"name\":\"Example User\",\"email\":\"test014@example.com\"},{\"name\":\"Example User\",\"email\":\"test015@example.com\"},{\"name\":\"Example User\",\"email\":\"test016@example.com\"},{\"name\":\"Example User\",\"email\":\"test017@example.com\"}]}]}", msg.Serialize()); + + // Personalization passed in, Personalization exists + msg = new SendGridMessage(); + emails = new List + { + new EmailAddress("test018@example.com", "Example User"), + new EmailAddress("test019@example.com", "Example User") + }; + msg.Personalizations = new List() { + new Personalization() { + Tos = emails + } + }; + emails = new List + { + new EmailAddress("test020@example.com", "Example User"), + new EmailAddress("test021@example.com", "Example User") + }; + personalization = new Personalization() + { + Tos = emails + }; + emails = new List + { + new EmailAddress("test022@example.com", "Example User"), + new EmailAddress("test023@example.com", "Example User") + }; + msg.AddTos(emails, 1, personalization); + Assert.Equal("{\"personalizations\":[{\"to\":[{\"name\":\"Example User\",\"email\":\"test018@example.com\"},{\"name\":\"Example User\",\"email\":\"test019@example.com\"}]},{\"to\":[{\"name\":\"Example User\",\"email\":\"test020@example.com\"},{\"name\":\"Example User\",\"email\":\"test021@example.com\"},{\"name\":\"Example User\",\"email\":\"test022@example.com\"},{\"name\":\"Example User\",\"email\":\"test023@example.com\"}]}]}", msg.Serialize()); + + // Personalization not passed in Personalization exists + msg = new SendGridMessage(); + emails = new List + { + new EmailAddress("test024@example.com", "Example User"), + new EmailAddress("test025@example.com", "Example User") + }; + msg.Personalizations = new List() { + new Personalization() { + Tos = emails + } + }; + emails = new List + { + new EmailAddress("test026@example.com", "Example User"), + new EmailAddress("test027@example.com", "Example User") + }; + msg.AddTos(emails); + Assert.Equal("{\"personalizations\":[{\"to\":[{\"name\":\"Example User\",\"email\":\"test024@example.com\"},{\"name\":\"Example User\",\"email\":\"test025@example.com\"},{\"name\":\"Example User\",\"email\":\"test026@example.com\"},{\"name\":\"Example User\",\"email\":\"test027@example.com\"}]}]}", msg.Serialize()); + + // Personalization not passed in Personalizations exists + msg = new SendGridMessage(); + emails = new List + { + new EmailAddress("test028@example.com", "Example User"), + new EmailAddress("test029@example.com", "Example User") + }; + msg.Personalizations = new List() { + new Personalization() { + Tos = emails + } + }; + emails = new List + { + new EmailAddress("test030@example.com", "Example User"), + new EmailAddress("test031@example.com", "Example User") + }; + personalization = new Personalization() + { + Tos = emails + }; + msg.Personalizations.Add(personalization); + emails = new List + { + new EmailAddress("test032@example.com", "Example User"), + new EmailAddress("test033@example.com", "Example User") + }; + msg.AddTos(emails); + Assert.Equal("{\"personalizations\":[{\"to\":[{\"name\":\"Example User\",\"email\":\"test028@example.com\"},{\"name\":\"Example User\",\"email\":\"test029@example.com\"},{\"name\":\"Example User\",\"email\":\"test032@example.com\"},{\"name\":\"Example User\",\"email\":\"test033@example.com\"}]},{\"to\":[{\"name\":\"Example User\",\"email\":\"test030@example.com\"},{\"name\":\"Example User\",\"email\":\"test031@example.com\"}]}]}", msg.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestAddCcWithoutEmailAddressObject() + { + var msg = new SendGridMessage(); + msg.AddCc("test001@example.com", "Example User"); + Assert.Equal("{\"personalizations\":[{\"cc\":[{\"name\":\"Example User\",\"email\":\"test001@example.com\"}]}]}", msg.Serialize()); + + msg = new SendGridMessage(); + msg.AddCc("test001@example.com"); + Assert.Equal("{\"personalizations\":[{\"cc\":[{\"email\":\"test001@example.com\"}]}]}", msg.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestAddCcArgumentNullExceptionIfNullEmailAddressIsSupplied() + { + var msg = new SendGridMessage(); + Assert.Throws(() => msg.AddCc(null, "Example User")); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestAddCcArgumentNullExceptionIfEmptyEmailAddressIsSupplied() + { + var msg = new SendGridMessage(); + Assert.Throws(() => msg.AddCc(string.Empty, "Example User")); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestAddCc() + { + // Personalization not passed in, Personalization does not exist + var msg = new SendGridMessage(); + msg.AddCc(new EmailAddress("test001@example.com", "Example User")); + Assert.Equal("{\"personalizations\":[{\"cc\":[{\"name\":\"Example User\",\"email\":\"test001@example.com\"}]}]}", msg.Serialize()); + + // Personalization passed in, no Personalizations + msg = new SendGridMessage(); + var email = new EmailAddress("test002@example.com", "Example User"); + var personalization = new Personalization() + { + Ccs = new List() + { + email + } + }; + msg.AddCc(new EmailAddress("test003@example.com", "Example User"), 0, personalization); + Assert.Equal("{\"personalizations\":[{\"cc\":[{\"name\":\"Example User\",\"email\":\"test002@example.com\"},{\"name\":\"Example User\",\"email\":\"test003@example.com\"}]}]}", msg.Serialize()); + + // Personalization passed in, Personalization exists + msg = new SendGridMessage(); + email = new EmailAddress("test004@example.com", "Example User"); + msg.Personalizations = new List() { + new Personalization() { + Ccs = new List() + { + email + } + } + }; + email = new EmailAddress("test005@example.com", "Example User"); + personalization = new Personalization() + { + Ccs = new List() + { + email + } + }; + msg.AddCc(new EmailAddress("test006@example.com", "Example User"), 1, personalization); + Assert.Equal("{\"personalizations\":[{\"cc\":[{\"name\":\"Example User\",\"email\":\"test004@example.com\"}]},{\"cc\":[{\"name\":\"Example User\",\"email\":\"test005@example.com\"},{\"name\":\"Example User\",\"email\":\"test006@example.com\"}]}]}", msg.Serialize()); + + // Personalization not passed in Personalization exists + msg = new SendGridMessage(); + email = new EmailAddress("test007@example.com", "Example User"); + msg.Personalizations = new List() { + new Personalization() { + Ccs = new List() + { + email + } + } + }; + msg.AddCc(new EmailAddress("test008@example.com", "Example User")); + Assert.Equal("{\"personalizations\":[{\"cc\":[{\"name\":\"Example User\",\"email\":\"test007@example.com\"},{\"name\":\"Example User\",\"email\":\"test008@example.com\"}]}]}", msg.Serialize()); + + + // Personalization not passed in Personalizations exists + msg = new SendGridMessage(); + email = new EmailAddress("test009@example.com", "Example User"); + msg.Personalizations = new List() { + new Personalization() { + Ccs = new List() + { + email + } + } + }; + email = new EmailAddress("test010@example.com", "Example User"); + personalization = new Personalization() + { + Ccs = new List() + { + email + } + }; + msg.Personalizations.Add(personalization); + msg.AddCc(new EmailAddress("test011@example.com", "Example User")); + Assert.Equal("{\"personalizations\":[{\"cc\":[{\"name\":\"Example User\",\"email\":\"test009@example.com\"},{\"name\":\"Example User\",\"email\":\"test011@example.com\"}]},{\"cc\":[{\"name\":\"Example User\",\"email\":\"test010@example.com\"}]}]}", msg.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestAddCcs() + { + // Personalization not passed in, Personalization does not exist + var msg = new SendGridMessage(); + var emails = new List + { + new EmailAddress("test012@example.com", "Example User"), + new EmailAddress("test013@example.com", "Example User") + }; + msg.AddCcs(emails); + Assert.Equal("{\"personalizations\":[{\"cc\":[{\"name\":\"Example User\",\"email\":\"test012@example.com\"},{\"name\":\"Example User\",\"email\":\"test013@example.com\"}]}]}", msg.Serialize()); + + // Personalization passed in, no Personalizations + msg = new SendGridMessage(); + emails = new List + { + new EmailAddress("test014@example.com", "Example User"), + new EmailAddress("test015@example.com", "Example User") + }; + var personalization = new Personalization() + { + Ccs = emails + }; + emails = new List + { + new EmailAddress("test016@example.com", "Example User"), + new EmailAddress("test017@example.com", "Example User") + }; + msg.AddCcs(emails, 0, personalization); + Assert.Equal("{\"personalizations\":[{\"cc\":[{\"name\":\"Example User\",\"email\":\"test014@example.com\"},{\"name\":\"Example User\",\"email\":\"test015@example.com\"},{\"name\":\"Example User\",\"email\":\"test016@example.com\"},{\"name\":\"Example User\",\"email\":\"test017@example.com\"}]}]}", msg.Serialize()); + + // Personalization passed in, Personalization exists + msg = new SendGridMessage(); + emails = new List + { + new EmailAddress("test018@example.com", "Example User"), + new EmailAddress("test019@example.com", "Example User") + }; + msg.Personalizations = new List() { + new Personalization() { + Ccs = emails + } + }; + emails = new List + { + new EmailAddress("test020@example.com", "Example User"), + new EmailAddress("test021@example.com", "Example User") + }; + personalization = new Personalization() + { + Ccs = emails + }; + emails = new List + { + new EmailAddress("test022@example.com", "Example User"), + new EmailAddress("test023@example.com", "Example User") + }; + msg.AddCcs(emails, 1, personalization); + Assert.Equal("{\"personalizations\":[{\"cc\":[{\"name\":\"Example User\",\"email\":\"test018@example.com\"},{\"name\":\"Example User\",\"email\":\"test019@example.com\"}]},{\"cc\":[{\"name\":\"Example User\",\"email\":\"test020@example.com\"},{\"name\":\"Example User\",\"email\":\"test021@example.com\"},{\"name\":\"Example User\",\"email\":\"test022@example.com\"},{\"name\":\"Example User\",\"email\":\"test023@example.com\"}]}]}", msg.Serialize()); + + // Personalization not passed in Personalization exists + msg = new SendGridMessage(); + emails = new List + { + new EmailAddress("test024@example.com", "Example User"), + new EmailAddress("test025@example.com", "Example User") + }; + msg.Personalizations = new List() { + new Personalization() { + Ccs = emails + } + }; + emails = new List + { + new EmailAddress("test026@example.com", "Example User"), + new EmailAddress("test027@example.com", "Example User") + }; + msg.AddCcs(emails); + Assert.Equal("{\"personalizations\":[{\"cc\":[{\"name\":\"Example User\",\"email\":\"test024@example.com\"},{\"name\":\"Example User\",\"email\":\"test025@example.com\"},{\"name\":\"Example User\",\"email\":\"test026@example.com\"},{\"name\":\"Example User\",\"email\":\"test027@example.com\"}]}]}", msg.Serialize()); + + // Personalization not passed in Personalizations exists + msg = new SendGridMessage(); + emails = new List + { + new EmailAddress("test028@example.com", "Example User"), + new EmailAddress("test029@example.com", "Example User") + }; + msg.Personalizations = new List() { + new Personalization() { + Ccs = emails + } + }; + emails = new List + { + new EmailAddress("test030@example.com", "Example User"), + new EmailAddress("test031@example.com", "Example User") + }; + personalization = new Personalization() + { + Ccs = emails + }; + msg.Personalizations.Add(personalization); + emails = new List + { + new EmailAddress("test032@example.com", "Example User"), + new EmailAddress("test033@example.com", "Example User") + }; + msg.AddCcs(emails); + Assert.Equal("{\"personalizations\":[{\"cc\":[{\"name\":\"Example User\",\"email\":\"test028@example.com\"},{\"name\":\"Example User\",\"email\":\"test029@example.com\"},{\"name\":\"Example User\",\"email\":\"test032@example.com\"},{\"name\":\"Example User\",\"email\":\"test033@example.com\"}]},{\"cc\":[{\"name\":\"Example User\",\"email\":\"test030@example.com\"},{\"name\":\"Example User\",\"email\":\"test031@example.com\"}]}]}", msg.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestAddBcc() + { + // Personalization not passed in, Personalization does not exist + var msg = new SendGridMessage(); + msg.AddBcc(new EmailAddress("test001@example.com", "Example User")); + Assert.Equal("{\"personalizations\":[{\"bcc\":[{\"name\":\"Example User\",\"email\":\"test001@example.com\"}]}]}", msg.Serialize()); + + // Personalization passed in, no Personalizations + msg = new SendGridMessage(); + var email = new EmailAddress("test002@example.com", "Example User"); + var personalization = new Personalization() + { + Bccs = new List() + { + email + } + }; + msg.AddBcc(new EmailAddress("test003@example.com", "Example User"), 0, personalization); + Assert.Equal("{\"personalizations\":[{\"bcc\":[{\"name\":\"Example User\",\"email\":\"test002@example.com\"},{\"name\":\"Example User\",\"email\":\"test003@example.com\"}]}]}", msg.Serialize()); + + // Personalization passed in, Personalization exists + msg = new SendGridMessage(); + email = new EmailAddress("test004@example.com", "Example User"); + msg.Personalizations = new List() { + new Personalization() { + Bccs = new List() + { + email + } + } + }; + email = new EmailAddress("test005@example.com", "Example User"); + personalization = new Personalization() + { + Bccs = new List() + { + email + } + }; + msg.AddBcc(new EmailAddress("test006@example.com", "Example User"), 1, personalization); + Assert.Equal("{\"personalizations\":[{\"bcc\":[{\"name\":\"Example User\",\"email\":\"test004@example.com\"}]},{\"bcc\":[{\"name\":\"Example User\",\"email\":\"test005@example.com\"},{\"name\":\"Example User\",\"email\":\"test006@example.com\"}]}]}", msg.Serialize()); + + // Personalization not passed in Personalization exists + msg = new SendGridMessage(); + email = new EmailAddress("test007@example.com", "Example User"); + msg.Personalizations = new List() { + new Personalization() { + Bccs = new List() + { + email + } + } + }; + msg.AddBcc(new EmailAddress("test008@example.com", "Example User")); + Assert.Equal("{\"personalizations\":[{\"bcc\":[{\"name\":\"Example User\",\"email\":\"test007@example.com\"},{\"name\":\"Example User\",\"email\":\"test008@example.com\"}]}]}", msg.Serialize()); + + + // Personalization not passed in Personalizations exists + msg = new SendGridMessage(); + email = new EmailAddress("test009@example.com", "Example User"); + msg.Personalizations = new List() { + new Personalization() { + Bccs = new List() + { + email + } + } + }; + email = new EmailAddress("test010@example.com", "Example User"); + personalization = new Personalization() + { + Bccs = new List() + { + email + } + }; + msg.Personalizations.Add(personalization); + msg.AddBcc(new EmailAddress("test011@example.com", "Example User")); + Assert.Equal("{\"personalizations\":[{\"bcc\":[{\"name\":\"Example User\",\"email\":\"test009@example.com\"},{\"name\":\"Example User\",\"email\":\"test011@example.com\"}]},{\"bcc\":[{\"name\":\"Example User\",\"email\":\"test010@example.com\"}]}]}", msg.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestAddBccWithOutEmailAddressObject() + { + var msg = new SendGridMessage(); + msg.AddBcc("test001@example.com", "Example User"); + Assert.Equal("{\"personalizations\":[{\"bcc\":[{\"name\":\"Example User\",\"email\":\"test001@example.com\"}]}]}", msg.Serialize()); + + msg = new SendGridMessage(); + msg.AddBcc("test001@example.com"); + Assert.Equal("{\"personalizations\":[{\"bcc\":[{\"email\":\"test001@example.com\"}]}]}", msg.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestAddBccArgumentNullExceptionIfNullEmailAddressIsSupplied() + { + var msg = new SendGridMessage(); + Assert.Throws(() => msg.AddBcc(null, "Example User")); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestAddBccArgumentNullExceptionIfEmptyEmailAddressIsSupplied() + { + var msg = new SendGridMessage(); + Assert.Throws(() => msg.AddBcc(string.Empty, "Example User")); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestAddBccs() + { + // Personalization not passed in, Personalization does not exist + var msg = new SendGridMessage(); + var emails = new List + { + new EmailAddress("test012@example.com", "Example User"), + new EmailAddress("test013@example.com", "Example User") + }; + msg.AddBccs(emails); + Assert.Equal("{\"personalizations\":[{\"bcc\":[{\"name\":\"Example User\",\"email\":\"test012@example.com\"},{\"name\":\"Example User\",\"email\":\"test013@example.com\"}]}]}", msg.Serialize()); + + // Personalization passed in, no Personalizations + msg = new SendGridMessage(); + emails = new List + { + new EmailAddress("test014@example.com", "Example User"), + new EmailAddress("test015@example.com", "Example User") + }; + var personalization = new Personalization() + { + Bccs = emails + }; + emails = new List + { + new EmailAddress("test016@example.com", "Example User"), + new EmailAddress("test017@example.com", "Example User") + }; + msg.AddBccs(emails, 0, personalization); + Assert.Equal("{\"personalizations\":[{\"bcc\":[{\"name\":\"Example User\",\"email\":\"test014@example.com\"},{\"name\":\"Example User\",\"email\":\"test015@example.com\"},{\"name\":\"Example User\",\"email\":\"test016@example.com\"},{\"name\":\"Example User\",\"email\":\"test017@example.com\"}]}]}", msg.Serialize()); + + // Personalization passed in, Personalization exists + msg = new SendGridMessage(); + emails = new List + { + new EmailAddress("test018@example.com", "Example User"), + new EmailAddress("test019@example.com", "Example User") + }; + msg.Personalizations = new List() { + new Personalization() { + Bccs = emails + } + }; + emails = new List + { + new EmailAddress("test020@example.com", "Example User"), + new EmailAddress("test021@example.com", "Example User") + }; + personalization = new Personalization() + { + Bccs = emails + }; + emails = new List + { + new EmailAddress("test022@example.com", "Example User"), + new EmailAddress("test023@example.com", "Example User") + }; + msg.AddBccs(emails, 1, personalization); + Assert.Equal("{\"personalizations\":[{\"bcc\":[{\"name\":\"Example User\",\"email\":\"test018@example.com\"},{\"name\":\"Example User\",\"email\":\"test019@example.com\"}]},{\"bcc\":[{\"name\":\"Example User\",\"email\":\"test020@example.com\"},{\"name\":\"Example User\",\"email\":\"test021@example.com\"},{\"name\":\"Example User\",\"email\":\"test022@example.com\"},{\"name\":\"Example User\",\"email\":\"test023@example.com\"}]}]}", msg.Serialize()); + + // Personalization not passed in Personalization exists + msg = new SendGridMessage(); + emails = new List + { + new EmailAddress("test024@example.com", "Example User"), + new EmailAddress("test025@example.com", "Example User") + }; + msg.Personalizations = new List() { + new Personalization() { + Bccs = emails + } + }; + emails = new List + { + new EmailAddress("test026@example.com", "Example User"), + new EmailAddress("test027@example.com", "Example User") + }; + msg.AddBccs(emails); + Assert.Equal("{\"personalizations\":[{\"bcc\":[{\"name\":\"Example User\",\"email\":\"test024@example.com\"},{\"name\":\"Example User\",\"email\":\"test025@example.com\"},{\"name\":\"Example User\",\"email\":\"test026@example.com\"},{\"name\":\"Example User\",\"email\":\"test027@example.com\"}]}]}", msg.Serialize()); + + // Personalization not passed in Personalizations exists + msg = new SendGridMessage(); + emails = new List + { + new EmailAddress("test028@example.com", "Example User"), + new EmailAddress("test029@example.com", "Example User") + }; + msg.Personalizations = new List() { + new Personalization() { + Bccs = emails + } + }; + emails = new List + { + new EmailAddress("test030@example.com", "Example User"), + new EmailAddress("test031@example.com", "Example User") + }; + personalization = new Personalization() + { + Bccs = emails + }; + msg.Personalizations.Add(personalization); + emails = new List + { + new EmailAddress("test032@example.com", "Example User"), + new EmailAddress("test033@example.com", "Example User") + }; + msg.AddBccs(emails); + Assert.Equal("{\"personalizations\":[{\"bcc\":[{\"name\":\"Example User\",\"email\":\"test028@example.com\"},{\"name\":\"Example User\",\"email\":\"test029@example.com\"},{\"name\":\"Example User\",\"email\":\"test032@example.com\"},{\"name\":\"Example User\",\"email\":\"test033@example.com\"}]},{\"bcc\":[{\"name\":\"Example User\",\"email\":\"test030@example.com\"},{\"name\":\"Example User\",\"email\":\"test031@example.com\"}]}]}", msg.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestAddDuplicateEmails() + { + var msg = new SendGridMessage(); + var emails = new List + { + new EmailAddress("user1@example.com", "example user"), + new EmailAddress("USER1@EXAMPLE.COM", "EXAMPLE USER") + }; + msg.AddTos(emails); + msg.AddCcs(emails); + msg.AddBccs(emails); + Assert.Equal("{\"personalizations\":[{\"to\":[{\"name\":\"example user\",\"email\":\"user1@example.com\"}],\"cc\":[{\"name\":\"example user\",\"email\":\"user1@example.com\"}],\"bcc\":[{\"name\":\"example user\",\"email\":\"user1@example.com\"}]}]}", msg.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestSetSubject() + { + // Personalization not passed in, Personalization does not exist + var msg = new SendGridMessage(); + msg.SetSubject("subject1"); + Assert.Equal("{\"personalizations\":[{\"subject\":\"subject1\"}]}", msg.Serialize()); + + // Personalization passed in, no Personalizations + msg = new SendGridMessage(); + var subject = "subject2"; + var personalization = new Personalization() + { + Subject = subject + }; + msg.SetSubject("subject3", 0, personalization); + Assert.Equal("{\"personalizations\":[{\"subject\":\"subject3\"}]}", msg.Serialize()); + + // Personalization passed in, Personalization exists + msg = new SendGridMessage(); + subject = "subject4"; + msg.Personalizations = new List() { + new Personalization() { + Subject = subject + } + }; + subject = "subject5"; + personalization = new Personalization() + { + Subject = subject + }; + msg.SetSubject("subject6", 1, personalization); + Assert.Equal("{\"personalizations\":[{\"subject\":\"subject4\"},{\"subject\":\"subject6\"}]}", msg.Serialize()); + + // Personalization not passed in Personalization exists + msg = new SendGridMessage(); + subject = "subject7"; + msg.Personalizations = new List() { + new Personalization() { + Subject = subject + } + }; + msg.SetSubject("subject8"); + Assert.Equal("{\"personalizations\":[{\"subject\":\"subject8\"}]}", msg.Serialize()); + + // Personalization not passed in Personalizations exists + msg = new SendGridMessage(); + subject = "subject9"; + msg.Personalizations = new List() { + new Personalization() { + Subject = subject + } + }; + subject = "subject10"; + personalization = new Personalization() + { + Subject = subject + }; + msg.Personalizations.Add(personalization); + msg.SetSubject("subject11"); + Assert.Equal("{\"personalizations\":[{\"subject\":\"subject11\"},{\"subject\":\"subject10\"}]}", msg.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestAddHeader() + { + // Personalization not passed in, Personalization does not exist + var msg = new SendGridMessage(); + msg.AddHeader("X-Test", "Test Value"); + Assert.Equal("{\"personalizations\":[{\"headers\":{\"X-Test\":\"Test Value\"}}]}", msg.Serialize()); + + // Personalization passed in, no Personalizations + msg = new SendGridMessage(); + var personalization = new Personalization() + { + Headers = new Dictionary() + { + { "X-Test", "Test Value" } + } + }; + msg.AddHeader("X-Test2", "Test Value 2", 0, personalization); + Assert.Equal("{\"personalizations\":[{\"headers\":{\"X-Test\":\"Test Value\",\"X-Test2\":\"Test Value 2\"}}]}", msg.Serialize()); + + // Personalization passed in, Personalization exists + msg = new SendGridMessage + { + Personalizations = new List() + { + new Personalization() + { + Headers = new Dictionary() + { + {"X-Test3", "Test Value 3"} + } + } + } + }; + personalization = new Personalization() + { + Headers = new Dictionary() + { + { "X-Test4", "Test Value 4" } + } + }; + msg.AddHeader("X-Test5", "Test Value 5", 1, personalization); + Assert.Equal("{\"personalizations\":[{\"headers\":{\"X-Test3\":\"Test Value 3\"}},{\"headers\":{\"X-Test4\":\"Test Value 4\",\"X-Test5\":\"Test Value 5\"}}]}", msg.Serialize()); + + // Personalization not passed in Personalization exists + msg = new SendGridMessage + { + Personalizations = new List() + { + new Personalization() + { + Headers = new Dictionary() + { + {"X-Test6", "Test Value 6"} + } + } + } + }; + msg.AddHeader("X-Test7", "Test Value 7"); + Assert.Equal("{\"personalizations\":[{\"headers\":{\"X-Test6\":\"Test Value 6\",\"X-Test7\":\"Test Value 7\"}}]}", msg.Serialize()); + + // Personalization not passed in Personalizations exists + msg = new SendGridMessage + { + Personalizations = new List() + { + new Personalization() + { + Headers = new Dictionary() + { + {"X-Test8", "Test Value 8"} + } + } + } + }; + personalization = new Personalization() + { + Headers = new Dictionary() + { + { "X-Test9", "Test Value 9" } + } + }; + msg.Personalizations.Add(personalization); + msg.AddHeader("X-Test10", "Test Value 10"); + Assert.Equal("{\"personalizations\":[{\"headers\":{\"X-Test8\":\"Test Value 8\",\"X-Test10\":\"Test Value 10\"}},{\"headers\":{\"X-Test9\":\"Test Value 9\"}}]}", msg.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestAddHeaders() + { + // Personalization not passed in, Personalization does not exist + var msg = new SendGridMessage(); + var headers = new Dictionary { { "X-Test1", "Test Value 1" }, { "X-Test2", "Test Value 2" } }; + msg.AddHeaders(headers); + Assert.Equal("{\"personalizations\":[{\"headers\":{\"X-Test1\":\"Test Value 1\",\"X-Test2\":\"Test Value 2\"}}]}", msg.Serialize()); + + // Personalization passed in, no Personalizations + msg = new SendGridMessage(); + headers = new Dictionary { { "X-Test3", "Test Value 3" }, { "X-Test4", "Test Value 4" } }; + var personalization = new Personalization() + { + Headers = headers + }; + headers = new Dictionary { { "X-Test5", "Test Value 5" }, { "X-Test6", "Test Value 6" } }; + msg.AddHeaders(headers, 0, personalization); + Assert.Equal("{\"personalizations\":[{\"headers\":{\"X-Test3\":\"Test Value 3\",\"X-Test4\":\"Test Value 4\",\"X-Test5\":\"Test Value 5\",\"X-Test6\":\"Test Value 6\"}}]}", msg.Serialize()); + + // Personalization passed in, Personalization exists + msg = new SendGridMessage(); + headers = new Dictionary { { "X-Test7", "Test Value 7" }, { "X-Test8", "Test Value 8" } }; + msg.Personalizations = new List() { + new Personalization() { + Headers = headers + } + }; + headers = new Dictionary { { "X-Test9", "Test Value 9" }, { "X-Test10", "Test Value 10" } }; + personalization = new Personalization() + { + Headers = headers + }; + headers = new Dictionary { { "X-Test11", "Test Value 11" }, { "X-Test12", "Test Value 12" } }; + msg.AddHeaders(headers, 1, personalization); + Assert.Equal("{\"personalizations\":[{\"headers\":{\"X-Test7\":\"Test Value 7\",\"X-Test8\":\"Test Value 8\"}},{\"headers\":{\"X-Test9\":\"Test Value 9\",\"X-Test10\":\"Test Value 10\",\"X-Test11\":\"Test Value 11\",\"X-Test12\":\"Test Value 12\"}}]}", msg.Serialize()); + + // Personalization not passed in Personalization exists + msg = new SendGridMessage(); + headers = new Dictionary { { "X-Test13", "Test Value 13" }, { "X-Test14", "Test Value 14" } }; + msg.Personalizations = new List() { + new Personalization() { + Headers = headers + } + }; + headers = new Dictionary { { "X-Test15", "Test Value 15" }, { "X-Test16", "Test Value 16" } }; + msg.AddHeaders(headers); + Assert.Equal("{\"personalizations\":[{\"headers\":{\"X-Test13\":\"Test Value 13\",\"X-Test14\":\"Test Value 14\",\"X-Test15\":\"Test Value 15\",\"X-Test16\":\"Test Value 16\"}}]}", msg.Serialize()); + + // Personalization not passed in Personalizations exists + msg = new SendGridMessage(); + headers = new Dictionary { { "X-Test17", "Test Value 17" }, { "X-Test18", "Test Value 18" } }; + msg.Personalizations = new List() { + new Personalization() { + Headers = headers + } + }; + headers = new Dictionary { { "X-Test19", "Test Value 19" }, { "X-Test20", "Test Value 20" } }; + personalization = new Personalization() + { + Headers = headers + }; + msg.Personalizations.Add(personalization); + headers = new Dictionary { { "X-Test21", "Test Value 21" }, { "X-Test22", "Test Value 22" } }; + msg.AddHeaders(headers); + Assert.Equal("{\"personalizations\":[{\"headers\":{\"X-Test17\":\"Test Value 17\",\"X-Test18\":\"Test Value 18\",\"X-Test21\":\"Test Value 21\",\"X-Test22\":\"Test Value 22\"}},{\"headers\":{\"X-Test19\":\"Test Value 19\",\"X-Test20\":\"Test Value 20\"}}]}", msg.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestAddSubstitution() + { + // Personalization not passed in, Personalization does not exist + var msg = new SendGridMessage(); + msg.AddSubstitution("-sub1-", "Substituted Value 1"); + Assert.Equal("{\"personalizations\":[{\"substitutions\":{\"-sub1-\":\"Substituted Value 1\"}}]}", msg.Serialize()); + + // Personalization passed in, no Personalizations + msg = new SendGridMessage(); + var personalization = new Personalization() + { + Substitutions = new Dictionary() + { + { "-sub2-", "Substituted Value 2" } + } + }; + msg.AddSubstitution("-sub3-", "Substituted Value 3", 0, personalization); + Assert.Equal("{\"personalizations\":[{\"substitutions\":{\"-sub2-\":\"Substituted Value 2\",\"-sub3-\":\"Substituted Value 3\"}}]}", msg.Serialize()); + + // Personalization passed in, Personalization exists + msg = new SendGridMessage + { + Personalizations = new List() + { + new Personalization() + { + Substitutions = new Dictionary() + { + {"-sub4-", "Substituted Value 4"} + } + } + } + }; + personalization = new Personalization() + { + Substitutions = new Dictionary() + { + { "-sub5-", "Substituted Value 5" } + } + }; + msg.AddSubstitution("-sub6-", "Substituted Value 6", 1, personalization); + Assert.Equal("{\"personalizations\":[{\"substitutions\":{\"-sub4-\":\"Substituted Value 4\"}},{\"substitutions\":{\"-sub5-\":\"Substituted Value 5\",\"-sub6-\":\"Substituted Value 6\"}}]}", msg.Serialize()); + + // Personalization not passed in Personalization exists + msg = new SendGridMessage + { + Personalizations = new List() + { + new Personalization() + { + Substitutions = new Dictionary() + { + {"-sub7-", "Substituted Value 7"} + } + } + } + }; + msg.AddSubstitution("-sub8-", "Substituted Value 8"); + Assert.Equal("{\"personalizations\":[{\"substitutions\":{\"-sub7-\":\"Substituted Value 7\",\"-sub8-\":\"Substituted Value 8\"}}]}", msg.Serialize()); + + // Personalization not passed in Personalizations exists + msg = new SendGridMessage + { + Personalizations = new List() + { + new Personalization() + { + Substitutions = new Dictionary() + { + {"-sub9-", "Substituted Value 9"} + } + } + } + }; + personalization = new Personalization() + { + Substitutions = new Dictionary() + { + { "-sub10-", "Substituted Value 10" } + } + }; + msg.Personalizations.Add(personalization); + msg.AddSubstitution("-sub11-", "Substituted Value 11"); + Assert.Equal("{\"personalizations\":[{\"substitutions\":{\"-sub9-\":\"Substituted Value 9\",\"-sub11-\":\"Substituted Value 11\"}},{\"substitutions\":{\"-sub10-\":\"Substituted Value 10\"}}]}", msg.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestAddSubstitutions() + { + // Personalization not passed in, Personalization does not exist + var msg = new SendGridMessage(); + var substitutions = new Dictionary + { + {"-sub12-", "Substituted Value 12"}, + {"-sub13-", "Substituted Value 13"} + }; + msg.AddSubstitutions(substitutions); + Assert.Equal("{\"personalizations\":[{\"substitutions\":{\"-sub12-\":\"Substituted Value 12\",\"-sub13-\":\"Substituted Value 13\"}}]}", msg.Serialize()); + + // Personalization passed in, no Personalizations + msg = new SendGridMessage(); + substitutions = new Dictionary + { + {"-sub14-", "Substituted Value 14"}, + {"-sub15-", "Substituted Value 15"} + }; + var personalization = new Personalization() + { + Substitutions = substitutions + }; + substitutions = new Dictionary + { + {"-sub16-", "Substituted Value 16"}, + {"-sub17-", "Substituted Value 17"} + }; + msg.AddSubstitutions(substitutions, 0, personalization); + Assert.Equal("{\"personalizations\":[{\"substitutions\":{\"-sub14-\":\"Substituted Value 14\",\"-sub15-\":\"Substituted Value 15\",\"-sub16-\":\"Substituted Value 16\",\"-sub17-\":\"Substituted Value 17\"}}]}", msg.Serialize()); + + // Personalization passed in, Personalization exists + msg = new SendGridMessage(); + substitutions = new Dictionary + { + {"-sub18-", "Substituted Value 18"}, + {"-sub19-", "Substituted Value 19"} + }; + msg.Personalizations = new List() { + new Personalization() { + Substitutions = substitutions + } + }; + substitutions = new Dictionary + { + {"-sub20-", "Substituted Value 20"}, + {"-sub21-", "Substituted Value 21"} + }; + personalization = new Personalization() + { + Substitutions = substitutions + }; + substitutions = new Dictionary + { + {"-sub22-", "Substituted Value 22"}, + {"-sub23-", "Substituted Value 23"} + }; + msg.AddSubstitutions(substitutions, 1, personalization); + Assert.Equal("{\"personalizations\":[{\"substitutions\":{\"-sub18-\":\"Substituted Value 18\",\"-sub19-\":\"Substituted Value 19\"}},{\"substitutions\":{\"-sub20-\":\"Substituted Value 20\",\"-sub21-\":\"Substituted Value 21\",\"-sub22-\":\"Substituted Value 22\",\"-sub23-\":\"Substituted Value 23\"}}]}", msg.Serialize()); + + // Personalization not passed in Personalization exists + msg = new SendGridMessage(); + substitutions = new Dictionary + { + {"-sub24-", "Substituted Value 24"}, + {"-sub25-", "Substituted Value 25"} + }; + msg.Personalizations = new List() { + new Personalization() { + Substitutions = substitutions + } + }; + substitutions = new Dictionary + { + {"-sub26-", "Substituted Value 26"}, + {"-sub27-", "Substituted Value 27"} + }; + msg.AddSubstitutions(substitutions); + Assert.Equal("{\"personalizations\":[{\"substitutions\":{\"-sub24-\":\"Substituted Value 24\",\"-sub25-\":\"Substituted Value 25\",\"-sub26-\":\"Substituted Value 26\",\"-sub27-\":\"Substituted Value 27\"}}]}", msg.Serialize()); + + // Personalization not passed in Personalizations exists + msg = new SendGridMessage(); + substitutions = new Dictionary + { + {"-sub28-", "Substituted Value 28"}, + {"-sub29-", "Substituted Value 29"} + }; + msg.Personalizations = new List() { + new Personalization() { + Substitutions = substitutions + } + }; + substitutions = new Dictionary + { + {"-sub30-", "Substituted Value 30"}, + {"-sub31-", "Substituted Value 31"} + }; + personalization = new Personalization() + { + Substitutions = substitutions + }; + msg.Personalizations.Add(personalization); + substitutions = new Dictionary + { + {"-sub32-", "Substituted Value 32"}, + {"-sub33-", "Substituted Value 33"} + }; + msg.AddSubstitutions(substitutions); + Assert.Equal("{\"personalizations\":[{\"substitutions\":{\"-sub28-\":\"Substituted Value 28\",\"-sub29-\":\"Substituted Value 29\",\"-sub32-\":\"Substituted Value 32\",\"-sub33-\":\"Substituted Value 33\"}},{\"substitutions\":{\"-sub30-\":\"Substituted Value 30\",\"-sub31-\":\"Substituted Value 31\"}}]}", msg.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestSetTemplateData() + { + // Personalization not passed in, Personalization does not exist + var msg = new SendGridMessage(); + var dynamicTemplateData1 = new + { + key12 = "Dynamic Template Data Value 12", + key13 = "Dynamic Template Data Value 13" + }; + msg.SetTemplateData(dynamicTemplateData1); + Assert.Equal("{\"personalizations\":[{\"dynamic_template_data\":{\"key12\":\"Dynamic Template Data Value 12\",\"key13\":\"Dynamic Template Data Value 13\"}}]}", msg.Serialize()); + + // Personalization passed in, no Personalizations + msg = new SendGridMessage(); + var dynamicTemplateData2 = new + { + key14 = "Dynamic Template Data Value 14", + key15 = "Dynamic Template Data Value 15" + }; + var personalization = new Personalization() + { + TemplateData = dynamicTemplateData2 + }; + var dynamicTemplateData3 = new + { + key16 = "Dynamic Template Data Value 16", + key17 = "Dynamic Template Data Value 17" + }; + msg.SetTemplateData(dynamicTemplateData3, 0, personalization); + Assert.Equal("{\"personalizations\":[{\"dynamic_template_data\":{\"key16\":\"Dynamic Template Data Value 16\",\"key17\":\"Dynamic Template Data Value 17\"}}]}", msg.Serialize()); + + // Personalization passed in, Personalization exists + msg = new SendGridMessage(); + var dynamicTemplateData4 = new + { + key18 = "Dynamic Template Data Value 18", + key19 = "Dynamic Template Data Value 19" + }; + msg.Personalizations = new List() { + new Personalization() { + TemplateData = dynamicTemplateData4 + } + }; + var dynamicTemplateData5 = new + { + key20 = "Dynamic Template Data Value 20", + key21 = "Dynamic Template Data Value 21" + }; + personalization = new Personalization() + { + TemplateData = dynamicTemplateData5 + }; + var dynamicTemplateData6 = new + { + key22 = "Dynamic Template Data Value 22", + key23 = "Dynamic Template Data Value 23" + }; + msg.SetTemplateData(dynamicTemplateData6, 1, personalization); + Assert.Equal("{\"personalizations\":[{\"dynamic_template_data\":{\"key18\":\"Dynamic Template Data Value 18\",\"key19\":\"Dynamic Template Data Value 19\"}},{\"dynamic_template_data\":{\"key22\":\"Dynamic Template Data Value 22\",\"key23\":\"Dynamic Template Data Value 23\"}}]}", msg.Serialize()); + + // Personalization not passed in Personalization exists + msg = new SendGridMessage(); + var dynamicTemplateData7 = new + { + key24 = "Dynamic Template Data Value 24", + key25 = "Dynamic Template Data Value 25" + }; + msg.Personalizations = new List() { + new Personalization() { + TemplateData = dynamicTemplateData7 + } + }; + var dynamicTemplateData8 = new + { + key26 = "Dynamic Template Data Value 26", + key27 = "Dynamic Template Data Value 27" + }; + msg.SetTemplateData(dynamicTemplateData8); + Assert.Equal("{\"personalizations\":[{\"dynamic_template_data\":{\"key26\":\"Dynamic Template Data Value 26\",\"key27\":\"Dynamic Template Data Value 27\"}}]}", msg.Serialize()); + + // Personalization not passed in Personalizations exists + msg = new SendGridMessage(); + var dynamicTemplateData9 = new + { + key28 = "Dynamic Template Data Value 28", + key29 = "Dynamic Template Data Value 29" + }; + msg.Personalizations = new List() { + new Personalization() { + TemplateData = dynamicTemplateData9 + } + }; + var dynamicTemplateData10 = new + { + key30 = "Dynamic Template Data Value 30", + key31 = "Dynamic Template Data Value 31" + }; + personalization = new Personalization() + { + TemplateData = dynamicTemplateData10 + }; + msg.Personalizations.Add(personalization); + var dynamicTemplateData11 = new + { + key32 = "Dynamic Template Data Value 32", + key33 = "Dynamic Template Data Value 33" + }; + msg.SetTemplateData(dynamicTemplateData11); + Assert.Equal("{\"personalizations\":[{\"dynamic_template_data\":{\"key32\":\"Dynamic Template Data Value 32\",\"key33\":\"Dynamic Template Data Value 33\"}},{\"dynamic_template_data\":{\"key30\":\"Dynamic Template Data Value 30\",\"key31\":\"Dynamic Template Data Value 31\"}}]}", msg.Serialize()); + + // Complex dynamic template data + msg = new SendGridMessage(); + var dynamicTemplateData12 = new + { + array = new List + { + "Dynamic Template Data Array Value 1", + "Dynamic Template Data Array Value 2" + }, + innerObject = new + { + innerObjectKey1 = "Dynamic Template Data Deep Object Value 1" + } + }; + msg.SetTemplateData(dynamicTemplateData12); + Assert.Equal("{\"personalizations\":[{\"dynamic_template_data\":{\"array\":[\"Dynamic Template Data Array Value 1\",\"Dynamic Template Data Array Value 2\"],\"innerObject\":{\"innerObjectKey1\":\"Dynamic Template Data Deep Object Value 1\"}}}]}", msg.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestAddCustomArg() + { + // Personalization not passed in, Personalization does not exist + var msg = new SendGridMessage(); + msg.AddCustomArg("arg1", "Arguement Value 1"); + Assert.Equal("{\"personalizations\":[{\"custom_args\":{\"arg1\":\"Arguement Value 1\"}}]}", msg.Serialize()); + + // Personalization passed in, no Personalizations + msg = new SendGridMessage(); + var personalization = new Personalization() + { + CustomArgs = new Dictionary() + { + { "arg2", "Arguement Value 2" } + } + }; + msg.AddCustomArg("arg3", "Arguement Value 3", 0, personalization); + Assert.Equal("{\"personalizations\":[{\"custom_args\":{\"arg2\":\"Arguement Value 2\",\"arg3\":\"Arguement Value 3\"}}]}", msg.Serialize()); + + // Personalization passed in, Personalization exists + msg = new SendGridMessage + { + Personalizations = new List() + { + new Personalization() + { + CustomArgs = new Dictionary() + { + {"arg4", "Arguement Value 4"} + } + } + } + }; + personalization = new Personalization() + { + CustomArgs = new Dictionary() + { + { "arg5", "Arguement Value 5" } + } + }; + msg.AddCustomArg("arg6", "Arguement Value 6", 1, personalization); + Assert.Equal("{\"personalizations\":[{\"custom_args\":{\"arg4\":\"Arguement Value 4\"}},{\"custom_args\":{\"arg5\":\"Arguement Value 5\",\"arg6\":\"Arguement Value 6\"}}]}", msg.Serialize()); + + // Personalization not passed in Personalization exists + msg = new SendGridMessage + { + Personalizations = new List() + { + new Personalization() + { + CustomArgs = new Dictionary() + { + {"arg7", "Arguement Value 7"} + } + } + } + }; + msg.AddCustomArg("arg8", "Arguement Value 8"); + Assert.Equal("{\"personalizations\":[{\"custom_args\":{\"arg7\":\"Arguement Value 7\",\"arg8\":\"Arguement Value 8\"}}]}", msg.Serialize()); + + // Personalization not passed in Personalizations exists + msg = new SendGridMessage + { + Personalizations = new List() + { + new Personalization() + { + CustomArgs = new Dictionary() + { + {"arg9", "Arguement Value 9"} + } + } + } + }; + personalization = new Personalization() + { + CustomArgs = new Dictionary() + { + { "arg10", "Arguement Value 10" } + } + }; + msg.Personalizations.Add(personalization); + msg.AddCustomArg("arg11", "Arguement Value 11"); + Assert.Equal("{\"personalizations\":[{\"custom_args\":{\"arg9\":\"Arguement Value 9\",\"arg11\":\"Arguement Value 11\"}},{\"custom_args\":{\"arg10\":\"Arguement Value 10\"}}]}", msg.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestAddCustomArgs() + { + // Personalization not passed in, Personalization does not exist + var msg = new SendGridMessage(); + var customArgs = new Dictionary + { + {"arg12", "Arguement Value 12"}, + {"arg13", "Arguement Value 13"} + }; + msg.AddCustomArgs(customArgs); + Assert.Equal("{\"personalizations\":[{\"custom_args\":{\"arg12\":\"Arguement Value 12\",\"arg13\":\"Arguement Value 13\"}}]}", msg.Serialize()); + + // Personalization passed in, no Personalizations + msg = new SendGridMessage(); + customArgs = new Dictionary + { + {"arg14", "Arguement Value 14"}, + {"arg15", "Arguement Value 15"} + }; + var personalization = new Personalization() + { + CustomArgs = customArgs + }; + customArgs = new Dictionary + { + {"arg16", "Arguement Value 16"}, + {"arg17", "Arguement Value 17"} + }; + msg.AddCustomArgs(customArgs, 0, personalization); + Assert.Equal("{\"personalizations\":[{\"custom_args\":{\"arg14\":\"Arguement Value 14\",\"arg15\":\"Arguement Value 15\",\"arg16\":\"Arguement Value 16\",\"arg17\":\"Arguement Value 17\"}}]}", msg.Serialize()); + + // Personalization passed in, Personalization exists + msg = new SendGridMessage(); + customArgs = new Dictionary + { + {"arg18", "Arguement Value 18"}, + {"arg19", "Arguement Value 19"} + }; + msg.Personalizations = new List() { + new Personalization() { + CustomArgs = customArgs + } + }; + customArgs = new Dictionary + { + {"arg20", "Arguement Value 20"}, + {"arg21", "Arguement Value 21"} + }; + personalization = new Personalization() + { + CustomArgs = customArgs + }; + customArgs = new Dictionary + { + {"arg22", "Arguement Value 22"}, + {"arg23", "Arguement Value 23"} + }; + msg.AddCustomArgs(customArgs, 1, personalization); + Assert.Equal("{\"personalizations\":[{\"custom_args\":{\"arg18\":\"Arguement Value 18\",\"arg19\":\"Arguement Value 19\"}},{\"custom_args\":{\"arg20\":\"Arguement Value 20\",\"arg21\":\"Arguement Value 21\",\"arg22\":\"Arguement Value 22\",\"arg23\":\"Arguement Value 23\"}}]}", msg.Serialize()); + + // Personalization not passed in Personalization exists + msg = new SendGridMessage(); + customArgs = new Dictionary + { + {"arg24", "Arguement Value 24"}, + {"arg25", "Arguement Value 25"} + }; + msg.Personalizations = new List() { + new Personalization() { + CustomArgs = customArgs + } + }; + customArgs = new Dictionary + { + {"arg26", "Arguement Value 26"}, + {"arg27", "Arguement Value 27"} + }; + msg.AddCustomArgs(customArgs); + Assert.Equal("{\"personalizations\":[{\"custom_args\":{\"arg24\":\"Arguement Value 24\",\"arg25\":\"Arguement Value 25\",\"arg26\":\"Arguement Value 26\",\"arg27\":\"Arguement Value 27\"}}]}", msg.Serialize()); + + // Personalization not passed in Personalizations exists + msg = new SendGridMessage(); + customArgs = new Dictionary + { + {"arg28", "Arguement Value 28"}, + {"arg29", "Arguement Value 29"} + }; + msg.Personalizations = new List() { + new Personalization() { + CustomArgs = customArgs + } + }; + customArgs = new Dictionary + { + {"arg30", "Arguement Value 30"}, + {"arg31", "Arguement Value 31"} + }; + personalization = new Personalization() + { + CustomArgs = customArgs + }; + msg.Personalizations.Add(personalization); + customArgs = new Dictionary + { + {"arg32", "Arguement Value 32"}, + {"arg33", "Arguement Value 33"} + }; + msg.AddCustomArgs(customArgs); + Assert.Equal("{\"personalizations\":[{\"custom_args\":{\"arg28\":\"Arguement Value 28\",\"arg29\":\"Arguement Value 29\",\"arg32\":\"Arguement Value 32\",\"arg33\":\"Arguement Value 33\"}},{\"custom_args\":{\"arg30\":\"Arguement Value 30\",\"arg31\":\"Arguement Value 31\"}}]}", msg.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestSendAt() + { + // Personalization not passed in, Personalization does not exist + var msg = new SendGridMessage(); + msg.SetSendAt(1409348513); + Assert.Equal("{\"personalizations\":[{\"send_at\":1409348513}]}", msg.Serialize()); + + // Personalization passed in, no Personalizations + msg = new SendGridMessage(); + var sendAt = 1409348513; + var personalization = new Personalization() + { + SendAt = sendAt + }; + msg.SetSendAt(1409348513, 0, personalization); + Assert.Equal("{\"personalizations\":[{\"send_at\":1409348513}]}", msg.Serialize()); + + // Personalization passed in, Personalization exists + msg = new SendGridMessage(); + sendAt = 1409348513; + msg.Personalizations = new List() { + new Personalization() { + SendAt = sendAt + } + }; + sendAt = 1409348513; + personalization = new Personalization() + { + SendAt = sendAt + }; + msg.SetSendAt(1409348513, 1, personalization); + Assert.Equal("{\"personalizations\":[{\"send_at\":1409348513},{\"send_at\":1409348513}]}", msg.Serialize()); + + // Personalization not passed in Personalization exists + msg = new SendGridMessage(); + sendAt = 1409348513; + msg.Personalizations = new List() { + new Personalization() { + SendAt = sendAt + } + }; + msg.SetSendAt(1409348513); + Assert.Equal("{\"personalizations\":[{\"send_at\":1409348513}]}", msg.Serialize()); + + // Personalization not passed in Personalizations exists + msg = new SendGridMessage(); + sendAt = 1409348513; + msg.Personalizations = new List() { + new Personalization() { + SendAt = sendAt + } + }; + sendAt = 1409348513; + personalization = new Personalization() + { + SendAt = sendAt + }; + msg.Personalizations.Add(personalization); + msg.SetSendAt(1409348513); + Assert.Equal("{\"personalizations\":[{\"send_at\":1409348513},{\"send_at\":1409348513}]}", msg.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestSetFrom() + { + var msg = new SendGridMessage(); + var fromEmail = new EmailAddress() + { + Email = "test1@example.com", + Name = "Test User1" + }; + msg.SetFrom(fromEmail); + Assert.Equal("{\"from\":{\"name\":\"Test User1\",\"email\":\"test1@example.com\"}}", msg.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestSetFromArgumentNullExceptionIfNullEmailAddressIsSupplied() + { + var msg = new SendGridMessage(); + Assert.Throws(() => msg.SetFrom(null, "Example User")); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestSetFromArgumentEmptyExceptionIfEmptyEmailAddressIsSupplied() + { + var msg = new SendGridMessage(); + Assert.Throws(() => msg.SetFrom(string.Empty, "Example User")); + } + + + [Fact(Skip = SkipConfigureApiKey)] + public void TestSetFromWithOutEmailAddressObject() + { + var msg = new SendGridMessage(); + msg.SetFrom("test1@example.com", "Test User1"); + Assert.Equal("{\"from\":{\"name\":\"Test User1\",\"email\":\"test1@example.com\"}}", msg.Serialize()); + + msg = new SendGridMessage(); + msg.SetFrom("test1@example.com"); + Assert.Equal("{\"from\":{\"email\":\"test1@example.com\"}}", msg.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestSetReplyTo() + { + var msg = new SendGridMessage(); + var replyToEmail = new EmailAddress() + { + Email = "test2@example.com", + Name = "Test User2" + }; + msg.SetReplyTo(replyToEmail); + Assert.Equal("{\"reply_to\":{\"name\":\"Test User2\",\"email\":\"test2@example.com\"}}", msg.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestAddReplyTos() + { + var msg = new SendGridMessage(); + msg.AddReplyTo("test2@example.com", "Test User2"); + Assert.Equal("{\"reply_to_list\":[{\"name\":\"Test User2\",\"email\":\"test2@example.com\"}]}", msg.Serialize()); + + msg = new SendGridMessage(); + msg.AddReplyTo("test1@example.com", "Test User1"); + msg.AddReplyTo("test2@example.com", "Test User2"); + Assert.Equal("{\"reply_to_list\":[{\"name\":\"Test User1\",\"email\":\"test1@example.com\"},{\"name\":\"Test User2\",\"email\":\"test2@example.com\"}]}", msg.Serialize()); + + msg = new SendGridMessage(); + msg.AddReplyTos(new List { new EmailAddress() { Email = "test1@example.com" }, new EmailAddress() { Email = "test2@example.com", Name = "Test User2" } }); + Assert.Equal("{\"reply_to_list\":[{\"email\":\"test1@example.com\"},{\"name\":\"Test User2\",\"email\":\"test2@example.com\"}]}", msg.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestSetGlobalSubject() + { + var msg = new SendGridMessage(); + var globalSubject = "subject1"; + msg.SetGlobalSubject(globalSubject); + Assert.Equal("{\"subject\":\"subject1\"}", msg.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestAddContent() + { + //Content object does not exist + var msg = new SendGridMessage(); + msg.AddContent(MimeType.Html, "content1"); + Assert.Equal("{\"content\":[{\"type\":\"text/html\",\"value\":\"content1\"}]}", msg.Serialize()); + + msg.AddContent(MimeType.Text, "content2"); + Assert.Equal("{\"content\":[{\"type\":\"text/plain\",\"value\":\"content2\"},{\"type\":\"text/html\",\"value\":\"content1\"}]}", msg.Serialize()); + + //New content objects have invalid values + msg.AddContent(MimeType.Text, ""); + Assert.Equal("{\"content\":[{\"type\":\"text/plain\",\"value\":\"content2\"},{\"type\":\"text/html\",\"value\":\"content1\"}]}", msg.Serialize()); + + msg.AddContent(MimeType.Text, null); + Assert.Equal("{\"content\":[{\"type\":\"text/plain\",\"value\":\"content2\"},{\"type\":\"text/html\",\"value\":\"content1\"}]}", msg.Serialize()); + + msg.AddContent("", "Content4"); + Assert.Equal("{\"content\":[{\"type\":\"text/plain\",\"value\":\"content2\"},{\"type\":\"text/html\",\"value\":\"content1\"}]}", msg.Serialize()); + + msg.AddContent(null, "Content5"); + Assert.Equal("{\"content\":[{\"type\":\"text/plain\",\"value\":\"content2\"},{\"type\":\"text/html\",\"value\":\"content1\"}]}", msg.Serialize()); + + + //Content object exists + msg = new SendGridMessage(); + var content = new Content() + { + Type = MimeType.Html, + Value = "content3" + }; + msg.Contents = new List { content }; + msg.AddContent(MimeType.Text, "content6"); + Assert.Equal("{\"content\":[{\"type\":\"text/plain\",\"value\":\"content6\"},{\"type\":\"text/html\",\"value\":\"content3\"}]}", msg.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestAddContents() + { + //Content object does not exist + var msg = new SendGridMessage(); + var contents = new List(); + var content = new Content() + { + Type = MimeType.Html, + Value = "content7" + }; + contents.Add(content); + content = new Content() + { + Type = MimeType.Text, + Value = "content8" + }; + contents.Add(content); + msg.AddContents(contents); + Assert.Equal("{\"content\":[{\"type\":\"text/plain\",\"value\":\"content8\"},{\"type\":\"text/html\",\"value\":\"content7\"}]}", msg.Serialize()); + + //New content objects have invalid values + contents = new List(); + content = new Content() + { + Type = MimeType.Text, + Value = "" + }; + contents.Add(content); + content = new Content() + { + Type = MimeType.Text, + Value = null + }; + contents.Add(content); + content = new Content() + { + Type = "", + Value = "Content9" + }; + contents.Add(content); + content = new Content() + { + Type = null, + Value = "Content10" + }; + contents.Add(content); + msg.AddContents(contents); + Assert.Equal("{\"content\":[{\"type\":\"text/plain\",\"value\":\"content8\"},{\"type\":\"text/html\",\"value\":\"content7\"}]}", msg.Serialize()); + + //Content object exists + msg = new SendGridMessage(); + content = new Content() + { + Type = MimeType.Html, + Value = "content7" + }; + msg.Contents = new List { content }; + contents = new List(); + content = new Content() + { + Type = "fake/mimetype", + Value = "content8" + }; + contents.Add(content); + content = new Content() + { + Type = MimeType.Text, + Value = "content9" + }; + contents.Add(content); + msg.AddContents(contents); + Assert.Equal("{\"content\":[{\"type\":\"text/plain\",\"value\":\"content9\"},{\"type\":\"text/html\",\"value\":\"content7\"},{\"type\":\"fake/mimetype\",\"value\":\"content8\"}]}", msg.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestAddAttachment() + { + //Attachment object does not exist + var msg = new SendGridMessage(); + msg.AddAttachment("filename1", "base64content1", "jpg", "inline", "id1"); + Assert.Equal("{\"attachments\":[{\"content\":\"base64content1\",\"type\":\"jpg\",\"filename\":\"filename1\",\"disposition\":\"inline\",\"content_id\":\"id1\"}]}", msg.Serialize()); + + //Attachment object exists + msg = new SendGridMessage(); + var attachment = new Attachment() + { + Filename = "filename2", + Content = "base64content2", + Type = "jpg", + Disposition = "inline", + ContentId = "id2" + }; + msg.Attachments = new List { attachment }; + msg.AddAttachment("filename3", "base64content3", "jpg", "inline", "id3"); + Assert.Equal("{\"attachments\":[{\"content\":\"base64content2\",\"type\":\"jpg\",\"filename\":\"filename2\",\"disposition\":\"inline\",\"content_id\":\"id2\"},{\"content\":\"base64content3\",\"type\":\"jpg\",\"filename\":\"filename3\",\"disposition\":\"inline\",\"content_id\":\"id3\"}]}", msg.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestAddAttachments() + { + //Attachment object does not exist + var msg = new SendGridMessage(); + var attachments = new List(); + var attachment = new Attachment() + { + Filename = "filename4", + Content = "base64content4", + Type = "jpg", + Disposition = "inline", + ContentId = "id4" + }; + attachments.Add(attachment); + attachment = new Attachment() + { + Filename = "filename5", + Content = "base64content5", + Type = "jpg", + Disposition = "inline", + ContentId = "id5" + }; + attachments.Add(attachment); + msg.AddAttachments(attachments); + Assert.Equal("{\"attachments\":[{\"content\":\"base64content4\",\"type\":\"jpg\",\"filename\":\"filename4\",\"disposition\":\"inline\",\"content_id\":\"id4\"},{\"content\":\"base64content5\",\"type\":\"jpg\",\"filename\":\"filename5\",\"disposition\":\"inline\",\"content_id\":\"id5\"}]}", msg.Serialize()); + + //Attachment object exists + msg = new SendGridMessage(); + attachment = new Attachment() + { + Filename = "filename6", + Content = "base64content6", + Type = "jpg", + Disposition = "inline", + ContentId = "id6" + }; + msg.Attachments = new List { attachment }; + attachments = new List(); + attachment = new Attachment() + { + Filename = "filename7", + Content = "base64content7", + Type = "jpg", + Disposition = "inline", + ContentId = "id7" + }; + attachments.Add(attachment); + attachment = new Attachment() + { + Filename = "filename8", + Content = "base64content8", + Type = "jpg", + Disposition = "inline", + ContentId = "id8" + }; + attachments.Add(attachment); + msg.AddAttachments(attachments); + Assert.Equal("{\"attachments\":[{\"content\":\"base64content6\",\"type\":\"jpg\",\"filename\":\"filename6\",\"disposition\":\"inline\",\"content_id\":\"id6\"},{\"content\":\"base64content7\",\"type\":\"jpg\",\"filename\":\"filename7\",\"disposition\":\"inline\",\"content_id\":\"id7\"},{\"content\":\"base64content8\",\"type\":\"jpg\",\"filename\":\"filename8\",\"disposition\":\"inline\",\"content_id\":\"id8\"}]}", msg.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestSetTemplateId() + { + var msg = new SendGridMessage(); + msg.SetTemplateId("template_id1"); + Assert.Equal("{\"template_id\":\"template_id1\"}", msg.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestAddSection() + { + // Section object does not exist + var msg = new SendGridMessage(); + msg.AddSection("section_key1", "section_value1"); + Assert.Equal("{\"sections\":{\"section_key1\":\"section_value1\"}}", msg.Serialize()); + + // Section object exists + msg.AddSection("section_key2", "section_value2"); + Assert.Equal("{\"sections\":{\"section_key1\":\"section_value1\",\"section_key2\":\"section_value2\"}}", msg.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestAddSections() + { + // Section object does not exist + var msg = new SendGridMessage(); + var sections = new Dictionary() + { + { "section_key3", "section_value3" }, + { "section_key4", "section_value4" } + }; + msg.AddSections(sections); + Assert.Equal("{\"sections\":{\"section_key3\":\"section_value3\",\"section_key4\":\"section_value4\"}}", msg.Serialize()); + + // Section object exists + sections = new Dictionary() + { + { "section_key5", "section_value5" }, + { "section_key6", "section_value6" } + }; + msg.AddSections(sections); + Assert.Equal("{\"sections\":{\"section_key3\":\"section_value3\",\"section_key4\":\"section_value4\",\"section_key5\":\"section_value5\",\"section_key6\":\"section_value6\"}}", msg.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestAddGlobalHeader() + { + // Header object does not exist + var msg = new SendGridMessage(); + msg.AddGlobalHeader("X-Header1", "Value1"); + Assert.Equal("{\"headers\":{\"X-Header1\":\"Value1\"}}", msg.Serialize()); + + // Header object exists + msg.AddGlobalHeader("X-Header2", "Value2"); + Assert.Equal("{\"headers\":{\"X-Header1\":\"Value1\",\"X-Header2\":\"Value2\"}}", msg.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestAddGlobalHeaders() + { + // Header object does not exist + var msg = new SendGridMessage(); + var headers = new Dictionary() + { + { "X-Header3", "Value3" }, + { "X-Header4", "Value4" } + }; + msg.AddGlobalHeaders(headers); + Assert.Equal("{\"headers\":{\"X-Header3\":\"Value3\",\"X-Header4\":\"Value4\"}}", msg.Serialize()); + + // Header object exists + headers = new Dictionary() + { + { "X-Header5", "Value5" }, + { "X-Header6", "Value6" } + }; + msg.AddGlobalHeaders(headers); + Assert.Equal("{\"headers\":{\"X-Header3\":\"Value3\",\"X-Header4\":\"Value4\",\"X-Header5\":\"Value5\",\"X-Header6\":\"Value6\"}}", msg.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestAddCategory() + { + //Categories object does not exist + var msg = new SendGridMessage(); + msg.AddCategory("category1"); + Assert.Equal("{\"categories\":[\"category1\"]}", msg.Serialize()); + + msg.AddCategory("category2"); + Assert.Equal("{\"categories\":[\"category1\",\"category2\"]}", msg.Serialize()); + + //Categories object exists + msg = new SendGridMessage { Categories = new List { "category3" } }; + msg.AddCategory("category4"); + Assert.Equal("{\"categories\":[\"category3\",\"category4\"]}", msg.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestAddCategories() + { + //Categories object does not exist + var msg = new SendGridMessage(); + var categories = new List { "category5", "category6" }; + msg.AddCategories(categories); + Assert.Equal("{\"categories\":[\"category5\",\"category6\"]}", msg.Serialize()); + + //Categories object exists + msg = new SendGridMessage { Categories = new List { "category7", "category8" } }; + categories = new List { "category9", "category10" }; + msg.AddCategories(categories); + Assert.Equal("{\"categories\":[\"category7\",\"category8\",\"category9\",\"category10\"]}", msg.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestAddGlobalCustomArg() + { + // CustomArgs object does not exist + var msg = new SendGridMessage(); + msg.AddGlobalCustomArg("Key1", "Value1"); + Assert.Equal("{\"custom_args\":{\"Key1\":\"Value1\"}}", msg.Serialize()); + + // CustomArgs object exists + msg.AddGlobalCustomArg("Key2", "Value2"); + Assert.Equal("{\"custom_args\":{\"Key1\":\"Value1\",\"Key2\":\"Value2\"}}", msg.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestAddGlobalCustomArgs() + { + // CustomArgs object does not exist + var msg = new SendGridMessage(); + var customArgs = new Dictionary() + { + { "Key3", "Value3" }, + { "Key4", "Value4" } + }; + msg.AddGlobalCustomArgs(customArgs); + Assert.Equal("{\"custom_args\":{\"Key3\":\"Value3\",\"Key4\":\"Value4\"}}", msg.Serialize()); + + // CustomArgs object exists + customArgs = new Dictionary() + { + { "Key5", "Value5" }, + { "Key6", "Value6" } + }; + msg.AddGlobalCustomArgs(customArgs); + Assert.Equal("{\"custom_args\":{\"Key3\":\"Value3\",\"Key4\":\"Value4\",\"Key5\":\"Value5\",\"Key6\":\"Value6\"}}", msg.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestSetGlobalSendAt() + { + var msg = new SendGridMessage(); + msg.SetGlobalSendAt(1409348513); + Assert.Equal("{\"send_at\":1409348513}", msg.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestSetBatchId() + { + var msg = new SendGridMessage(); + msg.SetBatchId("batch_id"); + Assert.Equal("{\"batch_id\":\"batch_id\"}", msg.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestSetAsm() + { + var msg = new SendGridMessage(); + var groupsToDisplay = new List() + { + 1, 2, 3, 4, 5 + }; + msg.SetAsm(1, groupsToDisplay); + Assert.Equal("{\"asm\":{\"group_id\":1,\"groups_to_display\":[1,2,3,4,5]}}", msg.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestSetIpPoolName() + { + var msg = new SendGridMessage(); + msg.SetIpPoolName("pool_name"); + Assert.Equal("{\"ip_pool_name\":\"pool_name\"}", msg.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestSetBccSetting() + { + //MailSettings object does not exist + var msg = new SendGridMessage(); + msg.SetBccSetting(true, "test@example.com"); + Assert.Equal("{\"mail_settings\":{\"bcc\":{\"enable\":true,\"email\":\"test@example.com\"}}}", msg.Serialize()); + + //MailSettings object exists + msg = new SendGridMessage(); + var bccSetting = new BCCSettings() + { + Enable = false, + Email = "test2@example.com" + }; + msg.MailSettings = new MailSettings() + { + BccSettings = bccSetting + }; + msg.SetBccSetting(true, "test3@example.com"); + Assert.Equal("{\"mail_settings\":{\"bcc\":{\"enable\":true,\"email\":\"test3@example.com\"}}}", msg.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestSetBypassListManagement() + { + //MailSettings object does not exist + var msg = new SendGridMessage(); + msg.SetBypassListManagement(false); + Assert.Equal("{\"mail_settings\":{\"bypass_list_management\":{\"enable\":false}}}", msg.Serialize()); + + //MailSettings object exists + msg = new SendGridMessage(); + var bypassListManagement = new BypassListManagement() + { + Enable = true + }; + msg.MailSettings = new MailSettings() + { + BypassListManagement = bypassListManagement + }; + msg.SetBypassListManagement(true); + Assert.Equal("{\"mail_settings\":{\"bypass_list_management\":{\"enable\":true}}}", msg.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestSetBypassSpamManagement() + { + //MailSettings object does not exist + var msg = new SendGridMessage(); + msg.SetBypassSpamManagement(false); + Assert.Equal("{\"mail_settings\":{\"bypass_spam_management\":{\"enable\":false}}}", msg.Serialize()); + + //MailSettings object exists + msg = new SendGridMessage(); + var bypassSpamManagement = new BypassSpamManagement() + { + Enable = true + }; + msg.MailSettings = new MailSettings() + { + BypassSpamManagement = bypassSpamManagement + }; + msg.SetBypassSpamManagement(true); + Assert.Equal("{\"mail_settings\":{\"bypass_spam_management\":{\"enable\":true}}}", msg.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestSetBypassBounceManagement() + { + //MailSettings object does not exist + var msg = new SendGridMessage(); + msg.SetBypassBounceManagement(false); + Assert.Equal("{\"mail_settings\":{\"bypass_bounce_management\":{\"enable\":false}}}", msg.Serialize()); + + //MailSettings object exists + msg = new SendGridMessage(); + var bypassBounceManagement = new BypassBounceManagement() + { + Enable = true + }; + msg.MailSettings = new MailSettings() + { + BypassBounceManagement = bypassBounceManagement + }; + msg.SetBypassBounceManagement(true); + Assert.Equal("{\"mail_settings\":{\"bypass_bounce_management\":{\"enable\":true}}}", msg.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestSetBypassUnsubscribeManagement() + { + //MailSettings object does not exist + var msg = new SendGridMessage(); + msg.SetBypassUnsubscribeManagement(false); + Assert.Equal("{\"mail_settings\":{\"bypass_unsubscribe_management\":{\"enable\":false}}}", msg.Serialize()); + + //MailSettings object exists + msg = new SendGridMessage(); + var bypassUnsubscribeManagement = new BypassUnsubscribeManagement() + { + Enable = true + }; + msg.MailSettings = new MailSettings() + { + BypassUnsubscribeManagement = bypassUnsubscribeManagement + }; + msg.SetBypassUnsubscribeManagement(true); + Assert.Equal("{\"mail_settings\":{\"bypass_unsubscribe_management\":{\"enable\":true}}}", msg.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestSetFooterSetting() + { + //MailSettings object does not exist + var msg = new SendGridMessage(); + msg.SetFooterSetting(true, "html1", "text1"); + Assert.Equal("{\"mail_settings\":{\"footer\":{\"enable\":true,\"text\":\"text1\",\"html\":\"html1\"}}}", msg.Serialize()); + + //MailSettings object exists + msg = new SendGridMessage(); + var footerSetting = new FooterSettings() + { + Enable = false, + Html = "html2", + Text = "text2" + }; + msg.MailSettings = new MailSettings() + { + FooterSettings = footerSetting + }; + msg.SetFooterSetting(true, "html3", "text3"); + Assert.Equal("{\"mail_settings\":{\"footer\":{\"enable\":true,\"text\":\"text3\",\"html\":\"html3\"}}}", msg.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestSetSandBoxMode() + { + //MailSettings object does not exist + var msg = new SendGridMessage(); + msg.SetSandBoxMode(true); + Assert.Equal("{\"mail_settings\":{\"sandbox_mode\":{\"enable\":true}}}", msg.Serialize()); + + //MailSettings object exists + msg = new SendGridMessage(); + var sandBoxMode = new SandboxMode() + { + Enable = false + }; + msg.MailSettings = new MailSettings() + { + SandboxMode = sandBoxMode + }; + msg.SetSandBoxMode(true); + Assert.Equal("{\"mail_settings\":{\"sandbox_mode\":{\"enable\":true}}}", msg.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestSetSpamCheck() + { + //MailSettings object does not exist + var msg = new SendGridMessage(); + msg.SetSpamCheck(true, 1, "http://fakeurl.com"); + Assert.Equal("{\"mail_settings\":{\"spam_check\":{\"enable\":true,\"threshold\":1,\"post_to_url\":\"http://fakeurl.com\"}}}", msg.Serialize()); + + //MailSettings object exists + msg = new SendGridMessage(); + var spamCheck = new SpamCheck() + { + Enable = false, + Threshold = 3, + PostToUrl = "http://fakeurl1.com" + }; + msg.MailSettings = new MailSettings() + { + SpamCheck = spamCheck + }; + msg.SetSpamCheck(true, 2, "http://fakeurl2.com"); + Assert.Equal("{\"mail_settings\":{\"spam_check\":{\"enable\":true,\"threshold\":2,\"post_to_url\":\"http://fakeurl2.com\"}}}", msg.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestSetClickTracking() + { + //TrackingSettings object does not exist + var msg = new SendGridMessage(); + msg.SetClickTracking(false, false); + Assert.Equal("{\"tracking_settings\":{\"click_tracking\":{\"enable\":false,\"enable_text\":false}}}", msg.Serialize()); + + //TrackingSettings object exists + msg = new SendGridMessage(); + var clickTrackingSetting = new ClickTracking() + { + Enable = false, + EnableText = false + }; + msg.TrackingSettings = new TrackingSettings() + { + ClickTracking = clickTrackingSetting + }; + msg.SetClickTracking(true, true); + Assert.Equal("{\"tracking_settings\":{\"click_tracking\":{\"enable\":true,\"enable_text\":true}}}", msg.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestSetOpenTracking() + { + //TrackingSettings object does not exist + var msg = new SendGridMessage(); + msg.SetOpenTracking(false, "subtag1"); + Assert.Equal("{\"tracking_settings\":{\"open_tracking\":{\"enable\":false,\"substitution_tag\":\"subtag1\"}}}", msg.Serialize()); + + //TrackingSettings object exists + msg = new SendGridMessage(); + var openTrackingSetting = new OpenTracking() + { + Enable = false, + SubstitutionTag = "subtag2" + }; + msg.TrackingSettings = new TrackingSettings() + { + OpenTracking = openTrackingSetting + }; + msg.SetOpenTracking(false, "subtag3"); + Assert.Equal("{\"tracking_settings\":{\"open_tracking\":{\"enable\":false,\"substitution_tag\":\"subtag3\"}}}", msg.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestSetSubscriptionTracking() + { + //TrackingSettings object does not exist + var msg = new SendGridMessage(); + msg.SetSubscriptionTracking(true, "html1", "text1", "sub1"); + Assert.Equal("{\"tracking_settings\":{\"subscription_tracking\":{\"enable\":true,\"text\":\"text1\",\"html\":\"html1\",\"substitution_tag\":\"sub1\"}}}", msg.Serialize()); + + //TrackingSettings object exists + msg = new SendGridMessage(); + var subscriptionTracking = new SubscriptionTracking() + { + Enable = false, + Html = "html2", + Text = "text2", + SubstitutionTag = "sub2" + }; + msg.TrackingSettings = new TrackingSettings() + { + SubscriptionTracking = subscriptionTracking + }; + msg.SetSubscriptionTracking(true, "html3", "text3", "sub3"); + Assert.Equal("{\"tracking_settings\":{\"subscription_tracking\":{\"enable\":true,\"text\":\"text3\",\"html\":\"html3\",\"substitution_tag\":\"sub3\"}}}", msg.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestSetGoogleAnalytics() + { + //TrackingSettings object does not exist + var msg = new SendGridMessage(); + msg.SetGoogleAnalytics(true, "campaign1", "content1", "medium1", "source1", "term1"); + Assert.Equal("{\"tracking_settings\":{\"ganalytics\":{\"enable\":true,\"utm_source\":\"source1\",\"utm_medium\":\"medium1\",\"utm_term\":\"term1\",\"utm_content\":\"content1\",\"utm_campaign\":\"campaign1\"}}}", msg.Serialize()); + + //TrackingSettings object exists + msg = new SendGridMessage(); + var googleAnalytics = new Ganalytics() + { + Enable = false, + UtmCampaign = "campaign2", + UtmContent = "content2", + UtmMedium = "medium2", + UtmSource = "source2", + UtmTerm = "term2" + }; + msg.TrackingSettings = new TrackingSettings() + { + Ganalytics = googleAnalytics + }; + msg.SetGoogleAnalytics(true, "campaign3", "content3", "medium3", "source3", "term3"); + Assert.Equal("{\"tracking_settings\":{\"ganalytics\":{\"enable\":true,\"utm_source\":\"source3\",\"utm_medium\":\"medium3\",\"utm_term\":\"term3\",\"utm_content\":\"content3\",\"utm_campaign\":\"campaign3\"}}}", msg.Serialize()); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestAccessSettingsActivityGet() + { + var sg = GetClient("200"); + var queryParams = @"{ + 'limit': 1 +}"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "access_settings/activity", queryParams: queryParams); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestAccessSettingsWhitelistPost() + { + var sg = GetClient("201"); + var data = @"{ + 'ips': [ + { + 'ip': '192.168.1.1' + }, + { + 'ip': '192.*.*.*' + }, + { + 'ip': '192.168.1.3/32' + } + ] +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var response = await sg.RequestAsync(method: SendGridClient.Method.POST, urlPath: "access_settings/whitelist", requestBody: data); + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestAccessSettingsWhitelistGet() + { + var sg = GetClient("200"); + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "access_settings/whitelist"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestAccessSettingsWhitelistDelete() + { + var sg = GetClient("204"); + var data = @"{ + 'ids': [ + 1, + 2, + 3 + ] +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var response = await sg.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "access_settings/whitelist", requestBody: data); + Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestAccessSettingsWhitelistRuleIdGet() + { + var sg = GetClient("200"); + var rule_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "access_settings/whitelist/" + rule_id); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestAccessSettingsWhitelistRuleIdDelete() + { + var sg = GetClient("204"); + var rule_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "access_settings/whitelist/" + rule_id); + Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestAlertsPost() + { + var sg = GetClient("201"); + var data = @"{ + 'email_to': 'example@example.com', + 'frequency': 'daily', + 'type': 'stats_notification' +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var response = await sg.RequestAsync(method: SendGridClient.Method.POST, urlPath: "alerts", requestBody: data); + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestAlertsGet() + { + var sg = GetClient("200"); + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "alerts"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestAlertsAlertIdPatch() + { + var sg = GetClient("200"); + var data = @"{ + 'email_to': 'example@example.com' +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var alert_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.PATCH, urlPath: "alerts/" + alert_id, requestBody: data); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestAlertsAlertIdGet() + { + var sg = GetClient("200"); + var alert_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "alerts/" + alert_id); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestAlertsAlertIdDelete() + { + var sg = GetClient("204"); + var alert_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "alerts/" + alert_id); + Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestApiKeysPost() + { + var sg = GetClient("201"); + var data = @"{ + 'name': 'My API Key', + 'sample': 'data', + 'scopes': [ + 'mail.send', + 'alerts.create', + 'alerts.read' + ] +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var response = await sg.RequestAsync(method: SendGridClient.Method.POST, urlPath: "api_keys", requestBody: data); + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestApiKeysGet() + { + var sg = GetClient("200"); + var queryParams = @"{ + 'limit': 1 +}"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "api_keys", queryParams: queryParams); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestApiKeysApiKeyIdPut() + { + var sg = GetClient("200"); + var data = @"{ + 'name': 'A New Hope', + 'scopes': [ + 'user.profile.read', + 'user.profile.update' + ] +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var api_key_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.PUT, urlPath: "api_keys/" + api_key_id, requestBody: data); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestApiKeysApiKeyIdPatch() + { + var sg = GetClient("200"); + var data = @"{ + 'name': 'A New Hope' +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var api_key_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.PATCH, urlPath: "api_keys/" + api_key_id, requestBody: data); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestApiKeysApiKeyIdGet() + { + var sg = GetClient("200"); + var api_key_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "api_keys/" + api_key_id); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestApiKeysApiKeyIdDelete() + { + var sg = GetClient("204"); + var api_key_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "api_keys/" + api_key_id); + Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestAsmGroupsPost() + { + var sg = GetClient("201"); + var data = @"{ + 'description': 'Suggestions for products our users might like.', + 'is_default': true, + 'name': 'Product Suggestions' +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var response = await sg.RequestAsync(method: SendGridClient.Method.POST, urlPath: "asm/groups", requestBody: data); + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestAsmGroupsGet() + { + var sg = GetClient("200"); + var queryParams = @"{ + 'id': 1 +}"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "asm/groups", queryParams: queryParams); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestAsmGroupsGroupIdPatch() + { + var sg = GetClient("201"); + var data = @"{ + 'description': 'Suggestions for items our users might like.', + 'id': 103, + 'name': 'Item Suggestions' +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var group_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.PATCH, urlPath: "asm/groups/" + group_id, requestBody: data); + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestAsmGroupsGroupIdGet() + { + var sg = GetClient("200"); + var group_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "asm/groups/" + group_id); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestAsmGroupsGroupIdDelete() + { + var sg = GetClient("204"); + var group_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "asm/groups/" + group_id); + Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestAsmGroupsGroupIdSuppressionsPost() + { + var sg = GetClient("201"); + var data = @"{ + 'recipient_emails': [ + 'test1@example.com', + 'test2@example.com' + ] +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var group_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.POST, urlPath: "asm/groups/" + group_id + "/suppressions", requestBody: data); + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestAsmGroupsGroupIdSuppressionsGet() + { + var sg = GetClient("200"); + var group_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "asm/groups/" + group_id + "/suppressions"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestAsmGroupsGroupIdSuppressionsSearchPost() + { + var sg = GetClient("200"); + var data = @"{ + 'recipient_emails': [ + 'exists1@example.com', + 'exists2@example.com', + 'doesnotexists@example.com' + ] +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var group_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.POST, urlPath: "asm/groups/" + group_id + "/suppressions/search", requestBody: data); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestAsmGroupsGroupIdSuppressionsEmailDelete() + { + var sg = GetClient("204"); + var group_id = "test_url_param"; + var email = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "asm/groups/" + group_id + "/suppressions/" + email); + Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestAsmSuppressionsGet() + { + var sg = GetClient("200"); + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "asm/suppressions"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestAsmSuppressionsGlobalPost() + { + var sg = GetClient("201"); + var data = @"{ + 'recipient_emails': [ + 'test1@example.com', + 'test2@example.com' + ] +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var response = await sg.RequestAsync(method: SendGridClient.Method.POST, urlPath: "asm/suppressions/global", requestBody: data); + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestAsmSuppressionsGlobalEmailGet() + { + var sg = GetClient("200"); + var email = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "asm/suppressions/global/" + email); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestAsmSuppressionsGlobalEmailDelete() + { + var sg = GetClient("204"); + var email = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "asm/suppressions/global/" + email); + Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestAsmSuppressionsEmailGet() + { + var sg = GetClient("200"); + var email = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "asm/suppressions/" + email); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestBrowsersStatsGet() + { + var sg = GetClient("200"); + var queryParams = @"{ + 'aggregated_by': 'day', + 'browsers': 'test_string', + 'end_date': '2016-04-01', + 'limit': 'test_string', + 'offset': 'test_string', + 'start_date': '2016-01-01' +}"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "browsers/stats", queryParams: queryParams); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestCampaignsPost() + { + var sg = GetClient("201"); + var data = @"{ + 'categories': [ + 'spring line' + ], + 'custom_unsubscribe_url': '', + 'html_content': '

Check out our spring line!

', + 'ip_pool': 'marketing', + 'list_ids': [ + 110, + 124 + ], + 'plain_content': 'Check out our spring line!', + 'segment_ids': [ + 110 + ], + 'sender_id': 124451, + 'subject': 'New Products for Spring!', + 'suppression_group_id': 42, + 'title': 'March Newsletter' +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var response = await sg.RequestAsync(method: SendGridClient.Method.POST, urlPath: "campaigns", requestBody: data); + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestCampaignsGet() + { + var sg = GetClient("200"); + var queryParams = @"{ + 'limit': 1, + 'offset': 1 +}"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "campaigns", queryParams: queryParams); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestCampaignsCampaignIdPatch() + { + var sg = GetClient("200"); + var data = @"{ + 'categories': [ + 'summer line' + ], + 'html_content': '

Check out our summer line!

', + 'plain_content': 'Check out our summer line!', + 'subject': 'New Products for Summer!', + 'title': 'May Newsletter' +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var campaign_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.PATCH, urlPath: "campaigns/" + campaign_id, requestBody: data); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestCampaignsCampaignIdGet() + { + var sg = GetClient("200"); + var campaign_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "campaigns/" + campaign_id); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestCampaignsCampaignIdDelete() + { + var sg = GetClient("204"); + var campaign_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "campaigns/" + campaign_id); + Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestCampaignsCampaignIdSchedulesPatch() + { + var sg = GetClient("200"); + var data = @"{ + 'send_at': 1489451436 +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var campaign_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.PATCH, urlPath: "campaigns/" + campaign_id + "/schedules", requestBody: data); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestCampaignsCampaignIdSchedulesPost() + { + var sg = GetClient("201"); + var data = @"{ + 'send_at': 1489771528 +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var campaign_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.POST, urlPath: "campaigns/" + campaign_id + "/schedules", requestBody: data); + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestCampaignsCampaignIdSchedulesGet() + { + var sg = GetClient("200"); + var campaign_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "campaigns/" + campaign_id + "/schedules"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestCampaignsCampaignIdSchedulesDelete() + { + var sg = GetClient("204"); + var campaign_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "campaigns/" + campaign_id + "/schedules"); + Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestCampaignsCampaignIdSchedulesNowPost() + { + var sg = GetClient("201"); + var campaign_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.POST, urlPath: "campaigns/" + campaign_id + "/schedules/now"); + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestCampaignsCampaignIdSchedulesTestPost() + { + var sg = GetClient("204"); + var data = @"{ + 'to': 'your.email@example.com' +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var campaign_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.POST, urlPath: "campaigns/" + campaign_id + "/schedules/test", requestBody: data); + Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestCategoriesGet() + { + var sg = GetClient("200"); + var queryParams = @"{ + 'category': 'test_string', + 'limit': 1, + 'offset': 1 +}"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "categories", queryParams: queryParams); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestCategoriesStatsGet() + { + var sg = GetClient("200"); + var queryParams = @"{ + 'aggregated_by': 'day', + 'categories': 'test_string', + 'end_date': '2016-04-01', + 'limit': 1, + 'offset': 1, + 'start_date': '2016-01-01' +}"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "categories/stats", queryParams: queryParams); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestCategoriesStatsSumsGet() + { + var sg = GetClient("200"); + var queryParams = @"{ + 'aggregated_by': 'day', + 'end_date': '2016-04-01', + 'limit': 1, + 'offset': 1, + 'sort_by_direction': 'asc', + 'sort_by_metric': 'test_string', + 'start_date': '2016-01-01' +}"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "categories/stats/sums", queryParams: queryParams); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestClientsStatsGet() + { + var sg = GetClient("200"); + var queryParams = @"{ + 'aggregated_by': 'day', + 'end_date': '2016-04-01', + 'start_date': '2016-01-01' +}"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "clients/stats", queryParams: queryParams); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestClientsClientTypeStatsGet() + { + var sg = GetClient("200"); + var queryParams = @"{ + 'aggregated_by': 'day', + 'end_date': '2016-04-01', + 'start_date': '2016-01-01' +}"; + var client_type = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "clients/" + client_type + "/stats", queryParams: queryParams); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestContactdbCustomFieldsPost() + { + var sg = GetClient("201"); + var data = @"{ + 'name': 'pet', + 'type': 'text' +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var response = await sg.RequestAsync(method: SendGridClient.Method.POST, urlPath: "contactdb/custom_fields", requestBody: data); + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestContactdbCustomFieldsGet() + { + var sg = GetClient("200"); + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "contactdb/custom_fields"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestContactdbCustomFieldsCustomFieldIdGet() + { + var sg = GetClient("200"); + var custom_field_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "contactdb/custom_fields/" + custom_field_id); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestContactdbCustomFieldsCustomFieldIdDelete() + { + var sg = GetClient("202"); + var custom_field_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "contactdb/custom_fields/" + custom_field_id); + Assert.Equal(HttpStatusCode.Accepted, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestContactdbListsPost() + { + + var sg = GetClient("201"); + var data = @"{ + 'name': 'your list name' +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var response = await sg.RequestAsync(method: SendGridClient.Method.POST, urlPath: "contactdb/lists", requestBody: data); + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestContactdbListsGet() + { + var sg = GetClient("200"); + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "contactdb/lists"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestContactdbListsDelete() + { + var sg = GetClient("204"); + var data = @"[ + 1, + 2, + 3, + 4 +]"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var response = await sg.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "contactdb/lists", requestBody: data); + Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestContactdbListsListIdPatch() + { + var sg = GetClient("200"); + var data = @"{ + 'name': 'newlistname' +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var queryParams = @"{ + 'list_id': 1 +}"; + var list_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.PATCH, urlPath: "contactdb/lists/" + list_id, requestBody: data, queryParams: queryParams); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestContactdbListsListIdGet() + { + var sg = GetClient("200"); + var queryParams = @"{ + 'list_id': 1 +}"; + var list_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "contactdb/lists/" + list_id, queryParams: queryParams); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestContactdbListsListIdDelete() + { + var sg = GetClient("202"); + var queryParams = @"{ + 'delete_contacts': 'true' +}"; + var list_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "contactdb/lists/" + list_id, queryParams: queryParams); + Assert.Equal(HttpStatusCode.Accepted, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestContactdbListsListIdRecipientsPost() + { + var sg = GetClient("201"); + var data = @"[ + 'recipient_id1', + 'recipient_id2' +]"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var list_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.POST, urlPath: "contactdb/lists/" + list_id + "/recipients", requestBody: data); + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestContactdbListsListIdRecipientsGet() + { + var sg = GetClient("200"); + var queryParams = @"{ + 'list_id': 1, + 'page': 1, + 'page_size': 1 +}"; + var list_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "contactdb/lists/" + list_id + "/recipients", queryParams: queryParams); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestContactdbListsListIdRecipientsRecipientIdPost() + { + var sg = GetClient("201"); + var list_id = "test_url_param"; + var recipient_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.POST, urlPath: "contactdb/lists/" + list_id + "/recipients/" + recipient_id); + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestContactdbListsListIdRecipientsRecipientIdDelete() + { + var sg = GetClient("204"); + var queryParams = @"{ + 'list_id': 1, + 'recipient_id': 1 +}"; + var list_id = "test_url_param"; + var recipient_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "contactdb/lists/" + list_id + "/recipients/" + recipient_id, queryParams: queryParams); + Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestContactdbRecipientsPatch() + { + var sg = GetClient("201"); + var data = @"[ + { + 'email': 'jones@example.com', + 'first_name': 'Guy', + 'last_name': 'Jones' + } +]"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var response = await sg.RequestAsync(method: SendGridClient.Method.PATCH, urlPath: "contactdb/recipients", requestBody: data); + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestContactdbRecipientsPost() + { + var sg = GetClient("201"); + var data = @"[ + { + 'age': 25, + 'email': 'example@example.com', + 'first_name': '', + 'last_name': 'User' + }, + { + 'age': 25, + 'email': 'example2@example.com', + 'first_name': 'Example', + 'last_name': 'User' + } +]"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var response = await sg.RequestAsync(method: SendGridClient.Method.POST, urlPath: "contactdb/recipients", requestBody: data); + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestContactdbRecipientsGet() + { + var sg = GetClient("200"); + var queryParams = @"{ + 'page': 1, + 'page_size': 1 +}"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "contactdb/recipients", queryParams: queryParams); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestContactdbRecipientsDelete() + { + var sg = GetClient("200"); + var data = @"[ + 'recipient_id1', + 'recipient_id2' +]"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var response = await sg.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "contactdb/recipients", requestBody: data); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestContactdbRecipientsBillableCountGet() + { + var sg = GetClient("200"); + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "contactdb/recipients/billable_count"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestContactdbRecipientsCountGet() + { + var sg = GetClient("200"); + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "contactdb/recipients/count"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestContactdbRecipientsSearchGet() + { + var sg = GetClient("200"); + var queryParams = @"{ + '{field_name}': 'test_string' +}"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "contactdb/recipients/search", queryParams: queryParams); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestContactdbRecipientsRecipientIdGet() + { + var sg = GetClient("200"); + var recipient_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "contactdb/recipients/" + recipient_id); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestContactdbRecipientsRecipientIdDelete() + { + var sg = GetClient("204"); + var recipient_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "contactdb/recipients/" + recipient_id); + Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestContactdbRecipientsRecipientIdListsGet() + { + var sg = GetClient("200"); + var recipient_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "contactdb/recipients/" + recipient_id + "/lists"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestContactdbReservedFieldsGet() + { + var sg = GetClient("200"); + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "contactdb/reserved_fields"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestContactdbSegmentsPost() + { + var sg = GetClient("200"); + var data = @"{ + 'conditions': [ + { + 'and_or': '', + 'field': 'last_name', + 'operator': 'eq', + 'value': 'Miller' + }, + { + 'and_or': 'and', + 'field': 'last_clicked', + 'operator': 'gt', + 'value': '01/02/2015' + }, + { + 'and_or': 'or', + 'field': 'clicks.campaign_identifier', + 'operator': 'eq', + 'value': '513' + } + ], + 'list_id': 4, + 'name': 'Last Name Miller' +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var response = await sg.RequestAsync(method: SendGridClient.Method.POST, urlPath: "contactdb/segments", requestBody: data); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestContactdbSegmentsGet() + { + var sg = GetClient("200"); + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "contactdb/segments"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestContactdbSegmentsSegmentIdPatch() + { + var sg = GetClient("200"); + var data = @"{ + 'conditions': [ + { + 'and_or': '', + 'field': 'last_name', + 'operator': 'eq', + 'value': 'Miller' + } + ], + 'list_id': 5, + 'name': 'The Millers' +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var queryParams = @"{ + 'segment_id': 'test_string' +}"; + var segment_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.PATCH, urlPath: "contactdb/segments/" + segment_id, requestBody: data, queryParams: queryParams); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestContactdbSegmentsSegmentIdGet() + { + var sg = GetClient("200"); + var queryParams = @"{ + 'segment_id': 1 +}"; + var segment_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "contactdb/segments/" + segment_id, queryParams: queryParams); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestContactdbSegmentsSegmentIdDelete() + { + var sg = GetClient("204"); + var queryParams = @"{ + 'delete_contacts': 'true' +}"; + var segment_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "contactdb/segments/" + segment_id, queryParams: queryParams); + Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestContactdbSegmentsSegmentIdRecipientsGet() + { + var sg = GetClient("200"); + var queryParams = @"{ + 'page': 1, + 'page_size': 1 +}"; + var segment_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "contactdb/segments/" + segment_id + "/recipients", queryParams: queryParams); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestDevicesStatsGet() + { + var sg = GetClient("200"); + var queryParams = @"{ + 'aggregated_by': 'day', + 'end_date': '2016-04-01', + 'limit': 1, + 'offset': 1, + 'start_date': '2016-01-01' +}"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "devices/stats", queryParams: queryParams); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestGeoStatsGet() + { + var sg = GetClient("200"); + var queryParams = @"{ + 'aggregated_by': 'day', + 'country': 'US', + 'end_date': '2016-04-01', + 'limit': 1, + 'offset': 1, + 'start_date': '2016-01-01' +}"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "geo/stats", queryParams: queryParams); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestIpsGet() + { + var sg = GetClient("200"); + var queryParams = @"{ + 'exclude_whitelabels': 'true', + 'ip': 'test_string', + 'limit': 1, + 'offset': 1, + 'subuser': 'test_string' +}"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "ips", queryParams: queryParams); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestIpsAssignedGet() + { + var sg = GetClient("200"); + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "ips/assigned"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestIpsPoolsPost() + { + var sg = GetClient("200"); + var data = @"{ + 'name': 'marketing' +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var response = await sg.RequestAsync(method: SendGridClient.Method.POST, urlPath: "ips/pools", requestBody: data); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestIpsPoolsGet() + { + var sg = GetClient("200"); + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "ips/pools"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestIpsPoolsPoolNamePut() + { + var sg = GetClient("200"); + var data = @"{ + 'name': 'new_pool_name' +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var pool_name = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.PUT, urlPath: "ips/pools/" + pool_name, requestBody: data); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestIpsPoolsPoolNameGet() + { + var sg = GetClient("200"); + var pool_name = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "ips/pools/" + pool_name); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestIpsPoolsPoolNameDelete() + { + var sg = GetClient("204"); + var pool_name = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "ips/pools/" + pool_name); + Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestIpsPoolsPoolNameIpsPost() + { + var sg = GetClient("201"); + var data = @"{ + 'ip': '0.0.0.0' +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var pool_name = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.POST, urlPath: "ips/pools/" + pool_name + "/ips", requestBody: data); + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestIpsPoolsPoolNameIpsIpDelete() + { + var sg = GetClient("204"); + var pool_name = "test_url_param"; + var ip = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "ips/pools/" + pool_name + "/ips/" + ip); + Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestIpsWarmupPost() + { + var sg = GetClient("200"); + var data = @"{ + 'ip': '0.0.0.0' +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var response = await sg.RequestAsync(method: SendGridClient.Method.POST, urlPath: "ips/warmup", requestBody: data); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestIpsWarmupGet() + { + var sg = GetClient("200"); + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "ips/warmup"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestIpsWarmupIpAddressGet() + { + var sg = GetClient("200"); + var ip_address = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "ips/warmup/" + ip_address); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestIpsWarmupIpAddressDelete() + { + var sg = GetClient("204"); + var ip_address = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "ips/warmup/" + ip_address); + Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestIpsIpAddressGet() + { + var sg = GetClient("200"); + var ip_address = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "ips/" + ip_address); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestMailBatchPost() + { + var sg = GetClient("201"); + var response = await sg.RequestAsync(method: SendGridClient.Method.POST, urlPath: "mail/batch"); + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestMailBatchBatchIdGet() + { + var sg = GetClient("200"); + var batch_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "mail/batch/" + batch_id); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestMailSendPost() + { + var sg = GetClient("202"); + var data = @"{ + 'asm': { + 'group_id': 1, + 'groups_to_display': [ + 1, + 2, + 3 + ] + }, + 'attachments': [ + { + 'content': '[BASE64 encoded content block here]', + 'content_id': 'ii_139db99fdb5c3704', + 'disposition': 'inline', + 'filename': 'file1.jpg', + 'name': 'file1', + 'type': 'jpg' + } + ], + 'batch_id': '[YOUR BATCH ID GOES HERE]', + 'categories': [ + 'category1', + 'category2' + ], + 'content': [ + { + 'type': 'text/html', + 'value': '

Hello, world!

' + } + ], + 'custom_args': { + 'New Argument 1': 'New Value 1', + 'activationAttempt': '1', + 'customerAccountNumber': '[CUSTOMER ACCOUNT NUMBER GOES HERE]' + }, + 'from': { + 'email': 'sam.smith@example.com', + 'name': 'Sam Smith' + }, + 'headers': {}, + 'ip_pool_name': '[YOUR POOL NAME GOES HERE]', + 'mail_settings': { + 'bcc': { + 'email': 'ben.doe@example.com', + 'enable': true + }, + 'bypass_list_management': { + 'enable': true + }, + 'footer': { + 'enable': true, + 'html': '

Thanks
The Twilio SendGrid Team

', + 'text': 'Thanks,/n The Twilio SendGrid Team' + }, + 'sandbox_mode': { + 'enable': false + }, + 'spam_check': { + 'enable': true, + 'post_to_url': 'http://example.com/compliance', + 'threshold': 3 + } + }, + 'personalizations': [ + { + 'bcc': [ + { + 'email': 'sam.doe@example.com', + 'name': 'Sam Doe' + } + ], + 'cc': [ + { + 'email': 'jane.doe@example.com', + 'name': 'Jane Doe' + } + ], + 'custom_args': { + 'New Argument 1': 'New Value 1', + 'activationAttempt': '1', + 'customerAccountNumber': '[CUSTOMER ACCOUNT NUMBER GOES HERE]' + }, + 'headers': { + 'X-Accept-Language': 'en', + 'X-Mailer': 'MyApp' + }, + 'send_at': 1409348513, + 'subject': 'Hello, World!', + 'substitutions': { + 'id': 'substitutions', + 'type': 'object' + }, + 'to': [ + { + 'email': 'john.doe@example.com', + 'name': 'John Doe' + } + ] + } + ], + 'reply_to': { + 'email': 'sam.smith@example.com', + 'name': 'Sam Smith' + }, + 'sections': { + 'section': { + ':sectionName1': 'section 1 text', + ':sectionName2': 'section 2 text' + } + }, + 'send_at': 1409348513, + 'subject': 'Hello, World!', + 'template_id': '[YOUR TEMPLATE ID GOES HERE]', + 'tracking_settings': { + 'click_tracking': { + 'enable': true, + 'enable_text': true + }, + 'ganalytics': { + 'enable': true, + 'utm_campaign': '[NAME OF YOUR REFERRER SOURCE]', + 'utm_content': '[USE THIS SPACE TO DIFFERENTIATE YOUR EMAIL FROM ADS]', + 'utm_medium': '[NAME OF YOUR MARKETING MEDIUM e.g. email]', + 'utm_name': '[NAME OF YOUR CAMPAIGN]', + 'utm_term': '[IDENTIFY PAID KEYWORDS HERE]' + }, + 'open_tracking': { + 'enable': true, + 'substitution_tag': '%opentrack' + }, + 'subscription_tracking': { + 'enable': true, + 'html': 'If you would like to unsubscribe and stop receiving these emails <% clickhere %>.', + 'substitution_tag': '<%click here%>', + 'text': 'If you would like to unsubscribe and stop receiveing these emails <% click here %>.' + } + } +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var response = await sg.RequestAsync(method: SendGridClient.Method.POST, urlPath: "mail/send", requestBody: data); + Assert.Equal(HttpStatusCode.Accepted, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestMailSettingsGet() + { + var sg = GetClient("200"); + var queryParams = @"{ + 'limit': 1, + 'offset': 1 +}"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "mail_settings", queryParams: queryParams); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestMailSettingsAddressWhitelistPatch() + { + var sg = GetClient("200"); + var data = @"{ + 'enabled': true, + 'list': [ + 'email1@example.com', + 'example.com' + ] +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var response = await sg.RequestAsync(method: SendGridClient.Method.PATCH, urlPath: "mail_settings/address_whitelist", requestBody: data); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestMailSettingsAddressWhitelistGet() + { + var sg = GetClient("200"); + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "mail_settings/address_whitelist"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestMailSettingsBccPatch() + { + var sg = GetClient("200"); + var data = @"{ + 'email': 'email@example.com', + 'enabled': false +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var response = await sg.RequestAsync(method: SendGridClient.Method.PATCH, urlPath: "mail_settings/bcc", requestBody: data); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestMailSettingsBccGet() + { + var sg = GetClient("200"); + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "mail_settings/bcc"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestMailSettingsBouncePurgePatch() + { + var sg = GetClient("200"); + var data = @"{ + 'enabled': true, + 'hard_bounces': 5, + 'soft_bounces': 5 +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var response = await sg.RequestAsync(method: SendGridClient.Method.PATCH, urlPath: "mail_settings/bounce_purge", requestBody: data); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestMailSettingsBouncePurgeGet() + { + var sg = GetClient("200"); + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "mail_settings/bounce_purge"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestMailSettingsFooterPatch() + { + var sg = GetClient("200"); + var data = @"{ + 'enabled': true, + 'html_content': '...', + 'plain_content': '...' +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var response = await sg.RequestAsync(method: SendGridClient.Method.PATCH, urlPath: "mail_settings/footer", requestBody: data); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestMailSettingsFooterGet() + { + var sg = GetClient("200"); + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "mail_settings/footer"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestMailSettingsForwardBouncePatch() + { + var sg = GetClient("200"); + var data = @"{ + 'email': 'example@example.com', + 'enabled': true +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var response = await sg.RequestAsync(method: SendGridClient.Method.PATCH, urlPath: "mail_settings/forward_bounce", requestBody: data); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestMailSettingsForwardBounceGet() + { + var sg = GetClient("200"); + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "mail_settings/forward_bounce"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestMailSettingsForwardSpamPatch() + { + var sg = GetClient("200"); + var data = @"{ + 'email': '', + 'enabled': false +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var response = await sg.RequestAsync(method: SendGridClient.Method.PATCH, urlPath: "mail_settings/forward_spam", requestBody: data); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestMailSettingsForwardSpamGet() + { + var sg = GetClient("200"); + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "mail_settings/forward_spam"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestMailSettingsPlainContentPatch() + { + var sg = GetClient("200"); + var data = @"{ + 'enabled': false +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var response = await sg.RequestAsync(method: SendGridClient.Method.PATCH, urlPath: "mail_settings/plain_content", requestBody: data); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestMailSettingsPlainContentGet() + { + var sg = GetClient("200"); + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "mail_settings/plain_content"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestMailSettingsSpamCheckPatch() + { + var sg = GetClient("200"); + var data = @"{ + 'enabled': true, + 'max_score': 5, + 'url': 'url' +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var response = await sg.RequestAsync(method: SendGridClient.Method.PATCH, urlPath: "mail_settings/spam_check", requestBody: data); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestMailSettingsSpamCheckGet() + { + var sg = GetClient("200"); + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "mail_settings/spam_check"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestMailSettingsTemplatePatch() + { + var sg = GetClient("200"); + var data = @"{ + 'enabled': true, + 'html_content': '<% body %>' +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var response = await sg.RequestAsync(method: SendGridClient.Method.PATCH, urlPath: "mail_settings/template", requestBody: data); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestMailSettingsTemplateGet() + { + var sg = GetClient("200"); + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "mail_settings/template"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestMailboxProvidersStatsGet() + { + var sg = GetClient("200"); + var queryParams = @"{ + 'aggregated_by': 'day', + 'end_date': '2016-04-01', + 'limit': 1, + 'mailbox_providers': 'test_string', + 'offset': 1, + 'start_date': '2016-01-01' +}"; + + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "mailbox_providers/stats", queryParams: queryParams); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestPartnerSettingsGet() + { + var sg = GetClient("200"); + var queryParams = @"{ + 'limit': 1, + 'offset': 1 +}"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "partner_settings", queryParams: queryParams); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestPartnerSettingsNewRelicPatch() + { + var sg = GetClient("200"); + var data = @"{ + 'enable_subuser_statistics': true, + 'enabled': true, + 'license_key': '' +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var response = await sg.RequestAsync(method: SendGridClient.Method.PATCH, urlPath: "partner_settings/new_relic", requestBody: data); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestPartnerSettingsNewRelicGet() + { + var sg = GetClient("200"); + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "partner_settings/new_relic"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestScopesGet() + { + var sg = GetClient("200"); + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "scopes"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestInvalidUtf8Charset() + { + var httpResponse = @"{ + 'scopes': [ + 'user.profile.read', + 'user.profile.update' + ] +}"; + var httpMessageHandler = new InvalidUtf8CharsetMessageHandler(httpResponse); + HttpClient clientToInject = new HttpClient(httpMessageHandler); + + var sg = new SendGridClient(clientToInject, fixture.apiKey); + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "scopes"); + var responseBody = response.Body.ReadAsStringAsync().Result; + Assert.Equal(httpResponse, responseBody); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestSendersPost() + { + var sg = GetClient("201"); + var data = @"{ + 'address': '123 Elm St.', + 'address_2': 'Apt. 456', + 'city': 'Denver', + 'country': 'United States', + 'from': { + 'email': 'from@example.com', + 'name': 'Example INC' + }, + 'nickname': 'My Sender ID', + 'reply_to': { + 'email': 'replyto@example.com', + 'name': 'Example INC' + }, + 'state': 'Colorado', + 'zip': '80202' +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var response = await sg.RequestAsync(method: SendGridClient.Method.POST, urlPath: "senders", requestBody: data); + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestSendersGet() + { + var sg = GetClient("200"); + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "senders"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestSendersSenderIdPatch() + { + var sg = GetClient("200"); + var data = @"{ + 'address': '123 Elm St.', + 'address_2': 'Apt. 456', + 'city': 'Denver', + 'country': 'United States', + 'from': { + 'email': 'from@example.com', + 'name': 'Example INC' + }, + 'nickname': 'My Sender ID', + 'reply_to': { + 'email': 'replyto@example.com', + 'name': 'Example INC' + }, + 'state': 'Colorado', + 'zip': '80202' +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var sender_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.PATCH, urlPath: "senders/" + sender_id, requestBody: data); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestSendersSenderIdGet() + { + var sg = GetClient("200"); + var sender_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "senders/" + sender_id); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestSendersSenderIdDelete() + { + var sg = GetClient("204"); + var sender_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "senders/" + sender_id); + Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestSendersSenderIdResendVerificationPost() + { + var sg = GetClient("204"); + var sender_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.POST, urlPath: "senders/" + sender_id + "/resend_verification"); + Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestStatsGet() + { + var sg = GetClient("200"); + var queryParams = @"{ + 'aggregated_by': 'day', + 'end_date': '2016-04-01', + 'limit': 1, + 'offset': 1, + 'start_date': '2016-01-01' +}"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "stats", queryParams: queryParams); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestSubusersPost() + { + var sg = GetClient("200"); + var data = @"{ + 'email': 'John@example.com', + 'ips': [ + '1.1.1.1', + '2.2.2.2' + ], + 'password': 'johns_password', + 'username': 'John@example.com' +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var response = await sg.RequestAsync(method: SendGridClient.Method.POST, urlPath: "subusers", requestBody: data); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestSubusersGet() + { + var sg = GetClient("200"); + var queryParams = @"{ + 'limit': 1, + 'offset': 1, + 'username': 'test_string' +}"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "subusers", queryParams: queryParams); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestSubusersReputationsGet() + { + var sg = GetClient("200"); + var queryParams = @"{ + 'usernames': 'test_string' +}"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "subusers/reputations", queryParams: queryParams); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestSubusersStatsGet() + { + var sg = GetClient("200"); + var queryParams = @"{ + 'aggregated_by': 'day', + 'end_date': '2016-04-01', + 'limit': 1, + 'offset': 1, + 'start_date': '2016-01-01', + 'subusers': 'test_string' +}"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "subusers/stats", queryParams: queryParams); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestSubusersStatsMonthlyGet() + { + var sg = GetClient("200"); + var queryParams = @"{ + 'date': 'test_string', + 'limit': 1, + 'offset': 1, + 'sort_by_direction': 'asc', + 'sort_by_metric': 'test_string', + 'subuser': 'test_string' +}"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "subusers/stats/monthly", queryParams: queryParams); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestSubusersStatsSumsGet() + { + var sg = GetClient("200"); + var queryParams = @"{ + 'aggregated_by': 'day', + 'end_date': '2016-04-01', + 'limit': 1, + 'offset': 1, + 'sort_by_direction': 'asc', + 'sort_by_metric': 'test_string', + 'start_date': '2016-01-01' +}"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "subusers/stats/sums", queryParams: queryParams); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestSubusersSubuserNamePatch() + { + var sg = GetClient("204"); + var data = @"{ + 'disabled': false +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var subuser_name = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.PATCH, urlPath: "subusers/" + subuser_name, requestBody: data); + Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestSubusersSubuserNameDelete() + { + + var sg = GetClient("204"); + var subuser_name = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "subusers/" + subuser_name); + Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestSubusersSubuserNameIpsPut() + { + var sg = GetClient("200"); + var data = @"[ + '127.0.0.1' +]"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var subuser_name = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.PUT, urlPath: "subusers/" + subuser_name + "/ips", requestBody: data); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestSubusersSubuserNameMonitorPut() + { + var sg = GetClient("200"); + var data = @"{ + 'email': 'example@example.com', + 'frequency': 500 +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var subuser_name = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.PUT, urlPath: "subusers/" + subuser_name + "/monitor", requestBody: data); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestSubusersSubuserNameMonitorPost() + { + var sg = GetClient("200"); + var data = @"{ + 'email': 'example@example.com', + 'frequency': 50000 +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var subuser_name = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.POST, urlPath: "subusers/" + subuser_name + "/monitor", requestBody: data); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestSubusersSubuserNameMonitorGet() + { + var sg = GetClient("200"); + var subuser_name = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "subusers/" + subuser_name + "/monitor"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestSubusersSubuserNameMonitorDelete() + { + var sg = GetClient("204"); + var subuser_name = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "subusers/" + subuser_name + "/monitor"); + Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestSubusersSubuserNameStatsMonthlyGet() + { + var sg = GetClient("200"); + var queryParams = @"{ + 'date': 'test_string', + 'limit': 1, + 'offset': 1, + 'sort_by_direction': 'asc', + 'sort_by_metric': 'test_string' +}"; + var subuser_name = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "subusers/" + subuser_name + "/stats/monthly", queryParams: queryParams); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestSuppressionBlocksGet() + { + var sg = GetClient("200"); + var queryParams = @"{ + 'end_time': 1, + 'limit': 1, + 'offset': 1, + 'start_time': 1 +}"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "suppression/blocks", queryParams: queryParams); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestSuppressionBlocksDelete() + { + var sg = GetClient("204"); + var data = @"{ + 'delete_all': false, + 'emails': [ + 'example1@example.com', + 'example2@example.com' + ] +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var response = await sg.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "suppression/blocks", requestBody: data); + Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestSuppressionBlocksEmailGet() + { + var sg = GetClient("200"); + var email = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "suppression/blocks/" + email); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestSuppressionBlocksEmailDelete() + { + var sg = GetClient("204"); + var email = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "suppression/blocks/" + email); + Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestSuppressionBouncesGet() + { + var sg = GetClient("200"); + var queryParams = @"{ + 'end_time': 1, + 'start_time': 1 +}"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "suppression/bounces", queryParams: queryParams); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestSuppressionBouncesDelete() + { + var sg = GetClient("204"); + var data = @"{ + 'delete_all': true, + 'emails': [ + 'example@example.com', + 'example2@example.com' + ] +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var response = await sg.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "suppression/bounces", requestBody: data); + Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestSuppressionBouncesEmailGet() + { + + var sg = GetClient("200"); + var email = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "suppression/bounces/" + email); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestSuppressionBouncesEmailDelete() + { + var sg = GetClient("204"); + var queryParams = @"{ + 'email_address': 'example@example.com' +}"; + var email = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "suppression/bounces/" + email, queryParams: queryParams); + Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestSuppressionInvalidEmailsGet() + { + var sg = GetClient("200"); + var queryParams = @"{ + 'end_time': 1, + 'limit': 1, + 'offset': 1, + 'start_time': 1 +}"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "suppression/invalid_emails", queryParams: queryParams); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestSuppressionInvalidEmailsDelete() + { + var sg = GetClient("204"); + var data = @"{ + 'delete_all': false, + 'emails': [ + 'example1@example.com', + 'example2@example.com' + ] +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var response = await sg.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "suppression/invalid_emails", requestBody: data); + Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestSuppressionInvalidEmailsEmailGet() + { + var sg = GetClient("200"); + var email = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "suppression/invalid_emails/" + email); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestSuppressionInvalidEmailsEmailDelete() + { + var sg = GetClient("204"); + var email = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "suppression/invalid_emails/" + email); + Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestSuppressionSpamReportEmailGet() + { + var sg = GetClient("200"); + var email = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "suppression/spam_reports/" + email); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestSuppressionSpamReportEmailDelete() + { + var sg = GetClient("204"); + var email = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "suppression/spam_reports/" + email); + Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestSuppressionSpamReportsGet() + { + var sg = GetClient("200"); + var queryParams = @"{ + 'end_time': 1, + 'limit': 1, + 'offset': 1, + 'start_time': 1 +}"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "suppression/spam_reports", queryParams: queryParams); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestSuppressionSpamReportsDelete() + { + var sg = GetClient("204"); + var data = @"{ + 'delete_all': false, + 'emails': [ + 'example1@example.com', + 'example2@example.com' + ] +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var response = await sg.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "suppression/spam_reports", requestBody: data); + Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestSuppressionUnsubscribesGet() + { + var sg = GetClient("200"); + var queryParams = @"{ + 'end_time': 1, + 'limit': 1, + 'offset': 1, + 'start_time': 1 +}"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "suppression/unsubscribes", queryParams: queryParams); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestTemplatesPost() + { + var sg = GetClient("201"); + var data = @"{ + 'name': 'example_name' +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var response = await sg.RequestAsync(method: SendGridClient.Method.POST, urlPath: "templates", requestBody: data); + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestTemplatesGet() + { + var sg = GetClient("200"); + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "templates"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestTemplatesTemplateIdPatch() + { + var sg = GetClient("200"); + var data = @"{ + 'name': 'new_example_name' +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var template_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.PATCH, urlPath: "templates/" + template_id, requestBody: data); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestTemplatesTemplateIdGet() + { + var sg = GetClient("200"); + var template_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "templates/" + template_id); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestTemplatesTemplateIdDelete() + { + var sg = GetClient("204"); + var template_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "templates/" + template_id); + Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestTemplatesTemplateIdVersionsPost() + { + var sg = GetClient("201"); + var data = @"{ + 'active': 1, + 'html_content': '<%body%>', + 'name': 'example_version_name', + 'plain_content': '<%body%>', + 'subject': '<%subject%>', + 'template_id': 'ddb96bbc-9b92-425e-8979-99464621b543' +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var template_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.POST, urlPath: "templates/" + template_id + "/versions", requestBody: data); + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestTemplatesTemplateIdVersionsVersionIdPatch() + { + var sg = GetClient("200"); + var data = @"{ + 'active': 1, + 'html_content': '<%body%>', + 'name': 'updated_example_name', + 'plain_content': '<%body%>', + 'subject': '<%subject%>' +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var template_id = "test_url_param"; + var version_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.PATCH, urlPath: "templates/" + template_id + "/versions/" + version_id, requestBody: data); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestTemplatesTemplateIdVersionsVersionIdGet() + { + var sg = GetClient("200"); + var template_id = "test_url_param"; + var version_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "templates/" + template_id + "/versions/" + version_id); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestTemplatesTemplateIdVersionsVersionIdDelete() + { + var sg = GetClient("204"); + var template_id = "test_url_param"; + var version_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "templates/" + template_id + "/versions/" + version_id); + Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestTemplatesTemplateIdVersionsVersionIdActivatePost() + { + var sg = GetClient("200"); + var template_id = "test_url_param"; + var version_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.POST, urlPath: "templates/" + template_id + "/versions/" + version_id + "/activate"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestTrackingSettingsGet() + { + var sg = GetClient("200"); + var queryParams = @"{ + 'limit': 1, + 'offset': 1 +}"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "tracking_settings", queryParams: queryParams); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestTrackingSettingsClickPatch() + { + var sg = GetClient("200"); + var data = @"{ + 'enabled': true +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var response = await sg.RequestAsync(method: SendGridClient.Method.PATCH, urlPath: "tracking_settings/click", requestBody: data); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestTrackingSettingsClickGet() + { + var sg = GetClient("200"); + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "tracking_settings/click"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestTrackingSettingsGoogleAnalyticsPatch() + { + var sg = GetClient("200"); + var data = @"{ + 'enabled': true, + 'utm_campaign': 'website', + 'utm_content': '', + 'utm_medium': 'email', + 'utm_source': 'sendgrid.com', + 'utm_term': '' +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var response = await sg.RequestAsync(method: SendGridClient.Method.PATCH, urlPath: "tracking_settings/google_analytics", requestBody: data); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestTrackingSettingsGoogleAnalyticsGet() + { + var sg = GetClient("200"); + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "tracking_settings/google_analytics"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestTrackingSettingsOpenPatch() + { + var sg = GetClient("200"); + var data = @"{ + 'enabled': true +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var response = await sg.RequestAsync(method: SendGridClient.Method.PATCH, urlPath: "tracking_settings/open", requestBody: data); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestTrackingSettingsOpenGet() + { + var sg = GetClient("200"); + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "tracking_settings/open"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestTrackingSettingsSubscriptionPatch() + { + var sg = GetClient("200"); + var data = @"{ + 'enabled': true, + 'html_content': 'html content', + 'landing': 'landing page html', + 'plain_content': 'text content', + 'replace': 'replacement tag', + 'url': 'url' +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var response = await sg.RequestAsync(method: SendGridClient.Method.PATCH, urlPath: "tracking_settings/subscription", requestBody: data); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestTrackingSettingsSubscriptionGet() + { + var sg = GetClient("200"); + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "tracking_settings/subscription"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestUserAccountGet() + { + var sg = GetClient("200"); + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "user/account"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestUserCreditsGet() + { + var sg = GetClient("200"); + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "user/credits"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestUserEmailPut() + { + var sg = GetClient("200"); + var data = @"{ + 'email': 'example@example.com' +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var response = await sg.RequestAsync(method: SendGridClient.Method.PUT, urlPath: "user/email", requestBody: data); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestUserEmailGet() + { + var sg = GetClient("200"); + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "user/email"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestUserPasswordPut() + { + var sg = GetClient("200"); + var data = @"{ + 'new_password': 'new_password', + 'old_password': 'old_password' +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var response = await sg.RequestAsync(method: SendGridClient.Method.PUT, urlPath: "user/password", requestBody: data); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestUserProfilePatch() + { + var sg = GetClient("200"); + var data = @"{ + 'city': 'Orange', + 'first_name': 'Example', + 'last_name': 'User' +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var response = await sg.RequestAsync(method: SendGridClient.Method.PATCH, urlPath: "user/profile", requestBody: data); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestUserProfileGet() + { + var sg = GetClient("200"); + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "user/profile"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestUserScheduledSendsPost() + { + var sg = GetClient("201"); + var data = @"{ + 'batch_id': 'YOUR_BATCH_ID', + 'status': 'pause' +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var response = await sg.RequestAsync(method: SendGridClient.Method.POST, urlPath: "user/scheduled_sends", requestBody: data); + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestUserScheduledSendsGet() + { + + var sg = GetClient("200"); + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "user/scheduled_sends"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestUserScheduledSendsBatchIdPatch() + { + var sg = GetClient("204"); + var data = @"{ + 'status': 'pause' +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var batch_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.PATCH, urlPath: "user/scheduled_sends/" + batch_id, requestBody: data); + Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestUserScheduledSendsBatchIdGet() + { + var sg = GetClient("200"); + var batch_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "user/scheduled_sends/" + batch_id); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestUserScheduledSendsBatchIdDelete() + { + var sg = GetClient("204"); + var batch_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "user/scheduled_sends/" + batch_id); + Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestUserSettingsEnforcedTlsPatch() + { + var sg = GetClient("200"); + var data = @"{ + 'require_tls': true, + 'require_valid_cert': false +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var response = await sg.RequestAsync(method: SendGridClient.Method.PATCH, urlPath: "user/settings/enforced_tls", requestBody: data); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestUserSettingsEnforcedTlsGet() + { + var sg = GetClient("200"); + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "user/settings/enforced_tls"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestUserUsernamePut() + { + + var sg = GetClient("200"); + var data = @"{ + 'username': 'test_username' +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var response = await sg.RequestAsync(method: SendGridClient.Method.PUT, urlPath: "user/username", requestBody: data); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestUserUsernameGet() + { + var sg = GetClient("200"); + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "user/username"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestUserWebhooksEventSettingsPatch() + { + var sg = GetClient("200"); + var data = @"{ + 'bounce': true, + 'click': true, + 'deferred': true, + 'delivered': true, + 'dropped': true, + 'enabled': true, + 'group_resubscribe': true, + 'group_unsubscribe': true, + 'open': true, + 'processed': true, + 'spam_report': true, + 'unsubscribe': true, + 'url': 'url' +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var response = await sg.RequestAsync(method: SendGridClient.Method.PATCH, urlPath: "user/webhooks/event/settings", requestBody: data); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestUserWebhooksEventSettingsGet() + { + var sg = GetClient("200"); + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "user/webhooks/event/settings"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestUserWebhooksEventTestPost() + { + var sg = GetClient("204"); + var data = @"{ + 'url': 'url' +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var response = await sg.RequestAsync(method: SendGridClient.Method.POST, urlPath: "user/webhooks/event/test", requestBody: data); + Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestUserWebhooksParseSettingsPost() + { + var sg = GetClient("201"); + var data = @"{ + 'hostname': 'myhostname.com', + 'send_raw': false, + 'spam_check': true, + 'url': 'http://email.myhosthame.com' +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var response = await sg.RequestAsync(method: SendGridClient.Method.POST, urlPath: "user/webhooks/parse/settings", requestBody: data); + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestUserWebhooksParseSettingsGet() + { + var sg = GetClient("200"); + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "user/webhooks/parse/settings"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestUserWebhooksParseSettingsHostnamePatch() + { + var sg = GetClient("200"); + var data = @"{ + 'send_raw': true, + 'spam_check': false, + 'url': 'http://newdomain.com/parse' +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var hostname = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.PATCH, urlPath: "user/webhooks/parse/settings/" + hostname, requestBody: data); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestUserWebhooksParseSettingsHostnameGet() + { + var sg = GetClient("200"); + var hostname = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "user/webhooks/parse/settings/" + hostname); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestUserWebhooksParseSettingsHostnameDelete() + { + var sg = GetClient("204"); + var hostname = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "user/webhooks/parse/settings/" + hostname); + Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestUserWebhooksParseStatsGet() + { + var sg = GetClient("200"); + var queryParams = @"{ + 'aggregated_by': 'day', + 'end_date': '2016-04-01', + 'limit': 'test_string', + 'offset': 'test_string', + 'start_date': '2016-01-01' +}"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "user/webhooks/parse/stats", queryParams: queryParams); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestWhitelabelDomainsPost() + { + var sg = GetClient("201"); + var data = @"{ + 'automatic_security': false, + 'custom_spf': true, + 'default': true, + 'domain': 'example.com', + 'ips': [ + '192.168.1.1', + '192.168.1.2' + ], + 'subdomain': 'news', + 'username': 'john@example.com' +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var response = await sg.RequestAsync(method: SendGridClient.Method.POST, urlPath: "whitelabel/domains", requestBody: data); + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestWhitelabelDomainsGet() + { + var sg = GetClient("200"); + var queryParams = @"{ + 'domain': 'test_string', + 'exclude_subusers': 'true', + 'limit': 1, + 'offset': 1, + 'username': 'test_string' +}"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "whitelabel/domains", queryParams: queryParams); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestWhitelabelDomainsDefaultGet() + { + var sg = GetClient("200"); + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "whitelabel/domains/default"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestWhitelabelDomainsSubuserGet() + { + var sg = GetClient("200"); + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "whitelabel/domains/subuser"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestWhitelabelDomainsSubuserDelete() + { + var sg = GetClient("204"); + var response = await sg.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "whitelabel/domains/subuser"); + Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestWhitelabelDomainsDomainIdPatch() + { + var sg = GetClient("200"); + var data = @"{ + 'custom_spf': true, + 'default': false +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var domain_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.PATCH, urlPath: "whitelabel/domains/" + domain_id, requestBody: data); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestWhitelabelDomainsDomainIdGet() + { + var sg = GetClient("200"); + var domain_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "whitelabel/domains/" + domain_id); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestWhitelabelDomainsDomainIdDelete() + { + var sg = GetClient("204"); + var domain_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "whitelabel/domains/" + domain_id); + Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestWhitelabelDomainsDomainIdSubuserPost() + { + var sg = GetClient("201"); + var data = @"{ + 'username': 'jane@example.com' +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var domain_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.POST, urlPath: "whitelabel/domains/" + domain_id + "/subuser", requestBody: data); + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestWhitelabelDomainsIdIpsPost() + { + var sg = GetClient("200"); + var data = @"{ + 'ip': '192.168.0.1' +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.POST, urlPath: "whitelabel/domains/" + id + "/ips", requestBody: data); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestWhitelabelDomainsIdIpsIpDelete() + { + var sg = GetClient("200"); + var id = "test_url_param"; + var ip = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "whitelabel/domains/" + id + "/ips/" + ip); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestWhitelabelDomainsIdValidatePost() + { + var sg = GetClient("200"); + var id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.POST, urlPath: "whitelabel/domains/" + id + "/validate"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestWhitelabelIpsPost() + { + var sg = GetClient("201"); + var data = @"{ + 'domain': 'example.com', + 'ip': '192.168.1.1', + 'subdomain': 'email' +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var response = await sg.RequestAsync(method: SendGridClient.Method.POST, urlPath: "whitelabel/ips", requestBody: data); + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestWhitelabelIpsGet() + { + var sg = GetClient("200"); + var queryParams = @"{ + 'ip': 'test_string', + 'limit': 1, + 'offset': 1 +}"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "whitelabel/ips", queryParams: queryParams); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestWhitelabelIpsIdGet() + { + var sg = GetClient("200"); + var id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "whitelabel/ips/" + id); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestWhitelabelIpsIdDelete() + { + var sg = GetClient("204"); + var id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "whitelabel/ips/" + id); + Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestWhitelabelIpsIdValidatePost() + { + var sg = GetClient("200"); + var id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.POST, urlPath: "whitelabel/ips/" + id + "/validate"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestWhitelabelLinksPost() + { + var sg = GetClient("201"); + var data = @"{ + 'default': true, + 'domain': 'example.com', + 'subdomain': 'mail' +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var queryParams = @"{ + 'limit': 1, + 'offset': 1 +}"; + var response = await sg.RequestAsync(method: SendGridClient.Method.POST, urlPath: "whitelabel/links", requestBody: data, queryParams: queryParams); + Assert.Equal(HttpStatusCode.Created, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestWhitelabelLinksGet() + { + var sg = GetClient("200"); + var queryParams = @"{ + 'limit': 1 +}"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "whitelabel/links", queryParams: queryParams); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestWhitelabelLinksDefaultGet() + { + var sg = GetClient("200"); + var queryParams = @"{ + 'domain': 'test_string' +}"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "whitelabel/links/default", queryParams: queryParams); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestWhitelabelLinksSubuserGet() + { + var sg = GetClient("200"); + var queryParams = @"{ + 'username': 'test_string' +}"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "whitelabel/links/subuser", queryParams: queryParams); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestWhitelabelLinksSubuserDelete() + { + var sg = GetClient("204"); + var queryParams = @"{ + 'username': 'test_string' +}"; + var response = await sg.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "whitelabel/links/subuser", queryParams: queryParams); + Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestWhitelabelLinksIdPatch() + { + var sg = GetClient("200"); + var data = @"{ + 'default': true +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.PATCH, urlPath: "whitelabel/links/" + id, requestBody: data); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestWhitelabelLinksIdGet() + { + var sg = GetClient("200"); + var id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.GET, urlPath: "whitelabel/links/" + id); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestWhitelabelLinksIdDelete() + { + var sg = GetClient("204"); + var id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.DELETE, urlPath: "whitelabel/links/" + id); + Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestWhitelabelLinksIdValidatePost() + { + var sg = GetClient("200"); + var id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.POST, urlPath: "whitelabel/links/" + id + "/validate"); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestWhitelabelLinksLinkIdSubuserPost() + { + var sg = GetClient("200"); + var data = @"{ + 'username': 'jane@example.com' +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var link_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.POST, urlPath: "whitelabel/links/" + link_id + "/subuser", requestBody: data); + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + + [Theory] + [InlineData(HttpStatusCode.OK, "OK")] + [InlineData(HttpStatusCode.MovedPermanently, "Moved permanently")] + [InlineData(HttpStatusCode.Unauthorized, "Unauthorized")] + [InlineData(HttpStatusCode.ServiceUnavailable, "Service unavailable")] + public async Task TestTakesHttpClientFactoryAsConstructorArgumentAndUsesItInHttpCalls(HttpStatusCode httpStatusCode, string message) + { + var httpResponse = String.Format("{0}", message); + var httpMessageHandler = new FixedStatusAndMessageHttpMessageHandler(httpStatusCode, httpResponse); + HttpClient clientToInject = new HttpClient(httpMessageHandler); + + var sg = new SendGridClient(clientToInject, fixture.apiKey); + + var data = @"{ + 'username': 'jane@example.com' +}"; + var json = JsonConvert.DeserializeObject(data); + data = json.ToString(); + var link_id = "test_url_param"; + var response = await sg.RequestAsync(method: SendGridClient.Method.POST, urlPath: "whitelabel/links/" + link_id + "/subuser", requestBody: data); + Assert.Equal(httpStatusCode, response.StatusCode); + Assert.Equal(httpResponse, response.Body.ReadAsStringAsync().Result); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestTakesProxyAsConstructorArgumentAndInitiailsesHttpClient() + { + var urlPath = "urlPath"; + + var sg = new SendGridClient(new FakeWebProxy(), fixture.apiKey, urlPath: "urlPath"); + + Assert.Equal(sg.UrlPath, urlPath); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestTakesNullProxyAsConstructorArgumentAndInitiailsesHttpClient() + { + var urlPath = "urlPath"; + + var sg = new SendGridClient(null as IWebProxy, fixture.apiKey, urlPath: "urlPath"); + + Assert.Equal(sg.UrlPath, urlPath); + } + + /// + /// Tests the conditions in issue #358. + /// When an Http call times out while sending a message, + /// the client should NOT return a response code 200, but instead re-throw the exception. + /// + /// + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestWhenHttpCallTimesOutThenExceptionIsThrown() + { + /* **************************************************************************************** + * Create a simple message. + * **************************************************************************************** */ + var msg = new SendGridMessage(); + msg.SetFrom(new EmailAddress("test@example.com")); + msg.AddTo(new EmailAddress("test@example.com")); + msg.SetSubject("Hello World from the Twilio SendGrid CSharp Library"); + msg.AddContent(MimeType.Html, "HTML content"); + + /* **************************************************************************************** + * Here is where we ensure that the call to the SendEmailAsync() should lead to + * a TimeoutException being thrown by the HttpClient inside the SendGridClient object + * **************************************************************************************** */ + var httpMessageHandler = new TimeOutExceptionThrowingHttpMessageHandler(20, "The operation timed out"); + HttpClient clientToInject = new HttpClient(httpMessageHandler); + var sg = new SendGridClient(clientToInject, fixture.apiKey); + + /* **************************************************************************************** + * Make the method call, expecting a an exception to be thrown. + * I don't care if the component code simply passes on the original exception or if it catches + * the original exception and throws another, custom exception. So I'll only + * assert that ANY exception is thrown. + * **************************************************************************************** */ + var thrownException = await Record.ExceptionAsync(async () => + { + var response = await sg.SendEmailAsync(msg); + }); + + Assert.NotNull(thrownException); + + // If we are certain that we don't want custom exceptions to be thrown, + // we can also test that the original exception was thrown + Assert.IsType(thrownException); + } + + /// + /// Tests the conditions in issue #469. + /// JSON sent to SendGrid should never include reference handling ($id & $ref) + /// + /// + [Theory(Skip = SkipConfigureApiKey)] + [InlineData("$id")] + [InlineData("$ref")] + public void TestJsonNetReferenceHandling(string referenceHandlingProperty) + { + /* **************************************************************************************** + * Enable JSON.Net reference handling globally + * **************************************************************************************** */ + JsonConvert.DefaultSettings = () => new JsonSerializerSettings + { + PreserveReferencesHandling = PreserveReferencesHandling.All, + ReferenceLoopHandling = ReferenceLoopHandling.Serialize + }; + + /* **************************************************************************************** + * Create message with all possible properties + * **************************************************************************************** */ + var msg = new SendGridMessage(); + + msg.SetBccSetting(true, "test@example.com"); + msg.SetBypassListManagement(false); + msg.SetBypassSpamManagement(false); + msg.SetBypassBounceManagement(false); + msg.SetBypassUnsubscribeManagement(false); + msg.SetClickTracking(true, true); + msg.SetFooterSetting(true, "footer", "footer"); + msg.SetFrom(new EmailAddress("test@example.com")); + msg.SetGlobalSendAt(0); + msg.SetGlobalSubject("globalSubject"); + msg.SetGoogleAnalytics(true); + msg.SetIpPoolName("ipPoolName"); + msg.SetOpenTracking(true, "substituteTag"); + msg.SetReplyTo(new EmailAddress("test@example.com")); + msg.SetSandBoxMode(true); + msg.SetSendAt(0); + msg.SetSpamCheck(true); + msg.SetSubject("Hello World from the Twilio SendGrid CSharp Library"); + msg.SetSubscriptionTracking(true); + msg.SetTemplateId("templateID"); + + msg.AddAttachment("balance_001.pdf", + "TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gQ3JhcyBwdW12", + "application/pdf", + "attachment", + "Balance Sheet"); + msg.AddBcc("test@example.com"); + msg.AddCategory("category"); + msg.AddCc("test@example.com"); + msg.AddContent(MimeType.Html, "HTML content"); + msg.AddCustomArg("customArgKey", "customArgValue"); + msg.AddGlobalCustomArg("globalCustomArgKey", "globalCustomValue"); + msg.AddGlobalHeader("globalHeaderKey", "globalHeaderValue"); + msg.AddHeader("headerKey", "headerValue"); + msg.AddSection("sectionKey", "sectionValue"); + msg.AddSubstitution("substitutionKey", "substitutionValue"); + msg.AddTo(new EmailAddress("test@example.com")); + + /* **************************************************************************************** + * Serialize & check + * **************************************************************************************** */ + string serializedMessage = msg.Serialize(); + bool containsReferenceHandlingProperty = serializedMessage.Contains(referenceHandlingProperty); + Assert.False(containsReferenceHandlingProperty); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestRetryBehaviourThrowsTimeoutException() + { + var msg = new SendGridMessage(); + msg.SetFrom(new EmailAddress("test@example.com")); + msg.AddTo(new EmailAddress("test@example.com")); + msg.SetSubject("Hello World from the Twilio SendGrid CSharp Library"); + msg.AddContent(MimeType.Html, "HTML content"); + + var options = new SendGridClientOptions + { + ApiKey = fixture.apiKey, + ReliabilitySettings = new ReliabilitySettings(1, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(1)) + }; + + var retryHandler = new RetryDelegatingHandler(options.ReliabilitySettings); + + // Verify we can set the inner handler after constrcution. + retryHandler.InnerHandler = new HttpClientHandler(); + + HttpClient clientToInject = new HttpClient(retryHandler) { Timeout = TimeSpan.FromMilliseconds(1) }; + var sg = new SendGridClient(clientToInject, options.ApiKey); + + var exception = await Assert.ThrowsAsync(() => sg.SendEmailAsync(msg)); + + Assert.NotNull(exception); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async Task TestRetryBehaviourSucceedsOnSecondAttempt() + { + var msg = new SendGridMessage(); + msg.SetFrom(new EmailAddress("test@example.com")); + msg.AddTo(new EmailAddress("test@example.com")); + msg.SetSubject("Hello World from the Twilio SendGrid CSharp Library"); + msg.AddContent(MimeType.Html, "HTML content"); + + var options = new SendGridClientOptions + { + ApiKey = fixture.apiKey, + ReliabilitySettings = new ReliabilitySettings(1, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(1)) + }; + + var httpMessageHandler = new RetryTestBehaviourDelegatingHandler(); + httpMessageHandler.AddBehaviour(httpMessageHandler.TaskCancelled); + httpMessageHandler.AddBehaviour(httpMessageHandler.OK); + + var retryHandler = new RetryDelegatingHandler(httpMessageHandler, options.ReliabilitySettings); + + HttpClient clientToInject = new HttpClient(retryHandler); + var sg = new SendGridClient(clientToInject, options.ApiKey, options.Host); + + var result = await sg.SendEmailAsync(msg); + + Assert.Equal(HttpStatusCode.OK, result.StatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async void TestHttpErrorAsExceptionWhenSetInOptions() + { + await TestHttpErrorAsException((client, apiKey) => new SendGridClient(client, new SendGridClientOptions { ApiKey = apiKey, HttpErrorAsException = true })); + } + + [Fact(Skip = SkipConfigureApiKey)] + public async void TestHttpErrorAsExceptionWhenSetAsParameter() + { + await TestHttpErrorAsException((client, apiKey) => new SendGridClient(client, apiKey, httpErrorAsException: true)); + } + + private async Task TestHttpErrorAsException(Func createClientFunc) + { + var responseObject = new + { + errors = new[] { new { + message = "error message", + field = "field value", + help = "help value" + } } + }; + + var responseMessage = Newtonsoft.Json.JsonConvert.SerializeObject(responseObject, new JsonSerializerSettings + { + PreserveReferencesHandling = PreserveReferencesHandling.None + }); + var mockHandler = new FixedStatusAndMessageHttpMessageHandler(HttpStatusCode.ServiceUnavailable, responseMessage); + var mockClient = new HttpClient(mockHandler); + var client = createClientFunc(mockClient, fixture.apiKey); + + try + { + var response = await client.MakeRequest(new HttpRequestMessage(HttpMethod.Get, "http://api.sendgrid.com/")).ConfigureAwait(false); + } + catch (Exception ex) + { + Assert.NotNull(ex); + Assert.IsType(ex); + + var errorResponseExpected = new SendGridErrorResponse + { + ErrorHttpStatusCode = 503, + ErrorReasonPhrase = "Service Unavailable", + SendGridErrorMessage = "error message", + FieldWithError = "field value", + HelpLink = "help value" + }; + + var jsonErrorReponseExpected = Newtonsoft.Json.JsonConvert.SerializeObject(errorResponseExpected); + + Assert.Equal(jsonErrorReponseExpected, ex.Message); + } + } + + [Theory] + [InlineData("first last ", "first last", "username@example.com")] + [InlineData("", "", "username@example.com")] + [InlineData("username@example.com", "", "username@example.com")] + [InlineData("username@example.com ", "username@example.com", "username@example.com")] + public void TestStringToEmailAddress(string input, string expectedName, string expectedEmailAddress) + { + var actual = MailHelper.StringToEmailAddress(input); + + Assert.True(actual.Name == expectedName && actual.Email == expectedEmailAddress); + } + + /// + /// Tests the conditions in issue #670. + /// + /// + [Fact(Skip = SkipConfigureApiKey)] + public void TestInjectSameHttpClientWithMultipleInstance() + { + var httpMessageHandler = new FixedStatusAndMessageHttpMessageHandler(HttpStatusCode.Accepted, string.Empty); + var clientToInject = new HttpClient(httpMessageHandler); + var sg1 = new SendGridClient(clientToInject, fixture.apiKey); + var sg2 = new SendGridClient(clientToInject, fixture.apiKey); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestBadRequestIsSuccessStatusCodeReturnsFalse() + { + var message = new HttpResponseMessage(); + var response = new Response(HttpStatusCode.BadRequest, message.Content, message.Headers); + Assert.False(response.IsSuccessStatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestOkRequestIsSuccessStatusCodeReturnsTrue() + { + var message = new HttpResponseMessage(); + var response = new Response(HttpStatusCode.OK, message.Content, message.Headers); + Assert.True(response.IsSuccessStatusCode); + } + + [Fact(Skip = SkipConfigureApiKey)] + public void TestIsSuccessStatusCodeEvery2xxCodeReturnsTrue() + { + for (int i = 200; i <= 299; ++i) + { + var message = new HttpResponseMessage(); + var response = new Response((HttpStatusCode)i, message.Content, message.Headers); + Assert.True(response.IsSuccessStatusCode); + } + } + } + + public class FakeWebProxy : IWebProxy + { + public Uri GetProxy(Uri destination) + { + return new Uri("https://dummy-proxy"); + } + + public bool IsBypassed(Uri host) + { + return false; + } + + public ICredentials Credentials { get; set; } + } + + public class FakeHttpMessageHandler : HttpMessageHandler + { + public virtual HttpResponseMessage Send(HttpRequestMessage request) + { + throw new NotImplementedException("Ensure you setup this method as part of your test."); + } + + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + return Task.FromResult(Send(request)); + } + } + + public class FixedStatusAndMessageHttpMessageHandler : FakeHttpMessageHandler + { + private HttpStatusCode httpStatusCode; + private string message; + + public FixedStatusAndMessageHttpMessageHandler(HttpStatusCode httpStatusCode, string message) + { + this.httpStatusCode = httpStatusCode; + this.message = message; + } + + public override HttpResponseMessage Send(HttpRequestMessage request) + { + return new HttpResponseMessage(httpStatusCode) + { + Content = new StringContent(message) + }; + } + } + + /// + /// This message handler could be mocked using e.g. Moq.Mock, but the author of the test is + /// careful about introducing new dependecies in the test project, so creates a concrete + /// class instead. + /// + public class TimeOutExceptionThrowingHttpMessageHandler : FakeHttpMessageHandler + { + private int timeOutMilliseconds; + private string exceptionMessage; + + public TimeOutExceptionThrowingHttpMessageHandler(int timeOutMilliseconds, string exceptionMessage) + { + this.timeOutMilliseconds = timeOutMilliseconds; + this.exceptionMessage = exceptionMessage; + } + + public override HttpResponseMessage Send(HttpRequestMessage request) + { + Thread.Sleep(timeOutMilliseconds); + throw new TimeoutException(exceptionMessage); + } + } + + /// + /// A MessageHandler that returns the invalid character set value "utf8", instead of "utf-8", + /// in the Content-Type response header. + /// This reproduces the current behaviour of the SendGrid API's /scopes and /subusers endpoints. + /// See: #368 https://github.com/sendgrid/sendgrid-csharp/issues/368 + /// + public class InvalidUtf8CharsetMessageHandler : FakeHttpMessageHandler + { + private string message; + + public InvalidUtf8CharsetMessageHandler(string message) + { + this.message = message; + } + + public override HttpResponseMessage Send(HttpRequestMessage request) + { + var response = new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new StringContent(message, Encoding.UTF8) + }; + + response.Content.Headers.ContentType.CharSet = "utf8"; + + return response; + } + } +} diff --git a/tests/SendGrid.Net21Tests/LicenseTests.cs b/tests/SendGrid.Net21Tests/LicenseTests.cs new file mode 100644 index 000000000..bd44c7f68 --- /dev/null +++ b/tests/SendGrid.Net21Tests/LicenseTests.cs @@ -0,0 +1,19 @@ +namespace SendGrid.Tests +{ + using System; + using System.IO; + using System.Linq; + using System.Reflection; + using Xunit; + + public class LicenseTests + { + [Fact] + public void ShouldHaveCurrentYearInLicense() + { + var directoryInfo = new DirectoryInfo(Directory.GetCurrentDirectory()); + var line = File.ReadLines(Path.Combine(directoryInfo.Parent.Parent.Parent.Parent.Parent.FullName, "LICENSE")).Skip(2).Take(1).First(); + Assert.Contains(DateTime.Now.Year.ToString(), line); + } + } +} diff --git a/tests/SendGrid.Net21Tests/PermissionsBuilderTests.cs b/tests/SendGrid.Net21Tests/PermissionsBuilderTests.cs new file mode 100644 index 000000000..06517f185 --- /dev/null +++ b/tests/SendGrid.Net21Tests/PermissionsBuilderTests.cs @@ -0,0 +1,742 @@ +namespace SendGrid.Tests +{ + using System; + using System.Linq; + using Permissions; + using Xunit; + + public class PermissionsBuilderTests + { + [Fact] + public void AddPermissionWithReadOnlyScopeOptionIncludesOnlyReadScopes() + { + var sb = new SendGridPermissionsBuilder(); + sb.AddPermissionsFor(SendGridPermission.Templates, ScopeOptions.ReadOnly); + + var scopes = sb.Build().ToArray(); + + Assert.Equal(3, scopes.Length); + Assert.Contains("templates.read", scopes); + Assert.Contains("templates.versions.activate.read", scopes); + Assert.Contains("templates.versions.read", scopes); + } + + [Fact] + public void BillingPermissionIsMutuallyExclusiveWhenAddedAndBuilderAlreadyContainsOtherPermissions() + { + var sb = new SendGridPermissionsBuilder(); + sb.AddPermissionsFor(SendGridPermission.Alerts); + Assert.Throws(() => sb.AddPermissionsFor(SendGridPermission.Billing)); + } + + [Fact] + public void BillingPermissionIsMutuallyExclusiveWhenIncludedAndBuilderAlreadyContainsOtherPermissions() + { + var sb = new SendGridPermissionsBuilder(); + sb.AddPermissionsFor(SendGridPermission.Alerts); + Assert.Throws(() => sb.Include("billing.create")); + } + + [Fact] + public void BillingPermissionIsMutuallyExclusiveWhenOtherPermissionsAreAddedToBuilderAlreadyContainingBilling() + { + var sb = new SendGridPermissionsBuilder(); + sb.AddPermissionsFor(SendGridPermission.Billing); + Assert.Throws(() => sb.AddPermissionsFor(SendGridPermission.Alerts)); + } + + [Fact] + public void BillingPermissionIsMutuallyExclusiveWhenOtherPermissionsAreIncludeddToBuilderAlreadyContainingBilling() + { + var sb = new SendGridPermissionsBuilder(); + sb.AddPermissionsFor(SendGridPermission.Billing); + Assert.Throws(() => sb.Include("alerts.read")); + } + + [Fact] + public void BillingCanBeAddedToBilling() + { + var sb = new SendGridPermissionsBuilder(); + sb.Include("billing.update"); + sb.AddPermissionsFor(SendGridPermission.Billing, ScopeOptions.ReadOnly); + sb.Include("billing.create"); + var scopes = sb.Build().ToArray(); ; + Assert.Equal(3, scopes.Length); + Assert.Contains("billing.update", scopes); + Assert.Contains("billing.read", scopes); + Assert.Contains("billing.create", scopes); + } + + [Fact] + public void IncludeThrowsIfAnyScopeParamIsInvalid() + { + var sb = new SendGridPermissionsBuilder(); + Assert.Throws(() => sb.Include("alert.create", "bad.scope")); + } + + [Fact] + public void IncludeThrowsIfAnyScopeIsInvalid() + { + var sb = new SendGridPermissionsBuilder(); + Assert.Throws(() => sb.Include(new[] { "alert.create", "bad.scope" })); + } + + [Fact] + public void CanFilterByFunc() + { + var sb = new SendGridPermissionsBuilder(); + sb.AddPermissionsFor(SendGridPermission.MailSettings); + sb.Exclude(scope => scope.Contains("spam")); + var scopes = sb.Build().ToArray(); + Assert.DoesNotContain(scopes, x => x.Contains("spam")); + } + + [Fact] + public void CanFilterByList() + { + var apiScopes = new[] { "alerts.read" }; + var sb = new SendGridPermissionsBuilder(); + sb.AddPermissionsFor(SendGridPermission.Alerts); + sb.Exclude(scope => !apiScopes.Contains(scope)); + var scopes = sb.Build().ToArray(); + Assert.Single(scopes); + Assert.Contains(scopes, x => x == "alerts.read"); + } + + [Fact] + public void CanIncludeAdditionalScopes() + { + var sb = new SendGridPermissionsBuilder(); + sb.Include("mail.send", "mail.batch.create"); + var scopes = sb.Build().ToArray(); + Assert.Contains("mail.send", scopes); + Assert.Contains("mail.batch.create", scopes); + } + + [Fact] + public void CanIncludeAdditionalScopesList() + { + var sb = new SendGridPermissionsBuilder(); + sb.Include(new[] { "alerts.create", "alerts.delete", "mail.send" }); + var scopes = sb.Build().ToArray(); + Assert.Contains("alerts.create", scopes); + Assert.Contains("alerts.delete", scopes); + Assert.Contains("mail.send", scopes); + } + + [Fact] + public void CreateAlerts() + { + var sb = new SendGridPermissionsBuilder(); + sb.AddPermissionsFor(SendGridPermission.Alerts); + + var scopes = sb.Build().ToArray(); + + Assert.True(scopes.Length == 4, "Alerts should have 4 scopes"); + Assert.Contains("alerts.create", scopes); + Assert.Contains("alerts.delete", scopes); + Assert.Contains("alerts.read", scopes); + Assert.Contains("alerts.update", scopes); + } + + [Fact] + public void CreateApiKeys() + { + var sb = new SendGridPermissionsBuilder(); + sb.AddPermissionsFor(SendGridPermission.ApiKeys); + + var scopes = sb.Build().ToArray(); + + Assert.True(scopes.Length == 4, "Api Keys should have 4 scopes"); + Assert.Contains("api_keys.create", scopes); + Assert.Contains("api_keys.delete", scopes); + Assert.Contains("api_keys.read", scopes); + Assert.Contains("api_keys.update", scopes); + } + + [Fact] + public void CreateAsmGroups() + { + var sb = new SendGridPermissionsBuilder(); + sb.AddPermissionsFor(SendGridPermission.ASMGroups); + + var scopes = sb.Build().ToArray(); + + Assert.True(scopes.Length == 4, "Asm Groups should have 4 scopes"); + Assert.Contains("asm.groups.create", scopes); + Assert.Contains("asm.groups.delete", scopes); + Assert.Contains("asm.groups.read", scopes); + Assert.Contains("asm.groups.update", scopes); + } + + [Fact] + public void CreateBilling() + { + var sb = new SendGridPermissionsBuilder(); + sb.AddPermissionsFor(SendGridPermission.Billing); + + var scopes = sb.Build().ToArray(); + + Assert.True(scopes.Length == 4, "Billing should have 4 scopes"); + Assert.Contains("billing.create", scopes); + Assert.Contains("billing.delete", scopes); + Assert.Contains("billing.read", scopes); + Assert.Contains("billing.update", scopes); + } + + [Fact] + public void CreateCategories() + { + var sb = new SendGridPermissionsBuilder(); + sb.AddPermissionsFor(SendGridPermission.Categories); + + var scopes = sb.Build().ToArray(); + + Assert.True(scopes.Length == 6, "Categories should have 6 scopes"); + Assert.Contains("categories.create", scopes); + Assert.Contains("categories.delete", scopes); + Assert.Contains("categories.read", scopes); + Assert.Contains("categories.update", scopes); + Assert.Contains("categories.stats.read", scopes); + Assert.Contains("categories.stats.sums.read", scopes); + } + + [Fact] + public void CreateStats() + { + var sb = new SendGridPermissionsBuilder(); + sb.AddPermissionsFor(SendGridPermission.Stats); + + var scopes = sb.Build().ToArray(); + + Assert.True(scopes.Length == 12, "read-only stats should have 7 scopes"); + Assert.Contains("email_activity.read", scopes); + Assert.Contains("stats.read", scopes); + Assert.Contains("stats.global.read", scopes); + Assert.Contains("browsers.stats.read", scopes); + Assert.Contains("devices.stats.read", scopes); + Assert.Contains("geo.stats.read", scopes); + Assert.Contains("mailbox_providers.stats.read", scopes); + Assert.Contains("clients.desktop.stats.read", scopes); + Assert.Contains("clients.phone.stats.read", scopes); + Assert.Contains("clients.stats.read", scopes); + Assert.Contains("clients.tablet.stats.read", scopes); + Assert.Contains("clients.webmail.stats.read", scopes); + } + + [Fact] + public void CreateReadOnlySupressions() + { + var sb = new SendGridPermissionsBuilder(); + sb.AddPermissionsFor(SendGridPermission.IPs); + + var scopes = sb.Build().ToArray(); + + Assert.True(scopes.Length == 14, "IPs should have 14 scopes"); + Assert.Contains("ips.assigned.read", scopes); + Assert.Contains("ips.read", scopes); + Assert.Contains("ips.pools.create", scopes); + Assert.Contains("ips.pools.delete", scopes); + Assert.Contains("ips.pools.read", scopes); + Assert.Contains("ips.pools.update", scopes); + Assert.Contains("ips.pools.ips.create", scopes); + Assert.Contains("ips.pools.ips.delete", scopes); + Assert.Contains("ips.pools.ips.read", scopes); + Assert.Contains("ips.pools.ips.update", scopes); + Assert.Contains("ips.warmup.create", scopes); + Assert.Contains("ips.warmup.delete", scopes); + Assert.Contains("ips.warmup.read", scopes); + Assert.Contains("ips.warmup.update", scopes); + } + + [Fact] + public void CreateMailSettings() + { + var sb = new SendGridPermissionsBuilder(); + sb.AddPermissionsFor(SendGridPermission.MailSettings); + + var scopes = sb.Build().ToArray(); + + Assert.True(scopes.Length == 12, "Mail Settings should have 12 scopes"); + Assert.Contains("mail_settings.address_whitelist.read", scopes); + Assert.Contains("mail_settings.address_whitelist.update", scopes); + Assert.Contains("mail_settings.bounce_purge.read", scopes); + Assert.Contains("mail_settings.bounce_purge.update", scopes); + Assert.Contains("mail_settings.footer.read", scopes); + Assert.Contains("mail_settings.footer.update", scopes); + Assert.Contains("mail_settings.forward_bounce.read", scopes); + Assert.Contains("mail_settings.forward_bounce.update", scopes); + Assert.Contains("mail_settings.forward_spam.read", scopes); + Assert.Contains("mail_settings.forward_spam.update", scopes); + Assert.Contains("mail_settings.template.read", scopes); + Assert.Contains("mail_settings.template.update", scopes); + } + + [Fact] + public void CreateMail() + { + var sb = new SendGridPermissionsBuilder(); + sb.AddPermissionsFor(SendGridPermission.Mail); + + var scopes = sb.Build().ToArray(); + + Assert.True(scopes.Length == 5, "Mail should have 5 scopes"); + Assert.Contains("mail.batch.create", scopes); + Assert.Contains("mail.batch.delete", scopes); + Assert.Contains("mail.batch.read", scopes); + Assert.Contains("mail.batch.update", scopes); + Assert.Contains("mail.send", scopes); + } + + [Fact] + public void CreateMarketingCampaigns() + { + var sb = new SendGridPermissionsBuilder(); + sb.AddPermissionsFor(SendGridPermission.MarketingCampaigns); + + var scopes = sb.Build().ToArray(); + + Assert.True(scopes.Length == 4, "Marketing Campaigns should have 4 scopes"); + Assert.Contains("marketing_campaigns.create", scopes); + Assert.Contains("marketing_campaigns.delete", scopes); + Assert.Contains("marketing_campaigns.read", scopes); + Assert.Contains("marketing_campaigns.update", scopes); + } + + [Fact] + public void CreatePartnerSettings() + { + var sb = new SendGridPermissionsBuilder(); + sb.AddPermissionsFor(SendGridPermission.PartnerSettings); + + var scopes = sb.Build().ToArray(); + + Assert.True(scopes.Length == 3, "Partner Settings should have 3 scopes"); + Assert.Contains("partner_settings.new_relic.read", scopes); + Assert.Contains("partner_settings.new_relic.update", scopes); + Assert.Contains("partner_settings.read", scopes); + } + + [Fact] + public void CreateScheduledSends() + { + var sb = new SendGridPermissionsBuilder(); + sb.AddPermissionsFor(SendGridPermission.ScheduledSends); + + var scopes = sb.Build().ToArray(); + + Assert.True(scopes.Length == 4, "Scheduled Sends should have 4 scopes"); + Assert.Contains("user.scheduled_sends.create", scopes); + Assert.Contains("user.scheduled_sends.delete", scopes); + Assert.Contains("user.scheduled_sends.read", scopes); + Assert.Contains("user.scheduled_sends.update", scopes); + } + + [Fact] + public void CreateSubusers() + { + var sb = new SendGridPermissionsBuilder(); + sb.AddPermissionsFor(SendGridPermission.Subusers); + + var scopes = sb.Build().ToArray(); + + Assert.True(scopes.Length == 21, "Subusers should have 21 scopes"); + Assert.Contains("subusers.create", scopes); + Assert.Contains("subusers.delete", scopes); + Assert.Contains("subusers.read", scopes); + Assert.Contains("subusers.update", scopes); + Assert.Contains("subusers.credits.create", scopes); + Assert.Contains("subusers.credits.delete", scopes); + Assert.Contains("subusers.credits.read", scopes); + Assert.Contains("subusers.credits.update", scopes); + Assert.Contains("subusers.credits.remaining.create", scopes); + Assert.Contains("subusers.credits.remaining.delete", scopes); + Assert.Contains("subusers.credits.remaining.read", scopes); + Assert.Contains("subusers.credits.remaining.update", scopes); + Assert.Contains("subusers.monitor.create", scopes); + Assert.Contains("subusers.monitor.delete", scopes); + Assert.Contains("subusers.monitor.read", scopes); + Assert.Contains("subusers.monitor.update", scopes); + Assert.Contains("subusers.reputations.read", scopes); + Assert.Contains("subusers.stats.read", scopes); + Assert.Contains("subusers.stats.monthly.read", scopes); + Assert.Contains("subusers.stats.sums.read", scopes); + Assert.Contains("subusers.summary.read", scopes); + } + + [Fact] + public void CreateSuppressions() + { + var sb = new SendGridPermissionsBuilder(); + sb.AddPermissionsFor(SendGridPermission.Suppressions); + + var scopes = sb.Build().ToArray(); + + Assert.True(scopes.Length == 24, "Suppressions should have 24 scopes"); + Assert.Contains("suppression.create", scopes); + Assert.Contains("suppression.delete", scopes); + Assert.Contains("suppression.read", scopes); + Assert.Contains("suppression.update", scopes); + Assert.Contains("suppression.bounces.create", scopes); + Assert.Contains("suppression.bounces.read", scopes); + Assert.Contains("suppression.bounces.update", scopes); + Assert.Contains("suppression.bounces.delete", scopes); + Assert.Contains("suppression.blocks.create", scopes); + Assert.Contains("suppression.blocks.read", scopes); + Assert.Contains("suppression.blocks.update", scopes); + Assert.Contains("suppression.blocks.delete", scopes); + Assert.Contains("suppression.invalid_emails.create", scopes); + Assert.Contains("suppression.invalid_emails.read", scopes); + Assert.Contains("suppression.invalid_emails.update", scopes); + Assert.Contains("suppression.invalid_emails.delete", scopes); + Assert.Contains("suppression.spam_reports.create", scopes); + Assert.Contains("suppression.spam_reports.read", scopes); + Assert.Contains("suppression.spam_reports.update", scopes); + Assert.Contains("suppression.spam_reports.delete", scopes); + Assert.Contains("suppression.unsubscribes.create", scopes); + Assert.Contains("suppression.unsubscribes.read", scopes); + Assert.Contains("suppression.unsubscribes.update", scopes); + Assert.Contains("suppression.unsubscribes.delete", scopes); + } + + [Fact] + public void CreateTeammates() + { + var sb = new SendGridPermissionsBuilder(); + sb.AddPermissionsFor(SendGridPermission.Teammates); + + var scopes = sb.Build().ToArray(); + + Assert.True(scopes.Length == 4, "Teammates should have 4 scopes"); + Assert.Contains("teammates.create", scopes); + Assert.Contains("teammates.read", scopes); + Assert.Contains("teammates.update", scopes); + Assert.Contains("teammates.delete", scopes); + } + + [Fact] + public void CreateTemplates() + { + var sb = new SendGridPermissionsBuilder(); + sb.AddPermissionsFor(SendGridPermission.Templates); + + var scopes = sb.Build().ToArray(); + + Assert.True(scopes.Length == 12, "Templates should have 12 scopes"); + Assert.Contains("templates.create", scopes); + Assert.Contains("templates.delete", scopes); + Assert.Contains("templates.read", scopes); + Assert.Contains("templates.update", scopes); + Assert.Contains("templates.versions.activate.create", scopes); + Assert.Contains("templates.versions.activate.delete", scopes); + Assert.Contains("templates.versions.activate.read", scopes); + Assert.Contains("templates.versions.activate.update", scopes); + Assert.Contains("templates.versions.create", scopes); + Assert.Contains("templates.versions.delete", scopes); + Assert.Contains("templates.versions.read", scopes); + Assert.Contains("templates.versions.update", scopes); + } + + [Fact] + public void CreateTracking() + { + var sb = new SendGridPermissionsBuilder(); + sb.AddPermissionsFor(SendGridPermission.Tracking); + + var scopes = sb.Build().ToArray(); + + Assert.True(scopes.Length == 9, "Tracking should have 9 scopes"); + Assert.Contains("tracking_settings.click.read", scopes); + Assert.Contains("tracking_settings.click.update", scopes); + Assert.Contains("tracking_settings.google_analytics.read", scopes); + Assert.Contains("tracking_settings.google_analytics.update", scopes); + Assert.Contains("tracking_settings.open.read", scopes); + Assert.Contains("tracking_settings.open.update", scopes); + Assert.Contains("tracking_settings.read", scopes); + Assert.Contains("tracking_settings.subscription.read", scopes); + Assert.Contains("tracking_settings.subscription.update", scopes); + } + + [Fact] + public void CreateUserSettings() + { + var sb = new SendGridPermissionsBuilder(); + sb.AddPermissionsFor(SendGridPermission.UserSettings); + + var scopes = sb.Build().ToArray(); + + Assert.True(scopes.Length == 20, "User Settings should have 20 scopes"); + Assert.Contains("user.account.read", scopes); + Assert.Contains("user.credits.read", scopes); + Assert.Contains("user.email.create", scopes); + Assert.Contains("user.email.delete", scopes); + Assert.Contains("user.email.read", scopes); + Assert.Contains("user.email.update", scopes); + Assert.Contains("user.multifactor_authentication.create", scopes); + Assert.Contains("user.multifactor_authentication.delete", scopes); + Assert.Contains("user.multifactor_authentication.read", scopes); + Assert.Contains("user.multifactor_authentication.update", scopes); + Assert.Contains("user.password.read", scopes); + Assert.Contains("user.password.update", scopes); + Assert.Contains("user.profile.read", scopes); + Assert.Contains("user.profile.update", scopes); + Assert.Contains("user.settings.enforced_tls.read", scopes); + Assert.Contains("user.settings.enforced_tls.update", scopes); + Assert.Contains("user.timezone.read", scopes); + Assert.Contains("user.timezone.update", scopes); + Assert.Contains("user.username.read", scopes); + Assert.Contains("user.username.update", scopes); + } + + [Fact] + public void CreateWebhooks() + { + var sb = new SendGridPermissionsBuilder(); + sb.AddPermissionsFor(SendGridPermission.Webhook); + + var scopes = sb.Build().ToArray(); + + Assert.True(scopes.Length == 10, "Webhook should have 10 scopes"); + Assert.Contains("user.webhooks.event.settings.read", scopes); + Assert.Contains("user.webhooks.event.settings.update", scopes); + Assert.Contains("user.webhooks.event.test.create", scopes); + Assert.Contains("user.webhooks.event.test.read", scopes); + Assert.Contains("user.webhooks.event.test.update", scopes); + Assert.Contains("user.webhooks.parse.settings.create", scopes); + Assert.Contains("user.webhooks.parse.settings.delete", scopes); + Assert.Contains("user.webhooks.parse.settings.read", scopes); + Assert.Contains("user.webhooks.parse.settings.update", scopes); + Assert.Contains("user.webhooks.parse.stats.read", scopes); + } + + [Fact] + public void CreateDomainAuthentication() + { + var sb = new SendGridPermissionsBuilder(); + sb.AddPermissionsFor(SendGridPermission.DomainAuthentication); + + var scopes = sb.Build().ToArray(); + + Assert.True(scopes.Length == 4, "Domain Authentication should have 4 scopes"); + Assert.Contains("whitelabel.create", scopes); + Assert.Contains("whitelabel.delete", scopes); + Assert.Contains("whitelabel.read", scopes); + Assert.Contains("whitelabel.update", scopes); + } + + [Fact] + public void CreateReverseDNS() + { + var sb = new SendGridPermissionsBuilder(); + sb.AddPermissionsFor(SendGridPermission.ReverseDNS); + + var scopes = sb.Build().ToArray(); + + Assert.True(scopes.Length == 5, "Reverse DNS should have 5 scopes"); + Assert.Contains("access_settings.activity.read", scopes); + Assert.Contains("access_settings.whitelist.create", scopes); + Assert.Contains("access_settings.whitelist.delete", scopes); + Assert.Contains("access_settings.whitelist.read", scopes); + Assert.Contains("access_settings.whitelist.update", scopes); + } + + [Fact] + public void CreateAdminApiKeyScopes() + { + var sb = new SendGridPermissionsBuilder(); + sb.AddPermissionsFor(SendGridPermission.Admin); + + var scopes = sb.Build().ToArray(); + + Assert.True(scopes.Length == 187, "Admin should have 187 scopes"); + + Assert.Contains("access_settings.activity.read", scopes); + Assert.Contains("access_settings.whitelist.create", scopes); + Assert.Contains("access_settings.whitelist.delete", scopes); + Assert.Contains("access_settings.whitelist.read", scopes); + Assert.Contains("access_settings.whitelist.update", scopes); + Assert.Contains("alerts.create", scopes); + Assert.Contains("alerts.delete", scopes); + Assert.Contains("alerts.read", scopes); + Assert.Contains("alerts.update", scopes); + Assert.Contains("api_keys.create", scopes); + Assert.Contains("api_keys.delete", scopes); + Assert.Contains("api_keys.read", scopes); + Assert.Contains("api_keys.update", scopes); + Assert.Contains("asm.groups.create", scopes); + Assert.Contains("asm.groups.delete", scopes); + Assert.Contains("asm.groups.read", scopes); + Assert.Contains("asm.groups.update", scopes); + Assert.Contains("billing.create", scopes); + Assert.Contains("billing.delete", scopes); + Assert.Contains("billing.read", scopes); + Assert.Contains("billing.update", scopes); + Assert.Contains("browsers.stats.read", scopes); + Assert.Contains("categories.create", scopes); + Assert.Contains("categories.delete", scopes); + Assert.Contains("categories.read", scopes); + Assert.Contains("categories.stats.read", scopes); + Assert.Contains("categories.stats.sums.read", scopes); + Assert.Contains("categories.update", scopes); + Assert.Contains("clients.desktop.stats.read", scopes); + Assert.Contains("clients.phone.stats.read", scopes); + Assert.Contains("clients.stats.read", scopes); + Assert.Contains("clients.tablet.stats.read", scopes); + Assert.Contains("clients.webmail.stats.read", scopes); + Assert.Contains("devices.stats.read", scopes); + Assert.Contains("email_activity.read", scopes); + Assert.Contains("geo.stats.read", scopes); + Assert.Contains("ips.assigned.read", scopes); + Assert.Contains("ips.pools.create", scopes); + Assert.Contains("ips.pools.delete", scopes); + Assert.Contains("ips.pools.ips.create", scopes); + Assert.Contains("ips.pools.ips.delete", scopes); + Assert.Contains("ips.pools.ips.read", scopes); + Assert.Contains("ips.pools.ips.update", scopes); + Assert.Contains("ips.pools.read", scopes); + Assert.Contains("ips.pools.update", scopes); + Assert.Contains("ips.read", scopes); + Assert.Contains("ips.warmup.create", scopes); + Assert.Contains("ips.warmup.delete", scopes); + Assert.Contains("ips.warmup.read", scopes); + Assert.Contains("ips.warmup.update", scopes); + Assert.Contains("mail_settings.address_whitelist.read", scopes); + Assert.Contains("mail_settings.address_whitelist.update", scopes); + Assert.Contains("mail_settings.bounce_purge.read", scopes); + Assert.Contains("mail_settings.bounce_purge.update", scopes); + Assert.Contains("mail_settings.footer.read", scopes); + Assert.Contains("mail_settings.footer.update", scopes); + Assert.Contains("mail_settings.forward_bounce.read", scopes); + Assert.Contains("mail_settings.forward_bounce.update", scopes); + Assert.Contains("mail_settings.forward_spam.read", scopes); + Assert.Contains("mail_settings.forward_spam.update", scopes); + Assert.Contains("mail_settings.plain_content.read", scopes); + Assert.Contains("mail_settings.plain_content.update", scopes); + Assert.Contains("mail_settings.read", scopes); + Assert.Contains("mail_settings.template.read", scopes); + Assert.Contains("mail_settings.template.update", scopes); + Assert.Contains("mail.batch.create", scopes); + Assert.Contains("mail.batch.delete", scopes); + Assert.Contains("mail.batch.read", scopes); + Assert.Contains("mail.batch.update", scopes); + Assert.Contains("mail.send", scopes); + Assert.Contains("mailbox_providers.stats.read", scopes); + Assert.Contains("marketing_campaigns.create", scopes); + Assert.Contains("marketing_campaigns.delete", scopes); + Assert.Contains("marketing_campaigns.read", scopes); + Assert.Contains("marketing_campaigns.update", scopes); + Assert.Contains("partner_settings.new_relic.read", scopes); + Assert.Contains("partner_settings.new_relic.update", scopes); + Assert.Contains("partner_settings.read", scopes); + Assert.Contains("stats.global.read", scopes); + Assert.Contains("stats.read", scopes); + Assert.Contains("subusers.create", scopes); + Assert.Contains("subusers.credits.create", scopes); + Assert.Contains("subusers.credits.delete", scopes); + Assert.Contains("subusers.credits.read", scopes); + Assert.Contains("subusers.credits.remaining.create", scopes); + Assert.Contains("subusers.credits.remaining.delete", scopes); + Assert.Contains("subusers.credits.remaining.read", scopes); + Assert.Contains("subusers.credits.remaining.update", scopes); + Assert.Contains("subusers.credits.update", scopes); + Assert.Contains("subusers.delete", scopes); + Assert.Contains("subusers.monitor.create", scopes); + Assert.Contains("subusers.monitor.delete", scopes); + Assert.Contains("subusers.monitor.read", scopes); + Assert.Contains("subusers.monitor.update", scopes); + Assert.Contains("subusers.read", scopes); + Assert.Contains("subusers.reputations.read", scopes); + Assert.Contains("subusers.stats.monthly.read", scopes); + Assert.Contains("subusers.stats.read", scopes); + Assert.Contains("subusers.stats.sums.read", scopes); + Assert.Contains("subusers.summary.read", scopes); + Assert.Contains("subusers.update", scopes); + Assert.Contains("suppression.blocks.create", scopes); + Assert.Contains("suppression.blocks.delete", scopes); + Assert.Contains("suppression.blocks.read", scopes); + Assert.Contains("suppression.blocks.update", scopes); + Assert.Contains("suppression.bounces.create", scopes); + Assert.Contains("suppression.bounces.delete", scopes); + Assert.Contains("suppression.bounces.read", scopes); + Assert.Contains("suppression.bounces.update", scopes); + Assert.Contains("suppression.create", scopes); + Assert.Contains("suppression.delete", scopes); + Assert.Contains("suppression.invalid_emails.create", scopes); + Assert.Contains("suppression.invalid_emails.delete", scopes); + Assert.Contains("suppression.invalid_emails.read", scopes); + Assert.Contains("suppression.invalid_emails.update", scopes); + Assert.Contains("suppression.read", scopes); + Assert.Contains("suppression.spam_reports.create", scopes); + Assert.Contains("suppression.spam_reports.delete", scopes); + Assert.Contains("suppression.spam_reports.read", scopes); + Assert.Contains("suppression.spam_reports.update", scopes); + Assert.Contains("suppression.unsubscribes.create", scopes); + Assert.Contains("suppression.unsubscribes.delete", scopes); + Assert.Contains("suppression.unsubscribes.read", scopes); + Assert.Contains("suppression.unsubscribes.update", scopes); + Assert.Contains("suppression.update", scopes); + Assert.Contains("teammates.create", scopes); + Assert.Contains("teammates.read", scopes); + Assert.Contains("teammates.update", scopes); + Assert.Contains("teammates.delete", scopes); + Assert.Contains("templates.create", scopes); + Assert.Contains("templates.delete", scopes); + Assert.Contains("templates.read", scopes); + Assert.Contains("templates.update", scopes); + Assert.Contains("templates.versions.activate.create", scopes); + Assert.Contains("templates.versions.activate.delete", scopes); + Assert.Contains("templates.versions.activate.read", scopes); + Assert.Contains("templates.versions.activate.update", scopes); + Assert.Contains("templates.versions.create", scopes); + Assert.Contains("templates.versions.delete", scopes); + Assert.Contains("templates.versions.read", scopes); + Assert.Contains("templates.versions.update", scopes); + Assert.Contains("tracking_settings.click.read", scopes); + Assert.Contains("tracking_settings.click.update", scopes); + Assert.Contains("tracking_settings.google_analytics.read", scopes); + Assert.Contains("tracking_settings.google_analytics.update", scopes); + Assert.Contains("tracking_settings.open.read", scopes); + Assert.Contains("tracking_settings.open.update", scopes); + Assert.Contains("tracking_settings.read", scopes); + Assert.Contains("tracking_settings.subscription.read", scopes); + Assert.Contains("tracking_settings.subscription.update", scopes); + Assert.Contains("user.account.read", scopes); + Assert.Contains("user.credits.read", scopes); + Assert.Contains("user.email.create", scopes); + Assert.Contains("user.email.delete", scopes); + Assert.Contains("user.email.read", scopes); + Assert.Contains("user.email.update", scopes); + Assert.Contains("user.multifactor_authentication.create", scopes); + Assert.Contains("user.multifactor_authentication.delete", scopes); + Assert.Contains("user.multifactor_authentication.read", scopes); + Assert.Contains("user.multifactor_authentication.update", scopes); + Assert.Contains("user.password.read", scopes); + Assert.Contains("user.password.update", scopes); + Assert.Contains("user.profile.read", scopes); + Assert.Contains("user.profile.update", scopes); + Assert.Contains("user.scheduled_sends.create", scopes); + Assert.Contains("user.scheduled_sends.delete", scopes); + Assert.Contains("user.scheduled_sends.read", scopes); + Assert.Contains("user.scheduled_sends.update", scopes); + Assert.Contains("user.settings.enforced_tls.read", scopes); + Assert.Contains("user.settings.enforced_tls.update", scopes); + Assert.Contains("user.timezone.read", scopes); + Assert.Contains("user.username.read", scopes); + Assert.Contains("user.username.update", scopes); + Assert.Contains("user.webhooks.event.settings.read", scopes); + Assert.Contains("user.webhooks.event.settings.update", scopes); + Assert.Contains("user.webhooks.event.test.create", scopes); + Assert.Contains("user.webhooks.event.test.read", scopes); + Assert.Contains("user.webhooks.event.test.update", scopes); + Assert.Contains("user.webhooks.parse.settings.create", scopes); + Assert.Contains("user.webhooks.parse.settings.delete", scopes); + Assert.Contains("user.webhooks.parse.settings.read", scopes); + Assert.Contains("user.webhooks.parse.settings.update", scopes); + Assert.Contains("user.webhooks.parse.stats.read", scopes); + Assert.Contains("whitelabel.create", scopes); + Assert.Contains("whitelabel.delete", scopes); + Assert.Contains("whitelabel.read", scopes); + Assert.Contains("whitelabel.update", scopes); + } + } +} diff --git a/tests/SendGrid.Net21Tests/PreSendEmailValidation/WhenCreatingASendGridMessage.cs b/tests/SendGrid.Net21Tests/PreSendEmailValidation/WhenCreatingASendGridMessage.cs new file mode 100644 index 000000000..87f4477c7 --- /dev/null +++ b/tests/SendGrid.Net21Tests/PreSendEmailValidation/WhenCreatingASendGridMessage.cs @@ -0,0 +1,66 @@ +using System; +using System.Collections.Generic; +using SendGrid.Helpers.Mail; +using Xunit; + +namespace SendGrid.Tests.PreSendEmailValidation +{ + public class WhenCreatingASendGridMessage + { + [Fact] + public void WithAnEmptyListOfBlindCarbonCopiesThenAnExceptionIsThrown() + { + var sendGridMessage = MailHelper.CreateSingleEmail(new EmailAddress(), new EmailAddress(), string.Empty, string.Empty, string.Empty); + Assert.Throws(() => { sendGridMessage.AddBccs(new List()); }); + } + + [Fact] + public void WithANullListOfBlindCarbonCopiesThenAnExceptionIsThrown() + { + var sendGridMessage = MailHelper.CreateSingleEmail(new EmailAddress(), new EmailAddress(), string.Empty, string.Empty, string.Empty); + Assert.Throws(() => { sendGridMessage.AddBccs(null); }); + } + + [Fact] + public void WithANullBlindCarbonCopyThenAnExceptionIsThrown() + { + var sendGridMessage = MailHelper.CreateSingleEmail(new EmailAddress(), new EmailAddress(), string.Empty, string.Empty, string.Empty); + Assert.Throws(() => { sendGridMessage.AddBcc(null, 0); }); + } + + [Fact] + public void WithAnEmptyListOfCarbonCopiesThenAnExceptionIsThrown() + { + var sendGridMessage = MailHelper.CreateSingleEmail(new EmailAddress(), new EmailAddress(), string.Empty, string.Empty, string.Empty); + Assert.Throws(() => { sendGridMessage.AddCcs(new List()); }); + } + + [Fact] + public void WithANullListOfCarbonCopiesThenAnExceptionIsThrown() + { + var sendGridMessage = MailHelper.CreateSingleEmail(new EmailAddress(), new EmailAddress(), string.Empty, string.Empty, string.Empty); + Assert.Throws(() => { sendGridMessage.AddCcs(new List()); }); + } + + [Fact] + public void WithANullCarbonCopyThenAnExceptionIsThrown() + { + var sendGridMessage = MailHelper.CreateSingleEmail(new EmailAddress(), new EmailAddress(), string.Empty, string.Empty, string.Empty); + Assert.Throws(() => { sendGridMessage.AddCc(null, 0); }); + } + + [Fact] + public void WithAnEmptyListOfReplyTosThenAnExceptionIsThrown() + { + var sendGridMessage = MailHelper.CreateSingleEmail(new EmailAddress(), new EmailAddress(), string.Empty, string.Empty, string.Empty); + Assert.Throws(() => { sendGridMessage.AddReplyTos(new List()); }); + } + + [Fact] + public void WithANullListOfReplyTosThenAnExceptionIsThrown() + { + var sendGridMessage = MailHelper.CreateSingleEmail(new EmailAddress(), new EmailAddress(), string.Empty, string.Empty, string.Empty); + Assert.Throws(() => { sendGridMessage.AddReplyTos(null); }); + } + } +} \ No newline at end of file diff --git a/tests/SendGrid.Net21Tests/Reliability/ReliabilitySettingsTests.cs b/tests/SendGrid.Net21Tests/Reliability/ReliabilitySettingsTests.cs new file mode 100644 index 000000000..c63675775 --- /dev/null +++ b/tests/SendGrid.Net21Tests/Reliability/ReliabilitySettingsTests.cs @@ -0,0 +1,114 @@ +namespace SendGrid.Tests.Reliability +{ + using System; + using SendGrid.Helpers.Reliability; + using Xunit; + + public class ReliabilitySettingsTests + { + [Fact] + public void ShouldNotAllowNegativeRetryCount() + { + var exception = Assert.Throws(() => + new ReliabilitySettings(-1, + TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(1))); + + Assert.Contains("maximumNumberOfRetries must be greater than 0", exception.Message); + } + + [Fact] + public void ShouldNotAllowNegativeMinimumBackoffTime() + { + var exception = Assert.Throws(() => + new ReliabilitySettings(1, + TimeSpan.FromSeconds(-1), + TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(1))); + + Assert.Contains("minimumBackoff must be greater than 0", exception.Message); + } + + [Fact] + public void ShouldNotAllowNegativeMaximumBackoffTime() + { + var exception = Assert.Throws(() => + new ReliabilitySettings(1, + TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(-11), + TimeSpan.FromSeconds(1))); + + Assert.Contains("maximumBackOff must be greater than 0", exception.Message); + } + + [Fact] + public void ShouldNotAllowNegativeDeltaBackoffTime() + { + var exception = Assert.Throws(() => + new ReliabilitySettings(1, + TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(-1))); + + Assert.Contains("deltaBackOff must be greater than 0", exception.Message); + } + + [Fact] + public void ShouldNotAllowRetryCountGreaterThan5() + { + var exception = Assert.Throws(() => + new ReliabilitySettings(6, + TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(1))); + + Assert.Contains("The maximum number of retries allowed is 5", exception.Message); + } + + [Fact] + public void ShouldNotAllowMinimumBackOffGreaterThanMaximumBackoff() + { + var exception = Assert.Throws(() => + new ReliabilitySettings(1, + TimeSpan.FromSeconds(11), + TimeSpan.FromSeconds(10), + TimeSpan.FromSeconds(1))); + + Assert.Contains("minimumBackoff must be less than maximumBackOff", exception.Message); + } + + [Fact] + public void ShouldNotAllowMaximumBackOffGreaterThan30Seconds() + { + var exception = Assert.Throws(() => + new ReliabilitySettings(1, + TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(31), + TimeSpan.FromSeconds(1))); + + Assert.Contains("maximumBackOff must be less than 30 seconds", exception.Message); + } + + [Fact] + public void ShouldPassValidValuesFromDefaultConstruct() + { + var defaultSettings = new ReliabilitySettings(); + + Assert.Equal(TimeSpan.Zero, defaultSettings.MaximumBackOff); + Assert.Equal(TimeSpan.Zero, defaultSettings.MinimumBackOff); + Assert.Equal(TimeSpan.Zero, defaultSettings.DeltaBackOff); + Assert.Equal(0, defaultSettings.MaximumNumberOfRetries); + Assert.Equal(ReliabilitySettings.DefaultRetriableServerErrorStatusCodes, defaultSettings.RetriableServerErrorStatusCodes); + } + + [Fact] + public void ShouldNotAllowNullInstanceOnSendGridClientOptions() + { + var options = new SendGridClientOptions(); + + Assert.Throws(() => options.ReliabilitySettings = null); + } + } +} + diff --git a/tests/SendGrid.Net21Tests/Reliability/RetryDelegatingHandlerTests.cs b/tests/SendGrid.Net21Tests/Reliability/RetryDelegatingHandlerTests.cs new file mode 100644 index 000000000..e8e6dba17 --- /dev/null +++ b/tests/SendGrid.Net21Tests/Reliability/RetryDelegatingHandlerTests.cs @@ -0,0 +1,116 @@ +namespace SendGrid.Tests.Reliability +{ + using System; + using System.Net; + using System.Net.Http; + using System.Threading.Tasks; + using SendGrid.Helpers.Reliability; + using Xunit; + + public class RetryDelegatingHandlerTests + { + private readonly HttpClient client; + + private readonly RetryTestBehaviourDelegatingHandler innerHandler; + + public RetryDelegatingHandlerTests() + { + var reliabilitySettings = new ReliabilitySettings(1, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(10), + TimeSpan.FromSeconds(1)); + + innerHandler = new RetryTestBehaviourDelegatingHandler(); + client = new HttpClient(new RetryDelegatingHandler(innerHandler, reliabilitySettings)) + { + BaseAddress = new Uri("http://localhost") + }; + } + + [Fact] + public async Task ShouldReturnHttpResponseAndNotRetryWhenSuccessful() + { + innerHandler.AddBehaviour(innerHandler.OK); + + var result = await client.SendAsync(new HttpRequestMessage()); + + Assert.Equal(HttpStatusCode.OK, result.StatusCode); + Assert.Equal(1, innerHandler.InvocationCount); + } + + [Fact] + public async Task ShouldReturnHttpResponseAndNotRetryWhenUnauthorised() + { + innerHandler.AddBehaviour(innerHandler.AuthenticationError); + + var result = await client.SendAsync(new HttpRequestMessage()); + + Assert.Equal(HttpStatusCode.Unauthorized, result.StatusCode); + Assert.Equal(1, innerHandler.InvocationCount); + } + + [Fact] + public async Task ShouldReturnErrorWithoutRetryWhenErrorIsNotTransient() + { + innerHandler.AddBehaviour(innerHandler.NonTransientException); + + await Assert.ThrowsAsync(() => client.SendAsync(new HttpRequestMessage())); + + Assert.Equal(1, innerHandler.InvocationCount); + } + + [Fact] + public async Task ShouldReturnErrorWithoutRetryWhen500ErrorStatusIsNotTransient() + { + innerHandler.AddBehaviour(innerHandler.HttpVersionNotSupported); + + var response = await client.SendAsync(new HttpRequestMessage()); + + Assert.Equal(HttpStatusCode.HttpVersionNotSupported, response.StatusCode); + Assert.Equal(1, innerHandler.InvocationCount); + } + + [Fact] + public async Task ShouldReturnErrorWithoutRetryWhen501ErrorStatus() + { + innerHandler.AddBehaviour(innerHandler.NotImplemented); + + var response = await client.SendAsync(new HttpRequestMessage()); + + Assert.Equal(HttpStatusCode.NotImplemented, response.StatusCode); + Assert.Equal(1, innerHandler.InvocationCount); + } + + [Fact] + public async Task ShouldRetryOnceWhenFailedOnFirstAttemptThenSuccessful() + { + innerHandler.AddBehaviour(innerHandler.TaskCancelled); + innerHandler.AddBehaviour(innerHandler.OK); + + var result = await client.SendAsync(new HttpRequestMessage()); + + Assert.Equal(HttpStatusCode.OK, result.StatusCode); + Assert.Equal(2, innerHandler.InvocationCount); + } + + [Fact] + public async Task ShouldRetryTheExpectedAmountOfTimesAndReturnTimeoutExceptionWhenTasksCancelled() + { + innerHandler.AddBehaviour(innerHandler.TaskCancelled); + innerHandler.AddBehaviour(innerHandler.TaskCancelled); + + await Assert.ThrowsAsync(() => client.SendAsync(new HttpRequestMessage())); + + Assert.Equal(2, innerHandler.InvocationCount); + } + + [Fact] + public async Task ShouldRetryTheExpectedAmountOfTimesAndReturnExceptionWhenInternalServerErrorsEncountered() + { + innerHandler.AddBehaviour(innerHandler.InternalServerError); + innerHandler.AddBehaviour(innerHandler.ServiceUnavailable); + + await Assert.ThrowsAsync(() => client.SendAsync(new HttpRequestMessage())); + + Assert.Equal(2, innerHandler.InvocationCount); + } + } +} diff --git a/tests/SendGrid.Net21Tests/Reliability/RetryTestBehaviourDelegatingHandler.cs b/tests/SendGrid.Net21Tests/Reliability/RetryTestBehaviourDelegatingHandler.cs new file mode 100644 index 000000000..b594ee789 --- /dev/null +++ b/tests/SendGrid.Net21Tests/Reliability/RetryTestBehaviourDelegatingHandler.cs @@ -0,0 +1,80 @@ +namespace SendGrid.Tests.Reliability +{ + using System; + using System.Collections.Generic; + using System.Net; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + + public class RetryTestBehaviourDelegatingHandler : DelegatingHandler + { + private readonly List>> behaviours; + + public RetryTestBehaviourDelegatingHandler() + { + behaviours = new List>>(); + } + + public int InvocationCount { get; private set; } + + public void AddBehaviour(Func> configuredBehavior) + { + Task behaviour() + { + InvocationCount++; + return configuredBehavior(); + } + + behaviours.Add(behaviour); + } + + public Task OK() + { + return CreateHttpResponse(HttpStatusCode.OK); + } + + public Task InternalServerError() + { + return CreateHttpResponse(HttpStatusCode.InternalServerError); + } + public Task ServiceUnavailable() + { + return CreateHttpResponse(HttpStatusCode.ServiceUnavailable); + } + + public Task AuthenticationError() + { + return CreateHttpResponse(HttpStatusCode.Unauthorized); + } + public Task HttpVersionNotSupported() + { + return CreateHttpResponse(HttpStatusCode.HttpVersionNotSupported); + } + public Task NotImplemented() + { + return CreateHttpResponse(HttpStatusCode.NotImplemented); + } + + public Task CreateHttpResponse(HttpStatusCode statusCode) + { + var httpResponseMessage = new HttpResponseMessage(statusCode) { Content = new StringContent(string.Empty) }; + return Task.Factory.StartNew(() => httpResponseMessage); + } + + public Task TaskCancelled() + { + throw new TaskCanceledException(); + } + + public Task NonTransientException() + { + throw new InvalidOperationException(); + } + + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + return behaviours[InvocationCount](); + } + } +} diff --git a/tests/SendGrid.Net21Tests/RequiredFilesExistTest.cs b/tests/SendGrid.Net21Tests/RequiredFilesExistTest.cs new file mode 100644 index 000000000..86916eda5 --- /dev/null +++ b/tests/SendGrid.Net21Tests/RequiredFilesExistTest.cs @@ -0,0 +1,92 @@ +namespace SendGrid.Tests +{ + using System.IO; + using Xunit; + + public class TestRequiredFilesExist + { + + // ./Docker or docker/Docker + public void checkDockerExists() + { + bool dockerExists = File.Exists("./Dockerfile") || + File.Exists("./docker/Dockerfile"); + Assert.True(dockerExists); + } + + // ./docker-compose.yml or ./docker/docker-compose.yml + public void checkDockerComposeExists() + { + bool dockerComposeExists = File.Exists("./docker-compose.yml") || + File.Exists("./docker/docker-compose.yml"); + Assert.True(dockerComposeExists); + } + + // ./.env_sample + public void checkEnvSampleExists() + { + Assert.True(File.Exists("./.env_sample")); + } + + // ./.gitignore + public void checkGitIgnoreExists() + { + Assert.True(File.Exists("./.gitignore")); + } + + + // ./CHANGELOG.md + public void checkChangelogExists() + { + Assert.True(File.Exists("./CHANGELOG.md")); + } + + // ./CODE_OF_CONDUCT.md + public void checkCodeOfConductExists() + { + Assert.True(File.Exists("./CODE_OF_CONDUCT.md")); + } + + // ./CONTRIBUTING.md + public void checkContributingGuideExists() + { + Assert.True(File.Exists("./CONTRIBUTING.md")); + } + + // ./LICENSE + public void checkLicenseExists() + { + Assert.True(File.Exists("./LICENSE")); + } + + // ./PULL_REQUEST_TEMPLATE.md + public void checkPullRequestExists() + { + Assert.True(File.Exists("./PULL_REQUEST_TEMPLATE.md")); + } + + // ./README.md + public void checkReadMeExists() + { + Assert.True(File.Exists("./README.md")); + } + + // ./TROUBLESHOOTING.md + public void checkTroubleShootingGuideExists() + { + Assert.True(File.Exists("./TROUBLESHOOTING.md")); + } + + // ./USAGE.md + public void checkUsageGuideExists() + { + Assert.True(File.Exists("./USAGE.md")); + } + + // ./USE_CASES.md + public void checkUseCases() + { + Assert.True(File.Exists("./USE_CASES.md")); + } + } +} diff --git a/tests/SendGrid.Net21Tests/ResponseTests.cs b/tests/SendGrid.Net21Tests/ResponseTests.cs new file mode 100644 index 000000000..93cba5c6d --- /dev/null +++ b/tests/SendGrid.Net21Tests/ResponseTests.cs @@ -0,0 +1,69 @@ +using Newtonsoft.Json.Linq; + +using System.Collections.Generic; +using System.Net; +using System.Net.Http; +using System.Threading.Tasks; + +using Xunit; + +namespace SendGrid.Tests +{ + public class ResponseTests + { + [Fact] + public async Task DeserializeResponseBodyAsync_NullHttpContent_ReturnsEmptyDictionary() + { + var response = new Response(HttpStatusCode.OK, null, null); + Dictionary responseBody = await response.DeserializeResponseBodyAsync(); + Assert.Empty(responseBody); + } + + [Fact] + public async Task DeserializeResponseBodyAsync_JsonHttpContent_ReturnsBodyAsDictionary() + { + var content = "{\"scopes\": [\"alerts.read\"]}"; + var response = new Response(HttpStatusCode.OK, new StringContent(content), null); + Dictionary responseBody = await response.DeserializeResponseBodyAsync(); + var enumerable = responseBody["scopes"]; + Assert.Equal(new JArray() { "alerts.read" }, enumerable); + } + + [Fact] + public async Task DeserializeResponseBodyAsync_OverrideHttpContent_ReturnsBodyAsDictionary() + { + var content = "{\"scopes\": [\"alerts.read\"]}"; + var response = new Response(HttpStatusCode.OK, null, null); + Dictionary responseBody = await response.DeserializeResponseBodyAsync(new StringContent(content)); + Assert.Equal(new JArray() { "alerts.read" }, responseBody["scopes"]); + } + + [Fact] + public void DeserializeResponseHeaders_NullHttpResponseHeaders_ReturnsEmptyDictionary() + { + var response = new Response(HttpStatusCode.OK, null, null); + Dictionary responseHeadersDeserialized = response.DeserializeResponseHeaders(); + Assert.Empty(responseHeadersDeserialized); + } + + [Fact] + public void DeserializeResponseHeaders_HttpResponseHeaders_ReturnsHeadersAsDictionary() + { + var message = new HttpResponseMessage(); + message.Headers.Add("HeaderKey", "HeaderValue"); + var response = new Response(HttpStatusCode.OK, null, message.Headers); + Dictionary responseHeadersDeserialized = response.DeserializeResponseHeaders(); + Assert.Equal("HeaderValue", responseHeadersDeserialized["HeaderKey"]); + } + + [Fact] + public void DeserializeResponseHeaders_OverrideHttpResponseHeaders_ReturnsHeadersAsDictionary() + { + var message = new HttpResponseMessage(); + message.Headers.Add("HeaderKey", "HeaderValue"); + var response = new Response(HttpStatusCode.OK, null, null); + Dictionary responseHeadersDeserialized = response.DeserializeResponseHeaders(message.Headers); + Assert.Equal("HeaderValue", responseHeadersDeserialized["HeaderKey"]); + } + } +} diff --git a/tests/SendGrid.Net21Tests/SendGrid.Net21Tests.csproj b/tests/SendGrid.Net21Tests/SendGrid.Net21Tests.csproj new file mode 100644 index 000000000..7258c9c1e --- /dev/null +++ b/tests/SendGrid.Net21Tests/SendGrid.Net21Tests.csproj @@ -0,0 +1,23 @@ + + + + net8.0 + true + false + + + + + + + + + + + + + + + + + diff --git a/tests/SendGrid.Net21Tests/SendGridClientExtensionsTests.cs b/tests/SendGrid.Net21Tests/SendGridClientExtensionsTests.cs new file mode 100644 index 000000000..0cea5b3a1 --- /dev/null +++ b/tests/SendGrid.Net21Tests/SendGridClientExtensionsTests.cs @@ -0,0 +1,62 @@ +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +using Moq; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using SendGrid.Permissions; +using Xunit; + +namespace SendGrid.Tests +{ + public class SendGridClientExtensionsTests + { + [Fact] + public async Task MasksPermissionsForAGivenClient() + { + var content = "{\"scopes\": [\"alerts.read\"]}"; + var response = new Response(HttpStatusCode.OK, new StringContent(content), null); + var mockClient = new Mock(); + mockClient.Setup(x => x.RequestAsync(BaseClient.Method.GET, null, null, "scopes", default)) + .ReturnsAsync(response); + + var builder = await mockClient.Object.CreateMaskedPermissionsBuilderForClient(); + + builder.Include("mail.send", "alerts.read"); + var scopes = builder.Build().ToArray(); + + Assert.Single(scopes); + Assert.Contains("alerts.read", scopes); + } + + [Fact] + public async Task CallsApiWithBuiltScopes() + { + string[] requestedScopes = null; + string requestedApiKeyName = null; + var mockClient = new Mock(); + mockClient.Setup(x => x.RequestAsync(BaseClient.Method.POST, It.IsAny(), null, "api_keys", default)) + .Callback((method, body, query, path, token) => + { + JObject json = JsonConvert.DeserializeObject(body) as JObject; + requestedScopes = (json["scopes"] as JArray).Select(x => x.Value()).ToArray(); + requestedApiKeyName = (json["name"]).Value(); + }) + .ReturnsAsync(new Response(HttpStatusCode.Created, null, null)); + + var builder = new SendGridPermissionsBuilder(); + builder.AddPermissionsFor(SendGridPermission.Alerts); + var response = await mockClient.Object.CreateApiKey(builder, "Alerts Test"); + + Assert.Equal(4, requestedScopes.Length); + Assert.Contains("alerts.create", requestedScopes); + Assert.Contains("alerts.delete", requestedScopes); + Assert.Contains("alerts.read", requestedScopes); + Assert.Contains("alerts.update", requestedScopes); + + Assert.Equal("Alerts Test", requestedApiKeyName); + } + } +} diff --git a/tests/SendGrid.Net21Tests/SendgridEmailClientTests.cs b/tests/SendGrid.Net21Tests/SendgridEmailClientTests.cs new file mode 100644 index 000000000..006581ea2 --- /dev/null +++ b/tests/SendGrid.Net21Tests/SendgridEmailClientTests.cs @@ -0,0 +1,55 @@ +namespace SendGrid.Tests +{ + using System; + using System.Threading.Tasks; + using SendGrid.Helpers.Mail; + using Xunit; + + public class SendgridEmailClientTests + { + [Fact] + public void TestClientOptionsConstruction() + { + var options = new SendGridClientOptions(); + Assert.Equal("https://api.sendgrid.com", options.Host); + } + [Fact] + public void TestClientOptionsSetDataResidency() + { + var options = new SendGridClientOptions(); + options.SetDataResidency("eu"); + Assert.Equal("https://api.eu.sendgrid.com/", options.Host); + } + [Fact] + public void TestClientOptionsSetDataResidencyEU() + { + var options = new SendGridClientOptions(); + options.SetDataResidency("eu"); + Assert.Equal("https://api.eu.sendgrid.com/", options.Host); + } + + [Fact] + public void TestClientOptionsSetViaSendgridClient() + { + var options = new SendGridClientOptions(); + options.SetDataResidency("eu"); + var sg = new SendGridClient(options); + Assert.Equal("https://api.eu.sendgrid.com/", options.Host); + } + + [Fact] + public void TestErrorClientOptionsNUllEmpty() + { + var options = new SendGridClientOptions(); + Assert.Throws(() => options.SetDataResidency("")); + Assert.Throws(() => options.SetDataResidency(null)); + } + + [Fact] + public void TestErrorClientOptions() + { + var options = new SendGridClientOptions(); + Assert.Throws(() => options.SetDataResidency("foo")); + } + } +} diff --git a/tests/SendGrid.Net21Tests/TemplateDataSerialisationTests.cs b/tests/SendGrid.Net21Tests/TemplateDataSerialisationTests.cs new file mode 100644 index 000000000..e39f41f26 --- /dev/null +++ b/tests/SendGrid.Net21Tests/TemplateDataSerialisationTests.cs @@ -0,0 +1,42 @@ +using Newtonsoft.Json; +using SendGrid.Helpers.Mail; +using Xunit; + +namespace SendGrid.Tests +{ + public class TemplateDataSerialisationTests + { + [Fact] + public void TestSetTemplateDataWorksWithSpecifiedJsonPropertyNames() + { + var msg = new SendGridMessage(); + + var dynamicTemplateData = new TestTemplateData + { + MyCamelCaseProperty = "camelCase", + MyKebabCaseProperty = "kebab-case", + MyPascalCaseProperty = "PascalCase", + MySnakeCaseProperty = "snake_case", + }; + + msg.SetTemplateData(dynamicTemplateData); + var actual = msg.Serialize(); + var expected = "{\"personalizations\":[{\"dynamic_template_data\":{\"myCamelCaseProperty\":\"camelCase\",\"my-kebab-case-property\":\"kebab-case\",\"MyPascalCaseProperty\":\"PascalCase\",\"my_snake_case_property\":\"snake_case\"}}]}"; + Assert.Equal(expected, actual); + } + + private class TestTemplateData + { + [JsonProperty("myCamelCaseProperty")] + public string MyCamelCaseProperty { get; set; } + + [JsonProperty("my-kebab-case-property")] + public string MyKebabCaseProperty { get; set; } + + public string MyPascalCaseProperty { get; set; } + + [JsonProperty("my_snake_case_property")] + public string MySnakeCaseProperty { get; set; } + } + } +} diff --git a/tests/SendGrid.Net21Tests/TwilioEmailClientTests.cs b/tests/SendGrid.Net21Tests/TwilioEmailClientTests.cs new file mode 100644 index 000000000..80d59b7e4 --- /dev/null +++ b/tests/SendGrid.Net21Tests/TwilioEmailClientTests.cs @@ -0,0 +1,24 @@ +namespace SendGrid.Tests +{ + using System; + using Xunit; + + public class TwilioEmailClientTests + { + [Fact] + public void TestClientOptionsConstruction() + { + var options = new TwilioEmailClientOptions("username", "password"); + Assert.Equal("https://email.twilio.com", options.Host); + Assert.Equal("Basic", options.Auth.Scheme); + Assert.Equal("dXNlcm5hbWU6cGFzc3dvcmQ=", options.Auth.Parameter); + } + + [Fact] + public void TestNullUsernameOrPassword() + { + Assert.Throws(() => new TwilioEmailClientOptions(null, "password")); + Assert.Throws(() => new TwilioEmailClientOptions("username", null)); + } + } +} diff --git a/tests/SendGrid.Tests/Integration.cs b/tests/SendGrid.Tests/Integration.cs index b80ae8582..c3b696e57 100644 --- a/tests/SendGrid.Tests/Integration.cs +++ b/tests/SendGrid.Tests/Integration.cs @@ -4,7 +4,6 @@ using System.Collections.Generic; using System.Net; using System.Net.Http; - using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; @@ -23,6 +22,8 @@ public class IntegrationFixture public class Integration : IClassFixture { + private const string SkipConfigureApiKey = "API key must be configured"; // change to null after configuring API key + IntegrationFixture fixture; private readonly ITestOutputHelper output; @@ -39,7 +40,7 @@ private SendGridClient GetClient(string mockStatusCode) } // Base case for sending a single email - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestSendSingleEmailWithHelper() { var msg = new SendGridMessage(); @@ -60,10 +61,10 @@ public void TestSendSingleEmailWithHelper() output.WriteLine(msg.Serialize()); - Assert.Equal("{\"from\":{\"name\":\"Example User\",\"email\":\"test@example.com\"},\"personalizations\":[{\"to\":[{\"name\":\"Example User\",\"email\":\"test@example.com\"}],\"subject\":\"Sending with Twilio SendGrid is Fun\"}],\"content\":[{\"type\":\"text/plain\",\"value\":\"and easy to do anywhere, even with C#\"},{\"type\":\"text/html\",\"value\":\"\\u003cstrong\\u003eand easy to do anywhere, even with C#\\u003c/strong\\u003e\"}]}", msg.Serialize()); + Assert.Equal("{\"from\":{\"name\":\"Example User\",\"email\":\"test@example.com\"},\"personalizations\":[{\"to\":[{\"name\":\"Example User\",\"email\":\"test@example.com\"}],\"subject\":\"Sending with Twilio SendGrid is Fun\"}],\"content\":[{\"type\":\"text/plain\",\"value\":\"and easy to do anywhere, even with C#\"},{\"type\":\"text/html\",\"value\":\"\\u003Cstrong\\u003Eand easy to do anywhere, even with C#\\u003C/strong\\u003E\"}]}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestSendSingleEmailWithHelperWithOutEmailObject() { var msg = new SendGridMessage(); @@ -83,7 +84,7 @@ public void TestSendSingleEmailWithHelperWithOutEmailObject() } // All paramaters available for sending an email - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestKitchenSink() { TestKitchenSinkInternal(); @@ -346,7 +347,7 @@ private void TestKitchenSinkInternal(bool useDefaultSerialization = true) Assert.Equal(json, msg2.Serialize(useDefaultSerialization)); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestKitchenSinkIsUnaffectedByCustomContractResolver() { var originalGetDefaults = JsonConvert.DefaultSettings; @@ -374,7 +375,7 @@ public void TestKitchenSinkIsUnaffectedByCustomContractResolver() } } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestCreateSingleEmail() { var msg = MailHelper.CreateSingleEmail(new EmailAddress("test@example.com", "Example User"), @@ -414,7 +415,7 @@ public void TestCreateSingleEmail() } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestCreateSingleEmailToMultipleRecipients() { var emails = new List @@ -464,7 +465,7 @@ public void TestCreateSingleEmailToMultipleRecipients() Assert.Equal("{\"from\":{\"name\":\"Example User\",\"email\":\"test@example.com\"},\"subject\":\"Test Subject\",\"personalizations\":[{\"to\":[{\"email\":\"test1@example.com\"}]},{\"to\":[{\"email\":\"test2@example.com\"}]},{\"to\":[{\"email\":\"test3@example.com\"}]}],\"content\":[{\"type\":\"text/plain\",\"value\":\"Plain Text Content\"}]}", msg5.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestCreateSingleEmailToMultipleRecipientsToggleRecipientDisplay() { var emails = new List @@ -523,7 +524,7 @@ public void TestCreateSingleEmailToMultipleRecipientsToggleRecipientDisplay() Assert.Equal("{\"from\":{\"name\":\"Example User\",\"email\":\"test@example.com\"},\"subject\":\"Test Subject\",\"personalizations\":[{\"to\":[{\"email\":\"test1@example.com\"},{\"email\":\"test2@example.com\"},{\"email\":\"test3@example.com\"}]}],\"content\":[{\"type\":\"text/plain\",\"value\":\"Plain Text Content\"},{\"type\":\"text/html\",\"value\":\"HTML Content\"}]}", msg6.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestCreateMultipleEmailsToMultipleRecipients() { var emails = new List @@ -595,7 +596,7 @@ public void TestCreateMultipleEmailsToMultipleRecipients() Assert.Equal("{\"from\":{\"name\":\"Example User\",\"email\":\"test@example.com\"},\"personalizations\":[{\"to\":[{\"email\":\"test1@example.com\"}],\"subject\":\"Test Subject1\",\"substitutions\":{\"-name-\":\"Name1\"}},{\"to\":[{\"email\":\"test2@example.com\"}],\"subject\":\"Test Subject2\",\"substitutions\":{\"-name-\":\"Name1\"}},{\"to\":[{\"email\":\"test3@example.com\"}],\"subject\":\"Test Subject3\",\"substitutions\":{\"-name-\":\"Name1\"}}],\"content\":[{\"type\":\"text/plain\",\"value\":\"Hello -name-\"}]}", msg5.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestAddFrom() { // Personalization not passed in, Personalization does not exist @@ -680,7 +681,7 @@ public void TestAddFrom() "\"from\":{\"name\":\"Example User\",\"email\":\"test010@example.com\"}},{\"to\":[{\"name\":\"Example User\",\"email\":\"test011@example.com\"}]," + "\"from\":{\"name\":\"Example User\",\"email\":\"test012@example.com\"}}]}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestAddTo() { // Personalization not passed in, Personalization does not exist @@ -762,7 +763,7 @@ public void TestAddTo() Assert.Equal("{\"personalizations\":[{\"to\":[{\"name\":\"Example User\",\"email\":\"test009@example.com\"},{\"name\":\"Example User\",\"email\":\"test011@example.com\"}]},{\"to\":[{\"name\":\"Example User\",\"email\":\"test010@example.com\"}]}]}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestAddToWithOutEmailAddressObject() { var msg = new SendGridMessage(); @@ -775,21 +776,21 @@ public void TestAddToWithOutEmailAddressObject() } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestAddToArgumentNullExceptionIfNullEmailAddressIsSupplied() { var msg = new SendGridMessage(); Assert.Throws(() => msg.AddTo(null, "Example User")); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestAddToArgumentNullExceptionIfNoEmailAddressIsSupplied() { var msg = new SendGridMessage(); Assert.Throws(() => msg.AddTo(string.Empty, "Example User")); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestAddTos() { // Personalization not passed in, Personalization does not exist @@ -901,7 +902,7 @@ public void TestAddTos() Assert.Equal("{\"personalizations\":[{\"to\":[{\"name\":\"Example User\",\"email\":\"test028@example.com\"},{\"name\":\"Example User\",\"email\":\"test029@example.com\"},{\"name\":\"Example User\",\"email\":\"test032@example.com\"},{\"name\":\"Example User\",\"email\":\"test033@example.com\"}]},{\"to\":[{\"name\":\"Example User\",\"email\":\"test030@example.com\"},{\"name\":\"Example User\",\"email\":\"test031@example.com\"}]}]}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestAddCcWithoutEmailAddressObject() { var msg = new SendGridMessage(); @@ -913,21 +914,21 @@ public void TestAddCcWithoutEmailAddressObject() Assert.Equal("{\"personalizations\":[{\"cc\":[{\"email\":\"test001@example.com\"}]}]}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestAddCcArgumentNullExceptionIfNullEmailAddressIsSupplied() { var msg = new SendGridMessage(); Assert.Throws(() => msg.AddCc(null, "Example User")); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestAddCcArgumentNullExceptionIfEmptyEmailAddressIsSupplied() { var msg = new SendGridMessage(); Assert.Throws(() => msg.AddCc(string.Empty, "Example User")); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestAddCc() { // Personalization not passed in, Personalization does not exist @@ -1009,7 +1010,7 @@ public void TestAddCc() Assert.Equal("{\"personalizations\":[{\"cc\":[{\"name\":\"Example User\",\"email\":\"test009@example.com\"},{\"name\":\"Example User\",\"email\":\"test011@example.com\"}]},{\"cc\":[{\"name\":\"Example User\",\"email\":\"test010@example.com\"}]}]}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestAddCcs() { // Personalization not passed in, Personalization does not exist @@ -1121,7 +1122,7 @@ public void TestAddCcs() Assert.Equal("{\"personalizations\":[{\"cc\":[{\"name\":\"Example User\",\"email\":\"test028@example.com\"},{\"name\":\"Example User\",\"email\":\"test029@example.com\"},{\"name\":\"Example User\",\"email\":\"test032@example.com\"},{\"name\":\"Example User\",\"email\":\"test033@example.com\"}]},{\"cc\":[{\"name\":\"Example User\",\"email\":\"test030@example.com\"},{\"name\":\"Example User\",\"email\":\"test031@example.com\"}]}]}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestAddBcc() { // Personalization not passed in, Personalization does not exist @@ -1203,7 +1204,7 @@ public void TestAddBcc() Assert.Equal("{\"personalizations\":[{\"bcc\":[{\"name\":\"Example User\",\"email\":\"test009@example.com\"},{\"name\":\"Example User\",\"email\":\"test011@example.com\"}]},{\"bcc\":[{\"name\":\"Example User\",\"email\":\"test010@example.com\"}]}]}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestAddBccWithOutEmailAddressObject() { var msg = new SendGridMessage(); @@ -1215,21 +1216,21 @@ public void TestAddBccWithOutEmailAddressObject() Assert.Equal("{\"personalizations\":[{\"bcc\":[{\"email\":\"test001@example.com\"}]}]}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestAddBccArgumentNullExceptionIfNullEmailAddressIsSupplied() { var msg = new SendGridMessage(); Assert.Throws(() => msg.AddBcc(null, "Example User")); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestAddBccArgumentNullExceptionIfEmptyEmailAddressIsSupplied() { var msg = new SendGridMessage(); Assert.Throws(() => msg.AddBcc(string.Empty, "Example User")); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestAddBccs() { // Personalization not passed in, Personalization does not exist @@ -1341,7 +1342,7 @@ public void TestAddBccs() Assert.Equal("{\"personalizations\":[{\"bcc\":[{\"name\":\"Example User\",\"email\":\"test028@example.com\"},{\"name\":\"Example User\",\"email\":\"test029@example.com\"},{\"name\":\"Example User\",\"email\":\"test032@example.com\"},{\"name\":\"Example User\",\"email\":\"test033@example.com\"}]},{\"bcc\":[{\"name\":\"Example User\",\"email\":\"test030@example.com\"},{\"name\":\"Example User\",\"email\":\"test031@example.com\"}]}]}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestAddDuplicateEmails() { var msg = new SendGridMessage(); @@ -1356,7 +1357,7 @@ public void TestAddDuplicateEmails() Assert.Equal("{\"personalizations\":[{\"to\":[{\"name\":\"example user\",\"email\":\"user1@example.com\"}],\"cc\":[{\"name\":\"example user\",\"email\":\"user1@example.com\"}],\"bcc\":[{\"name\":\"example user\",\"email\":\"user1@example.com\"}]}]}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestSetSubject() { // Personalization not passed in, Personalization does not exist @@ -1419,7 +1420,7 @@ public void TestSetSubject() Assert.Equal("{\"personalizations\":[{\"subject\":\"subject11\"},{\"subject\":\"subject10\"}]}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestAddHeader() { // Personalization not passed in, Personalization does not exist @@ -1506,7 +1507,7 @@ public void TestAddHeader() Assert.Equal("{\"personalizations\":[{\"headers\":{\"X-Test8\":\"Test Value 8\",\"X-Test10\":\"Test Value 10\"}},{\"headers\":{\"X-Test9\":\"Test Value 9\"}}]}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestAddHeaders() { // Personalization not passed in, Personalization does not exist @@ -1574,7 +1575,7 @@ public void TestAddHeaders() Assert.Equal("{\"personalizations\":[{\"headers\":{\"X-Test17\":\"Test Value 17\",\"X-Test18\":\"Test Value 18\",\"X-Test21\":\"Test Value 21\",\"X-Test22\":\"Test Value 22\"}},{\"headers\":{\"X-Test19\":\"Test Value 19\",\"X-Test20\":\"Test Value 20\"}}]}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestAddSubstitution() { // Personalization not passed in, Personalization does not exist @@ -1661,7 +1662,7 @@ public void TestAddSubstitution() Assert.Equal("{\"personalizations\":[{\"substitutions\":{\"-sub9-\":\"Substituted Value 9\",\"-sub11-\":\"Substituted Value 11\"}},{\"substitutions\":{\"-sub10-\":\"Substituted Value 10\"}}]}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestAddSubstitutions() { // Personalization not passed in, Personalization does not exist @@ -1773,7 +1774,7 @@ public void TestAddSubstitutions() Assert.Equal("{\"personalizations\":[{\"substitutions\":{\"-sub28-\":\"Substituted Value 28\",\"-sub29-\":\"Substituted Value 29\",\"-sub32-\":\"Substituted Value 32\",\"-sub33-\":\"Substituted Value 33\"}},{\"substitutions\":{\"-sub30-\":\"Substituted Value 30\",\"-sub31-\":\"Substituted Value 31\"}}]}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestSetTemplateData() { // Personalization not passed in, Personalization does not exist @@ -1902,7 +1903,7 @@ public void TestSetTemplateData() Assert.Equal("{\"personalizations\":[{\"dynamic_template_data\":{\"array\":[\"Dynamic Template Data Array Value 1\",\"Dynamic Template Data Array Value 2\"],\"innerObject\":{\"innerObjectKey1\":\"Dynamic Template Data Deep Object Value 1\"}}}]}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestAddCustomArg() { // Personalization not passed in, Personalization does not exist @@ -1989,7 +1990,7 @@ public void TestAddCustomArg() Assert.Equal("{\"personalizations\":[{\"custom_args\":{\"arg9\":\"Arguement Value 9\",\"arg11\":\"Arguement Value 11\"}},{\"custom_args\":{\"arg10\":\"Arguement Value 10\"}}]}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestAddCustomArgs() { // Personalization not passed in, Personalization does not exist @@ -2101,7 +2102,7 @@ public void TestAddCustomArgs() Assert.Equal("{\"personalizations\":[{\"custom_args\":{\"arg28\":\"Arguement Value 28\",\"arg29\":\"Arguement Value 29\",\"arg32\":\"Arguement Value 32\",\"arg33\":\"Arguement Value 33\"}},{\"custom_args\":{\"arg30\":\"Arguement Value 30\",\"arg31\":\"Arguement Value 31\"}}]}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestSendAt() { // Personalization not passed in, Personalization does not exist @@ -2164,7 +2165,7 @@ public void TestSendAt() Assert.Equal("{\"personalizations\":[{\"send_at\":1409348513},{\"send_at\":1409348513}]}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestSetFrom() { var msg = new SendGridMessage(); @@ -2177,14 +2178,14 @@ public void TestSetFrom() Assert.Equal("{\"from\":{\"name\":\"Test User1\",\"email\":\"test1@example.com\"}}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestSetFromArgumentNullExceptionIfNullEmailAddressIsSupplied() { var msg = new SendGridMessage(); Assert.Throws(() => msg.SetFrom(null, "Example User")); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestSetFromArgumentEmptyExceptionIfEmptyEmailAddressIsSupplied() { var msg = new SendGridMessage(); @@ -2192,7 +2193,7 @@ public void TestSetFromArgumentEmptyExceptionIfEmptyEmailAddressIsSupplied() } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestSetFromWithOutEmailAddressObject() { var msg = new SendGridMessage(); @@ -2204,7 +2205,7 @@ public void TestSetFromWithOutEmailAddressObject() Assert.Equal("{\"from\":{\"email\":\"test1@example.com\"}}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestSetReplyTo() { var msg = new SendGridMessage(); @@ -2217,7 +2218,7 @@ public void TestSetReplyTo() Assert.Equal("{\"reply_to\":{\"name\":\"Test User2\",\"email\":\"test2@example.com\"}}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestAddReplyTos() { var msg = new SendGridMessage(); @@ -2234,7 +2235,7 @@ public void TestAddReplyTos() Assert.Equal("{\"reply_to_list\":[{\"email\":\"test1@example.com\"},{\"name\":\"Test User2\",\"email\":\"test2@example.com\"}]}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestSetGlobalSubject() { var msg = new SendGridMessage(); @@ -2243,7 +2244,7 @@ public void TestSetGlobalSubject() Assert.Equal("{\"subject\":\"subject1\"}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestAddContent() { //Content object does not exist @@ -2280,7 +2281,7 @@ public void TestAddContent() Assert.Equal("{\"content\":[{\"type\":\"text/plain\",\"value\":\"content6\"},{\"type\":\"text/html\",\"value\":\"content3\"}]}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestAddContents() { //Content object does not exist @@ -2355,7 +2356,7 @@ public void TestAddContents() Assert.Equal("{\"content\":[{\"type\":\"text/plain\",\"value\":\"content9\"},{\"type\":\"text/html\",\"value\":\"content7\"},{\"type\":\"fake/mimetype\",\"value\":\"content8\"}]}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestAddAttachment() { //Attachment object does not exist @@ -2378,7 +2379,7 @@ public void TestAddAttachment() Assert.Equal("{\"attachments\":[{\"content\":\"base64content2\",\"type\":\"jpg\",\"filename\":\"filename2\",\"disposition\":\"inline\",\"content_id\":\"id2\"},{\"content\":\"base64content3\",\"type\":\"jpg\",\"filename\":\"filename3\",\"disposition\":\"inline\",\"content_id\":\"id3\"}]}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestAddAttachments() { //Attachment object does not exist @@ -2439,7 +2440,7 @@ public void TestAddAttachments() Assert.Equal("{\"attachments\":[{\"content\":\"base64content6\",\"type\":\"jpg\",\"filename\":\"filename6\",\"disposition\":\"inline\",\"content_id\":\"id6\"},{\"content\":\"base64content7\",\"type\":\"jpg\",\"filename\":\"filename7\",\"disposition\":\"inline\",\"content_id\":\"id7\"},{\"content\":\"base64content8\",\"type\":\"jpg\",\"filename\":\"filename8\",\"disposition\":\"inline\",\"content_id\":\"id8\"}]}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestSetTemplateId() { var msg = new SendGridMessage(); @@ -2447,7 +2448,7 @@ public void TestSetTemplateId() Assert.Equal("{\"template_id\":\"template_id1\"}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestAddSection() { // Section object does not exist @@ -2460,7 +2461,7 @@ public void TestAddSection() Assert.Equal("{\"sections\":{\"section_key1\":\"section_value1\",\"section_key2\":\"section_value2\"}}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestAddSections() { // Section object does not exist @@ -2483,7 +2484,7 @@ public void TestAddSections() Assert.Equal("{\"sections\":{\"section_key3\":\"section_value3\",\"section_key4\":\"section_value4\",\"section_key5\":\"section_value5\",\"section_key6\":\"section_value6\"}}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestAddGlobalHeader() { // Header object does not exist @@ -2496,7 +2497,7 @@ public void TestAddGlobalHeader() Assert.Equal("{\"headers\":{\"X-Header1\":\"Value1\",\"X-Header2\":\"Value2\"}}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestAddGlobalHeaders() { // Header object does not exist @@ -2519,7 +2520,7 @@ public void TestAddGlobalHeaders() Assert.Equal("{\"headers\":{\"X-Header3\":\"Value3\",\"X-Header4\":\"Value4\",\"X-Header5\":\"Value5\",\"X-Header6\":\"Value6\"}}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestAddCategory() { //Categories object does not exist @@ -2536,7 +2537,7 @@ public void TestAddCategory() Assert.Equal("{\"categories\":[\"category3\",\"category4\"]}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestAddCategories() { //Categories object does not exist @@ -2552,7 +2553,7 @@ public void TestAddCategories() Assert.Equal("{\"categories\":[\"category7\",\"category8\",\"category9\",\"category10\"]}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestAddGlobalCustomArg() { // CustomArgs object does not exist @@ -2565,7 +2566,7 @@ public void TestAddGlobalCustomArg() Assert.Equal("{\"custom_args\":{\"Key1\":\"Value1\",\"Key2\":\"Value2\"}}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestAddGlobalCustomArgs() { // CustomArgs object does not exist @@ -2588,7 +2589,7 @@ public void TestAddGlobalCustomArgs() Assert.Equal("{\"custom_args\":{\"Key3\":\"Value3\",\"Key4\":\"Value4\",\"Key5\":\"Value5\",\"Key6\":\"Value6\"}}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestSetGlobalSendAt() { var msg = new SendGridMessage(); @@ -2596,7 +2597,7 @@ public void TestSetGlobalSendAt() Assert.Equal("{\"send_at\":1409348513}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestSetBatchId() { var msg = new SendGridMessage(); @@ -2604,7 +2605,7 @@ public void TestSetBatchId() Assert.Equal("{\"batch_id\":\"batch_id\"}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestSetAsm() { var msg = new SendGridMessage(); @@ -2616,7 +2617,7 @@ public void TestSetAsm() Assert.Equal("{\"asm\":{\"group_id\":1,\"groups_to_display\":[1,2,3,4,5]}}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestSetIpPoolName() { var msg = new SendGridMessage(); @@ -2624,7 +2625,7 @@ public void TestSetIpPoolName() Assert.Equal("{\"ip_pool_name\":\"pool_name\"}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestSetBccSetting() { //MailSettings object does not exist @@ -2647,7 +2648,7 @@ public void TestSetBccSetting() Assert.Equal("{\"mail_settings\":{\"bcc\":{\"enable\":true,\"email\":\"test3@example.com\"}}}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestSetBypassListManagement() { //MailSettings object does not exist @@ -2669,7 +2670,7 @@ public void TestSetBypassListManagement() Assert.Equal("{\"mail_settings\":{\"bypass_list_management\":{\"enable\":true}}}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestSetBypassSpamManagement() { //MailSettings object does not exist @@ -2691,7 +2692,7 @@ public void TestSetBypassSpamManagement() Assert.Equal("{\"mail_settings\":{\"bypass_spam_management\":{\"enable\":true}}}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestSetBypassBounceManagement() { //MailSettings object does not exist @@ -2713,7 +2714,7 @@ public void TestSetBypassBounceManagement() Assert.Equal("{\"mail_settings\":{\"bypass_bounce_management\":{\"enable\":true}}}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestSetBypassUnsubscribeManagement() { //MailSettings object does not exist @@ -2735,7 +2736,7 @@ public void TestSetBypassUnsubscribeManagement() Assert.Equal("{\"mail_settings\":{\"bypass_unsubscribe_management\":{\"enable\":true}}}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestSetFooterSetting() { //MailSettings object does not exist @@ -2759,7 +2760,7 @@ public void TestSetFooterSetting() Assert.Equal("{\"mail_settings\":{\"footer\":{\"enable\":true,\"text\":\"text3\",\"html\":\"html3\"}}}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestSetSandBoxMode() { //MailSettings object does not exist @@ -2781,7 +2782,7 @@ public void TestSetSandBoxMode() Assert.Equal("{\"mail_settings\":{\"sandbox_mode\":{\"enable\":true}}}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestSetSpamCheck() { //MailSettings object does not exist @@ -2805,7 +2806,7 @@ public void TestSetSpamCheck() Assert.Equal("{\"mail_settings\":{\"spam_check\":{\"enable\":true,\"threshold\":2,\"post_to_url\":\"http://fakeurl2.com\"}}}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestSetClickTracking() { //TrackingSettings object does not exist @@ -2828,7 +2829,7 @@ public void TestSetClickTracking() Assert.Equal("{\"tracking_settings\":{\"click_tracking\":{\"enable\":true,\"enable_text\":true}}}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestSetOpenTracking() { //TrackingSettings object does not exist @@ -2851,7 +2852,7 @@ public void TestSetOpenTracking() Assert.Equal("{\"tracking_settings\":{\"open_tracking\":{\"enable\":false,\"substitution_tag\":\"subtag3\"}}}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestSetSubscriptionTracking() { //TrackingSettings object does not exist @@ -2876,7 +2877,7 @@ public void TestSetSubscriptionTracking() Assert.Equal("{\"tracking_settings\":{\"subscription_tracking\":{\"enable\":true,\"text\":\"text3\",\"html\":\"html3\",\"substitution_tag\":\"sub3\"}}}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestSetGoogleAnalytics() { //TrackingSettings object does not exist @@ -2903,7 +2904,7 @@ public void TestSetGoogleAnalytics() Assert.Equal("{\"tracking_settings\":{\"ganalytics\":{\"enable\":true,\"utm_source\":\"source3\",\"utm_medium\":\"medium3\",\"utm_term\":\"term3\",\"utm_content\":\"content3\",\"utm_campaign\":\"campaign3\"}}}", msg.Serialize()); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestAccessSettingsActivityGet() { var sg = GetClient("200"); @@ -2914,7 +2915,7 @@ public async Task TestAccessSettingsActivityGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestAccessSettingsWhitelistPost() { var sg = GetClient("201"); @@ -2937,7 +2938,7 @@ public async Task TestAccessSettingsWhitelistPost() Assert.Equal(HttpStatusCode.Created, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestAccessSettingsWhitelistGet() { var sg = GetClient("200"); @@ -2945,7 +2946,7 @@ public async Task TestAccessSettingsWhitelistGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestAccessSettingsWhitelistDelete() { var sg = GetClient("204"); @@ -2962,7 +2963,7 @@ public async Task TestAccessSettingsWhitelistDelete() Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestAccessSettingsWhitelistRuleIdGet() { var sg = GetClient("200"); @@ -2971,7 +2972,7 @@ public async Task TestAccessSettingsWhitelistRuleIdGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestAccessSettingsWhitelistRuleIdDelete() { var sg = GetClient("204"); @@ -2980,7 +2981,7 @@ public async Task TestAccessSettingsWhitelistRuleIdDelete() Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestAlertsPost() { var sg = GetClient("201"); @@ -2995,7 +2996,7 @@ public async Task TestAlertsPost() Assert.Equal(HttpStatusCode.Created, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestAlertsGet() { var sg = GetClient("200"); @@ -3003,7 +3004,7 @@ public async Task TestAlertsGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestAlertsAlertIdPatch() { var sg = GetClient("200"); @@ -3017,7 +3018,7 @@ public async Task TestAlertsAlertIdPatch() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestAlertsAlertIdGet() { var sg = GetClient("200"); @@ -3026,7 +3027,7 @@ public async Task TestAlertsAlertIdGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestAlertsAlertIdDelete() { var sg = GetClient("204"); @@ -3035,7 +3036,7 @@ public async Task TestAlertsAlertIdDelete() Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestApiKeysPost() { var sg = GetClient("201"); @@ -3054,7 +3055,7 @@ public async Task TestApiKeysPost() Assert.Equal(HttpStatusCode.Created, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestApiKeysGet() { var sg = GetClient("200"); @@ -3065,7 +3066,7 @@ public async Task TestApiKeysGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestApiKeysApiKeyIdPut() { var sg = GetClient("200"); @@ -3083,7 +3084,7 @@ public async Task TestApiKeysApiKeyIdPut() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestApiKeysApiKeyIdPatch() { var sg = GetClient("200"); @@ -3097,7 +3098,7 @@ public async Task TestApiKeysApiKeyIdPatch() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestApiKeysApiKeyIdGet() { var sg = GetClient("200"); @@ -3106,7 +3107,7 @@ public async Task TestApiKeysApiKeyIdGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestApiKeysApiKeyIdDelete() { var sg = GetClient("204"); @@ -3115,7 +3116,7 @@ public async Task TestApiKeysApiKeyIdDelete() Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestAsmGroupsPost() { var sg = GetClient("201"); @@ -3130,7 +3131,7 @@ public async Task TestAsmGroupsPost() Assert.Equal(HttpStatusCode.Created, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestAsmGroupsGet() { var sg = GetClient("200"); @@ -3141,7 +3142,7 @@ public async Task TestAsmGroupsGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestAsmGroupsGroupIdPatch() { var sg = GetClient("201"); @@ -3157,7 +3158,7 @@ public async Task TestAsmGroupsGroupIdPatch() Assert.Equal(HttpStatusCode.Created, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestAsmGroupsGroupIdGet() { var sg = GetClient("200"); @@ -3166,7 +3167,7 @@ public async Task TestAsmGroupsGroupIdGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestAsmGroupsGroupIdDelete() { var sg = GetClient("204"); @@ -3175,7 +3176,7 @@ public async Task TestAsmGroupsGroupIdDelete() Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestAsmGroupsGroupIdSuppressionsPost() { var sg = GetClient("201"); @@ -3192,7 +3193,7 @@ public async Task TestAsmGroupsGroupIdSuppressionsPost() Assert.Equal(HttpStatusCode.Created, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestAsmGroupsGroupIdSuppressionsGet() { var sg = GetClient("200"); @@ -3201,7 +3202,7 @@ public async Task TestAsmGroupsGroupIdSuppressionsGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestAsmGroupsGroupIdSuppressionsSearchPost() { var sg = GetClient("200"); @@ -3219,7 +3220,7 @@ public async Task TestAsmGroupsGroupIdSuppressionsSearchPost() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestAsmGroupsGroupIdSuppressionsEmailDelete() { var sg = GetClient("204"); @@ -3229,7 +3230,7 @@ public async Task TestAsmGroupsGroupIdSuppressionsEmailDelete() Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestAsmSuppressionsGet() { var sg = GetClient("200"); @@ -3237,7 +3238,7 @@ public async Task TestAsmSuppressionsGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestAsmSuppressionsGlobalPost() { var sg = GetClient("201"); @@ -3253,7 +3254,7 @@ public async Task TestAsmSuppressionsGlobalPost() Assert.Equal(HttpStatusCode.Created, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestAsmSuppressionsGlobalEmailGet() { var sg = GetClient("200"); @@ -3262,7 +3263,7 @@ public async Task TestAsmSuppressionsGlobalEmailGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestAsmSuppressionsGlobalEmailDelete() { var sg = GetClient("204"); @@ -3271,7 +3272,7 @@ public async Task TestAsmSuppressionsGlobalEmailDelete() Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestAsmSuppressionsEmailGet() { var sg = GetClient("200"); @@ -3280,7 +3281,7 @@ public async Task TestAsmSuppressionsEmailGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestBrowsersStatsGet() { var sg = GetClient("200"); @@ -3296,7 +3297,7 @@ public async Task TestBrowsersStatsGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestCampaignsPost() { var sg = GetClient("201"); @@ -3326,7 +3327,7 @@ public async Task TestCampaignsPost() Assert.Equal(HttpStatusCode.Created, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestCampaignsGet() { var sg = GetClient("200"); @@ -3338,7 +3339,7 @@ public async Task TestCampaignsGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestCampaignsCampaignIdPatch() { var sg = GetClient("200"); @@ -3358,7 +3359,7 @@ public async Task TestCampaignsCampaignIdPatch() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestCampaignsCampaignIdGet() { var sg = GetClient("200"); @@ -3367,7 +3368,7 @@ public async Task TestCampaignsCampaignIdGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestCampaignsCampaignIdDelete() { var sg = GetClient("204"); @@ -3376,7 +3377,7 @@ public async Task TestCampaignsCampaignIdDelete() Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestCampaignsCampaignIdSchedulesPatch() { var sg = GetClient("200"); @@ -3390,7 +3391,7 @@ public async Task TestCampaignsCampaignIdSchedulesPatch() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestCampaignsCampaignIdSchedulesPost() { var sg = GetClient("201"); @@ -3404,7 +3405,7 @@ public async Task TestCampaignsCampaignIdSchedulesPost() Assert.Equal(HttpStatusCode.Created, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestCampaignsCampaignIdSchedulesGet() { var sg = GetClient("200"); @@ -3413,7 +3414,7 @@ public async Task TestCampaignsCampaignIdSchedulesGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestCampaignsCampaignIdSchedulesDelete() { var sg = GetClient("204"); @@ -3422,7 +3423,7 @@ public async Task TestCampaignsCampaignIdSchedulesDelete() Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestCampaignsCampaignIdSchedulesNowPost() { var sg = GetClient("201"); @@ -3431,7 +3432,7 @@ public async Task TestCampaignsCampaignIdSchedulesNowPost() Assert.Equal(HttpStatusCode.Created, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestCampaignsCampaignIdSchedulesTestPost() { var sg = GetClient("204"); @@ -3445,7 +3446,7 @@ public async Task TestCampaignsCampaignIdSchedulesTestPost() Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestCategoriesGet() { var sg = GetClient("200"); @@ -3458,7 +3459,7 @@ public async Task TestCategoriesGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestCategoriesStatsGet() { var sg = GetClient("200"); @@ -3474,7 +3475,7 @@ public async Task TestCategoriesStatsGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestCategoriesStatsSumsGet() { var sg = GetClient("200"); @@ -3491,7 +3492,7 @@ public async Task TestCategoriesStatsSumsGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestClientsStatsGet() { var sg = GetClient("200"); @@ -3504,7 +3505,7 @@ public async Task TestClientsStatsGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestClientsClientTypeStatsGet() { var sg = GetClient("200"); @@ -3518,7 +3519,7 @@ public async Task TestClientsClientTypeStatsGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestContactdbCustomFieldsPost() { var sg = GetClient("201"); @@ -3532,7 +3533,7 @@ public async Task TestContactdbCustomFieldsPost() Assert.Equal(HttpStatusCode.Created, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestContactdbCustomFieldsGet() { var sg = GetClient("200"); @@ -3540,7 +3541,7 @@ public async Task TestContactdbCustomFieldsGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestContactdbCustomFieldsCustomFieldIdGet() { var sg = GetClient("200"); @@ -3549,7 +3550,7 @@ public async Task TestContactdbCustomFieldsCustomFieldIdGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestContactdbCustomFieldsCustomFieldIdDelete() { var sg = GetClient("202"); @@ -3558,7 +3559,7 @@ public async Task TestContactdbCustomFieldsCustomFieldIdDelete() Assert.Equal(HttpStatusCode.Accepted, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestContactdbListsPost() { @@ -3572,7 +3573,7 @@ public async Task TestContactdbListsPost() Assert.Equal(HttpStatusCode.Created, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestContactdbListsGet() { var sg = GetClient("200"); @@ -3580,7 +3581,7 @@ public async Task TestContactdbListsGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestContactdbListsDelete() { var sg = GetClient("204"); @@ -3596,7 +3597,7 @@ public async Task TestContactdbListsDelete() Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestContactdbListsListIdPatch() { var sg = GetClient("200"); @@ -3613,7 +3614,7 @@ public async Task TestContactdbListsListIdPatch() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestContactdbListsListIdGet() { var sg = GetClient("200"); @@ -3625,7 +3626,7 @@ public async Task TestContactdbListsListIdGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestContactdbListsListIdDelete() { var sg = GetClient("202"); @@ -3637,7 +3638,7 @@ public async Task TestContactdbListsListIdDelete() Assert.Equal(HttpStatusCode.Accepted, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestContactdbListsListIdRecipientsPost() { var sg = GetClient("201"); @@ -3652,7 +3653,7 @@ public async Task TestContactdbListsListIdRecipientsPost() Assert.Equal(HttpStatusCode.Created, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestContactdbListsListIdRecipientsGet() { var sg = GetClient("200"); @@ -3666,7 +3667,7 @@ public async Task TestContactdbListsListIdRecipientsGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestContactdbListsListIdRecipientsRecipientIdPost() { var sg = GetClient("201"); @@ -3676,7 +3677,7 @@ public async Task TestContactdbListsListIdRecipientsRecipientIdPost() Assert.Equal(HttpStatusCode.Created, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestContactdbListsListIdRecipientsRecipientIdDelete() { var sg = GetClient("204"); @@ -3690,7 +3691,7 @@ public async Task TestContactdbListsListIdRecipientsRecipientIdDelete() Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestContactdbRecipientsPatch() { var sg = GetClient("201"); @@ -3707,7 +3708,7 @@ public async Task TestContactdbRecipientsPatch() Assert.Equal(HttpStatusCode.Created, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestContactdbRecipientsPost() { var sg = GetClient("201"); @@ -3731,7 +3732,7 @@ public async Task TestContactdbRecipientsPost() Assert.Equal(HttpStatusCode.Created, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestContactdbRecipientsGet() { var sg = GetClient("200"); @@ -3743,7 +3744,7 @@ public async Task TestContactdbRecipientsGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestContactdbRecipientsDelete() { var sg = GetClient("200"); @@ -3757,7 +3758,7 @@ public async Task TestContactdbRecipientsDelete() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestContactdbRecipientsBillableCountGet() { var sg = GetClient("200"); @@ -3765,7 +3766,7 @@ public async Task TestContactdbRecipientsBillableCountGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestContactdbRecipientsCountGet() { var sg = GetClient("200"); @@ -3773,7 +3774,7 @@ public async Task TestContactdbRecipientsCountGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestContactdbRecipientsSearchGet() { var sg = GetClient("200"); @@ -3784,7 +3785,7 @@ public async Task TestContactdbRecipientsSearchGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestContactdbRecipientsRecipientIdGet() { var sg = GetClient("200"); @@ -3793,7 +3794,7 @@ public async Task TestContactdbRecipientsRecipientIdGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestContactdbRecipientsRecipientIdDelete() { var sg = GetClient("204"); @@ -3802,7 +3803,7 @@ public async Task TestContactdbRecipientsRecipientIdDelete() Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestContactdbRecipientsRecipientIdListsGet() { var sg = GetClient("200"); @@ -3811,7 +3812,7 @@ public async Task TestContactdbRecipientsRecipientIdListsGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestContactdbReservedFieldsGet() { var sg = GetClient("200"); @@ -3819,7 +3820,7 @@ public async Task TestContactdbReservedFieldsGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestContactdbSegmentsPost() { var sg = GetClient("200"); @@ -3853,7 +3854,7 @@ public async Task TestContactdbSegmentsPost() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestContactdbSegmentsGet() { var sg = GetClient("200"); @@ -3861,7 +3862,7 @@ public async Task TestContactdbSegmentsGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestContactdbSegmentsSegmentIdPatch() { var sg = GetClient("200"); @@ -3887,7 +3888,7 @@ public async Task TestContactdbSegmentsSegmentIdPatch() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestContactdbSegmentsSegmentIdGet() { var sg = GetClient("200"); @@ -3899,7 +3900,7 @@ public async Task TestContactdbSegmentsSegmentIdGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestContactdbSegmentsSegmentIdDelete() { var sg = GetClient("204"); @@ -3911,7 +3912,7 @@ public async Task TestContactdbSegmentsSegmentIdDelete() Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestContactdbSegmentsSegmentIdRecipientsGet() { var sg = GetClient("200"); @@ -3924,7 +3925,7 @@ public async Task TestContactdbSegmentsSegmentIdRecipientsGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestDevicesStatsGet() { var sg = GetClient("200"); @@ -3939,7 +3940,7 @@ public async Task TestDevicesStatsGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestGeoStatsGet() { var sg = GetClient("200"); @@ -3955,7 +3956,7 @@ public async Task TestGeoStatsGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestIpsGet() { var sg = GetClient("200"); @@ -3970,7 +3971,7 @@ public async Task TestIpsGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestIpsAssignedGet() { var sg = GetClient("200"); @@ -3978,7 +3979,7 @@ public async Task TestIpsAssignedGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestIpsPoolsPost() { var sg = GetClient("200"); @@ -3991,7 +3992,7 @@ public async Task TestIpsPoolsPost() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestIpsPoolsGet() { var sg = GetClient("200"); @@ -3999,7 +4000,7 @@ public async Task TestIpsPoolsGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestIpsPoolsPoolNamePut() { var sg = GetClient("200"); @@ -4013,7 +4014,7 @@ public async Task TestIpsPoolsPoolNamePut() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestIpsPoolsPoolNameGet() { var sg = GetClient("200"); @@ -4022,7 +4023,7 @@ public async Task TestIpsPoolsPoolNameGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestIpsPoolsPoolNameDelete() { var sg = GetClient("204"); @@ -4031,7 +4032,7 @@ public async Task TestIpsPoolsPoolNameDelete() Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestIpsPoolsPoolNameIpsPost() { var sg = GetClient("201"); @@ -4045,7 +4046,7 @@ public async Task TestIpsPoolsPoolNameIpsPost() Assert.Equal(HttpStatusCode.Created, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestIpsPoolsPoolNameIpsIpDelete() { var sg = GetClient("204"); @@ -4055,7 +4056,7 @@ public async Task TestIpsPoolsPoolNameIpsIpDelete() Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestIpsWarmupPost() { var sg = GetClient("200"); @@ -4068,7 +4069,7 @@ public async Task TestIpsWarmupPost() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestIpsWarmupGet() { var sg = GetClient("200"); @@ -4076,7 +4077,7 @@ public async Task TestIpsWarmupGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestIpsWarmupIpAddressGet() { var sg = GetClient("200"); @@ -4085,7 +4086,7 @@ public async Task TestIpsWarmupIpAddressGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestIpsWarmupIpAddressDelete() { var sg = GetClient("204"); @@ -4094,7 +4095,7 @@ public async Task TestIpsWarmupIpAddressDelete() Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestIpsIpAddressGet() { var sg = GetClient("200"); @@ -4103,7 +4104,7 @@ public async Task TestIpsIpAddressGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestMailBatchPost() { var sg = GetClient("201"); @@ -4111,7 +4112,7 @@ public async Task TestMailBatchPost() Assert.Equal(HttpStatusCode.Created, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestMailBatchBatchIdGet() { var sg = GetClient("200"); @@ -4120,7 +4121,7 @@ public async Task TestMailBatchBatchIdGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestMailSendPost() { var sg = GetClient("202"); @@ -4268,7 +4269,7 @@ public async Task TestMailSendPost() Assert.Equal(HttpStatusCode.Accepted, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestMailSettingsGet() { var sg = GetClient("200"); @@ -4280,7 +4281,7 @@ public async Task TestMailSettingsGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestMailSettingsAddressWhitelistPatch() { var sg = GetClient("200"); @@ -4297,7 +4298,7 @@ public async Task TestMailSettingsAddressWhitelistPatch() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestMailSettingsAddressWhitelistGet() { var sg = GetClient("200"); @@ -4305,7 +4306,7 @@ public async Task TestMailSettingsAddressWhitelistGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestMailSettingsBccPatch() { var sg = GetClient("200"); @@ -4319,7 +4320,7 @@ public async Task TestMailSettingsBccPatch() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestMailSettingsBccGet() { var sg = GetClient("200"); @@ -4327,7 +4328,7 @@ public async Task TestMailSettingsBccGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestMailSettingsBouncePurgePatch() { var sg = GetClient("200"); @@ -4342,7 +4343,7 @@ public async Task TestMailSettingsBouncePurgePatch() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestMailSettingsBouncePurgeGet() { var sg = GetClient("200"); @@ -4350,7 +4351,7 @@ public async Task TestMailSettingsBouncePurgeGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestMailSettingsFooterPatch() { var sg = GetClient("200"); @@ -4365,7 +4366,7 @@ public async Task TestMailSettingsFooterPatch() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestMailSettingsFooterGet() { var sg = GetClient("200"); @@ -4373,7 +4374,7 @@ public async Task TestMailSettingsFooterGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestMailSettingsForwardBouncePatch() { var sg = GetClient("200"); @@ -4387,7 +4388,7 @@ public async Task TestMailSettingsForwardBouncePatch() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestMailSettingsForwardBounceGet() { var sg = GetClient("200"); @@ -4395,7 +4396,7 @@ public async Task TestMailSettingsForwardBounceGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestMailSettingsForwardSpamPatch() { var sg = GetClient("200"); @@ -4409,7 +4410,7 @@ public async Task TestMailSettingsForwardSpamPatch() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestMailSettingsForwardSpamGet() { var sg = GetClient("200"); @@ -4417,7 +4418,7 @@ public async Task TestMailSettingsForwardSpamGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestMailSettingsPlainContentPatch() { var sg = GetClient("200"); @@ -4430,7 +4431,7 @@ public async Task TestMailSettingsPlainContentPatch() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestMailSettingsPlainContentGet() { var sg = GetClient("200"); @@ -4438,7 +4439,7 @@ public async Task TestMailSettingsPlainContentGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestMailSettingsSpamCheckPatch() { var sg = GetClient("200"); @@ -4453,7 +4454,7 @@ public async Task TestMailSettingsSpamCheckPatch() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestMailSettingsSpamCheckGet() { var sg = GetClient("200"); @@ -4461,7 +4462,7 @@ public async Task TestMailSettingsSpamCheckGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestMailSettingsTemplatePatch() { var sg = GetClient("200"); @@ -4475,7 +4476,7 @@ public async Task TestMailSettingsTemplatePatch() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestMailSettingsTemplateGet() { var sg = GetClient("200"); @@ -4483,7 +4484,7 @@ public async Task TestMailSettingsTemplateGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestMailboxProvidersStatsGet() { var sg = GetClient("200"); @@ -4500,7 +4501,7 @@ public async Task TestMailboxProvidersStatsGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestPartnerSettingsGet() { var sg = GetClient("200"); @@ -4512,7 +4513,7 @@ public async Task TestPartnerSettingsGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestPartnerSettingsNewRelicPatch() { var sg = GetClient("200"); @@ -4527,7 +4528,7 @@ public async Task TestPartnerSettingsNewRelicPatch() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestPartnerSettingsNewRelicGet() { var sg = GetClient("200"); @@ -4535,7 +4536,7 @@ public async Task TestPartnerSettingsNewRelicGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestScopesGet() { var sg = GetClient("200"); @@ -4543,7 +4544,7 @@ public async Task TestScopesGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestInvalidUtf8Charset() { var httpResponse = @"{ @@ -4561,7 +4562,7 @@ public async Task TestInvalidUtf8Charset() Assert.Equal(httpResponse, responseBody); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestSendersPost() { var sg = GetClient("201"); @@ -4588,7 +4589,7 @@ public async Task TestSendersPost() Assert.Equal(HttpStatusCode.Created, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestSendersGet() { var sg = GetClient("200"); @@ -4596,7 +4597,7 @@ public async Task TestSendersGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestSendersSenderIdPatch() { var sg = GetClient("200"); @@ -4624,7 +4625,7 @@ public async Task TestSendersSenderIdPatch() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestSendersSenderIdGet() { var sg = GetClient("200"); @@ -4633,7 +4634,7 @@ public async Task TestSendersSenderIdGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestSendersSenderIdDelete() { var sg = GetClient("204"); @@ -4642,7 +4643,7 @@ public async Task TestSendersSenderIdDelete() Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestSendersSenderIdResendVerificationPost() { var sg = GetClient("204"); @@ -4651,7 +4652,7 @@ public async Task TestSendersSenderIdResendVerificationPost() Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestStatsGet() { var sg = GetClient("200"); @@ -4666,7 +4667,7 @@ public async Task TestStatsGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestSubusersPost() { var sg = GetClient("200"); @@ -4685,7 +4686,7 @@ public async Task TestSubusersPost() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestSubusersGet() { var sg = GetClient("200"); @@ -4698,7 +4699,7 @@ public async Task TestSubusersGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestSubusersReputationsGet() { var sg = GetClient("200"); @@ -4709,7 +4710,7 @@ public async Task TestSubusersReputationsGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestSubusersStatsGet() { var sg = GetClient("200"); @@ -4725,7 +4726,7 @@ public async Task TestSubusersStatsGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestSubusersStatsMonthlyGet() { var sg = GetClient("200"); @@ -4741,7 +4742,7 @@ public async Task TestSubusersStatsMonthlyGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestSubusersStatsSumsGet() { var sg = GetClient("200"); @@ -4758,7 +4759,7 @@ public async Task TestSubusersStatsSumsGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestSubusersSubuserNamePatch() { var sg = GetClient("204"); @@ -4772,7 +4773,7 @@ public async Task TestSubusersSubuserNamePatch() Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestSubusersSubuserNameDelete() { @@ -4782,7 +4783,7 @@ public async Task TestSubusersSubuserNameDelete() Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestSubusersSubuserNameIpsPut() { var sg = GetClient("200"); @@ -4796,7 +4797,7 @@ public async Task TestSubusersSubuserNameIpsPut() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestSubusersSubuserNameMonitorPut() { var sg = GetClient("200"); @@ -4811,7 +4812,7 @@ public async Task TestSubusersSubuserNameMonitorPut() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestSubusersSubuserNameMonitorPost() { var sg = GetClient("200"); @@ -4826,7 +4827,7 @@ public async Task TestSubusersSubuserNameMonitorPost() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestSubusersSubuserNameMonitorGet() { var sg = GetClient("200"); @@ -4835,7 +4836,7 @@ public async Task TestSubusersSubuserNameMonitorGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestSubusersSubuserNameMonitorDelete() { var sg = GetClient("204"); @@ -4844,7 +4845,7 @@ public async Task TestSubusersSubuserNameMonitorDelete() Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestSubusersSubuserNameStatsMonthlyGet() { var sg = GetClient("200"); @@ -4860,7 +4861,7 @@ public async Task TestSubusersSubuserNameStatsMonthlyGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestSuppressionBlocksGet() { var sg = GetClient("200"); @@ -4874,7 +4875,7 @@ public async Task TestSuppressionBlocksGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestSuppressionBlocksDelete() { var sg = GetClient("204"); @@ -4891,7 +4892,7 @@ public async Task TestSuppressionBlocksDelete() Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestSuppressionBlocksEmailGet() { var sg = GetClient("200"); @@ -4900,7 +4901,7 @@ public async Task TestSuppressionBlocksEmailGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestSuppressionBlocksEmailDelete() { var sg = GetClient("204"); @@ -4909,7 +4910,7 @@ public async Task TestSuppressionBlocksEmailDelete() Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestSuppressionBouncesGet() { var sg = GetClient("200"); @@ -4921,7 +4922,7 @@ public async Task TestSuppressionBouncesGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestSuppressionBouncesDelete() { var sg = GetClient("204"); @@ -4938,7 +4939,7 @@ public async Task TestSuppressionBouncesDelete() Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestSuppressionBouncesEmailGet() { @@ -4948,7 +4949,7 @@ public async Task TestSuppressionBouncesEmailGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestSuppressionBouncesEmailDelete() { var sg = GetClient("204"); @@ -4960,7 +4961,7 @@ public async Task TestSuppressionBouncesEmailDelete() Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestSuppressionInvalidEmailsGet() { var sg = GetClient("200"); @@ -4974,7 +4975,7 @@ public async Task TestSuppressionInvalidEmailsGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestSuppressionInvalidEmailsDelete() { var sg = GetClient("204"); @@ -4991,7 +4992,7 @@ public async Task TestSuppressionInvalidEmailsDelete() Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestSuppressionInvalidEmailsEmailGet() { var sg = GetClient("200"); @@ -5000,7 +5001,7 @@ public async Task TestSuppressionInvalidEmailsEmailGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestSuppressionInvalidEmailsEmailDelete() { var sg = GetClient("204"); @@ -5009,7 +5010,7 @@ public async Task TestSuppressionInvalidEmailsEmailDelete() Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestSuppressionSpamReportEmailGet() { var sg = GetClient("200"); @@ -5018,7 +5019,7 @@ public async Task TestSuppressionSpamReportEmailGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestSuppressionSpamReportEmailDelete() { var sg = GetClient("204"); @@ -5027,7 +5028,7 @@ public async Task TestSuppressionSpamReportEmailDelete() Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestSuppressionSpamReportsGet() { var sg = GetClient("200"); @@ -5041,7 +5042,7 @@ public async Task TestSuppressionSpamReportsGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestSuppressionSpamReportsDelete() { var sg = GetClient("204"); @@ -5058,7 +5059,7 @@ public async Task TestSuppressionSpamReportsDelete() Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestSuppressionUnsubscribesGet() { var sg = GetClient("200"); @@ -5072,7 +5073,7 @@ public async Task TestSuppressionUnsubscribesGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestTemplatesPost() { var sg = GetClient("201"); @@ -5085,7 +5086,7 @@ public async Task TestTemplatesPost() Assert.Equal(HttpStatusCode.Created, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestTemplatesGet() { var sg = GetClient("200"); @@ -5093,7 +5094,7 @@ public async Task TestTemplatesGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestTemplatesTemplateIdPatch() { var sg = GetClient("200"); @@ -5107,7 +5108,7 @@ public async Task TestTemplatesTemplateIdPatch() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestTemplatesTemplateIdGet() { var sg = GetClient("200"); @@ -5116,7 +5117,7 @@ public async Task TestTemplatesTemplateIdGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestTemplatesTemplateIdDelete() { var sg = GetClient("204"); @@ -5125,7 +5126,7 @@ public async Task TestTemplatesTemplateIdDelete() Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestTemplatesTemplateIdVersionsPost() { var sg = GetClient("201"); @@ -5144,7 +5145,7 @@ public async Task TestTemplatesTemplateIdVersionsPost() Assert.Equal(HttpStatusCode.Created, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestTemplatesTemplateIdVersionsVersionIdPatch() { var sg = GetClient("200"); @@ -5163,7 +5164,7 @@ public async Task TestTemplatesTemplateIdVersionsVersionIdPatch() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestTemplatesTemplateIdVersionsVersionIdGet() { var sg = GetClient("200"); @@ -5173,7 +5174,7 @@ public async Task TestTemplatesTemplateIdVersionsVersionIdGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestTemplatesTemplateIdVersionsVersionIdDelete() { var sg = GetClient("204"); @@ -5183,7 +5184,7 @@ public async Task TestTemplatesTemplateIdVersionsVersionIdDelete() Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestTemplatesTemplateIdVersionsVersionIdActivatePost() { var sg = GetClient("200"); @@ -5193,7 +5194,7 @@ public async Task TestTemplatesTemplateIdVersionsVersionIdActivatePost() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestTrackingSettingsGet() { var sg = GetClient("200"); @@ -5205,7 +5206,7 @@ public async Task TestTrackingSettingsGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestTrackingSettingsClickPatch() { var sg = GetClient("200"); @@ -5218,7 +5219,7 @@ public async Task TestTrackingSettingsClickPatch() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestTrackingSettingsClickGet() { var sg = GetClient("200"); @@ -5226,7 +5227,7 @@ public async Task TestTrackingSettingsClickGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestTrackingSettingsGoogleAnalyticsPatch() { var sg = GetClient("200"); @@ -5244,7 +5245,7 @@ public async Task TestTrackingSettingsGoogleAnalyticsPatch() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestTrackingSettingsGoogleAnalyticsGet() { var sg = GetClient("200"); @@ -5252,7 +5253,7 @@ public async Task TestTrackingSettingsGoogleAnalyticsGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestTrackingSettingsOpenPatch() { var sg = GetClient("200"); @@ -5265,7 +5266,7 @@ public async Task TestTrackingSettingsOpenPatch() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestTrackingSettingsOpenGet() { var sg = GetClient("200"); @@ -5273,7 +5274,7 @@ public async Task TestTrackingSettingsOpenGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestTrackingSettingsSubscriptionPatch() { var sg = GetClient("200"); @@ -5291,7 +5292,7 @@ public async Task TestTrackingSettingsSubscriptionPatch() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestTrackingSettingsSubscriptionGet() { var sg = GetClient("200"); @@ -5299,7 +5300,7 @@ public async Task TestTrackingSettingsSubscriptionGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestUserAccountGet() { var sg = GetClient("200"); @@ -5307,7 +5308,7 @@ public async Task TestUserAccountGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestUserCreditsGet() { var sg = GetClient("200"); @@ -5315,7 +5316,7 @@ public async Task TestUserCreditsGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestUserEmailPut() { var sg = GetClient("200"); @@ -5328,7 +5329,7 @@ public async Task TestUserEmailPut() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestUserEmailGet() { var sg = GetClient("200"); @@ -5336,7 +5337,7 @@ public async Task TestUserEmailGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestUserPasswordPut() { var sg = GetClient("200"); @@ -5350,7 +5351,7 @@ public async Task TestUserPasswordPut() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestUserProfilePatch() { var sg = GetClient("200"); @@ -5365,7 +5366,7 @@ public async Task TestUserProfilePatch() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestUserProfileGet() { var sg = GetClient("200"); @@ -5373,7 +5374,7 @@ public async Task TestUserProfileGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestUserScheduledSendsPost() { var sg = GetClient("201"); @@ -5387,7 +5388,7 @@ public async Task TestUserScheduledSendsPost() Assert.Equal(HttpStatusCode.Created, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestUserScheduledSendsGet() { @@ -5396,7 +5397,7 @@ public async Task TestUserScheduledSendsGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestUserScheduledSendsBatchIdPatch() { var sg = GetClient("204"); @@ -5410,7 +5411,7 @@ public async Task TestUserScheduledSendsBatchIdPatch() Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestUserScheduledSendsBatchIdGet() { var sg = GetClient("200"); @@ -5419,7 +5420,7 @@ public async Task TestUserScheduledSendsBatchIdGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestUserScheduledSendsBatchIdDelete() { var sg = GetClient("204"); @@ -5428,7 +5429,7 @@ public async Task TestUserScheduledSendsBatchIdDelete() Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestUserSettingsEnforcedTlsPatch() { var sg = GetClient("200"); @@ -5442,7 +5443,7 @@ public async Task TestUserSettingsEnforcedTlsPatch() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestUserSettingsEnforcedTlsGet() { var sg = GetClient("200"); @@ -5450,7 +5451,7 @@ public async Task TestUserSettingsEnforcedTlsGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestUserUsernamePut() { @@ -5464,7 +5465,7 @@ public async Task TestUserUsernamePut() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestUserUsernameGet() { var sg = GetClient("200"); @@ -5472,7 +5473,7 @@ public async Task TestUserUsernameGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestUserWebhooksEventSettingsPatch() { var sg = GetClient("200"); @@ -5497,7 +5498,7 @@ public async Task TestUserWebhooksEventSettingsPatch() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestUserWebhooksEventSettingsGet() { var sg = GetClient("200"); @@ -5505,7 +5506,7 @@ public async Task TestUserWebhooksEventSettingsGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestUserWebhooksEventTestPost() { var sg = GetClient("204"); @@ -5518,7 +5519,7 @@ public async Task TestUserWebhooksEventTestPost() Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestUserWebhooksParseSettingsPost() { var sg = GetClient("201"); @@ -5534,7 +5535,7 @@ public async Task TestUserWebhooksParseSettingsPost() Assert.Equal(HttpStatusCode.Created, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestUserWebhooksParseSettingsGet() { var sg = GetClient("200"); @@ -5542,7 +5543,7 @@ public async Task TestUserWebhooksParseSettingsGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestUserWebhooksParseSettingsHostnamePatch() { var sg = GetClient("200"); @@ -5558,7 +5559,7 @@ public async Task TestUserWebhooksParseSettingsHostnamePatch() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestUserWebhooksParseSettingsHostnameGet() { var sg = GetClient("200"); @@ -5567,7 +5568,7 @@ public async Task TestUserWebhooksParseSettingsHostnameGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestUserWebhooksParseSettingsHostnameDelete() { var sg = GetClient("204"); @@ -5576,7 +5577,7 @@ public async Task TestUserWebhooksParseSettingsHostnameDelete() Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestUserWebhooksParseStatsGet() { var sg = GetClient("200"); @@ -5591,7 +5592,7 @@ public async Task TestUserWebhooksParseStatsGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestWhitelabelDomainsPost() { var sg = GetClient("201"); @@ -5613,7 +5614,7 @@ public async Task TestWhitelabelDomainsPost() Assert.Equal(HttpStatusCode.Created, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestWhitelabelDomainsGet() { var sg = GetClient("200"); @@ -5628,7 +5629,7 @@ public async Task TestWhitelabelDomainsGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestWhitelabelDomainsDefaultGet() { var sg = GetClient("200"); @@ -5636,7 +5637,7 @@ public async Task TestWhitelabelDomainsDefaultGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestWhitelabelDomainsSubuserGet() { var sg = GetClient("200"); @@ -5644,7 +5645,7 @@ public async Task TestWhitelabelDomainsSubuserGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestWhitelabelDomainsSubuserDelete() { var sg = GetClient("204"); @@ -5652,7 +5653,7 @@ public async Task TestWhitelabelDomainsSubuserDelete() Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestWhitelabelDomainsDomainIdPatch() { var sg = GetClient("200"); @@ -5667,7 +5668,7 @@ public async Task TestWhitelabelDomainsDomainIdPatch() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestWhitelabelDomainsDomainIdGet() { var sg = GetClient("200"); @@ -5676,7 +5677,7 @@ public async Task TestWhitelabelDomainsDomainIdGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestWhitelabelDomainsDomainIdDelete() { var sg = GetClient("204"); @@ -5685,7 +5686,7 @@ public async Task TestWhitelabelDomainsDomainIdDelete() Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestWhitelabelDomainsDomainIdSubuserPost() { var sg = GetClient("201"); @@ -5699,7 +5700,7 @@ public async Task TestWhitelabelDomainsDomainIdSubuserPost() Assert.Equal(HttpStatusCode.Created, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestWhitelabelDomainsIdIpsPost() { var sg = GetClient("200"); @@ -5713,7 +5714,7 @@ public async Task TestWhitelabelDomainsIdIpsPost() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestWhitelabelDomainsIdIpsIpDelete() { var sg = GetClient("200"); @@ -5723,7 +5724,7 @@ public async Task TestWhitelabelDomainsIdIpsIpDelete() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestWhitelabelDomainsIdValidatePost() { var sg = GetClient("200"); @@ -5732,7 +5733,7 @@ public async Task TestWhitelabelDomainsIdValidatePost() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestWhitelabelIpsPost() { var sg = GetClient("201"); @@ -5747,7 +5748,7 @@ public async Task TestWhitelabelIpsPost() Assert.Equal(HttpStatusCode.Created, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestWhitelabelIpsGet() { var sg = GetClient("200"); @@ -5760,7 +5761,7 @@ public async Task TestWhitelabelIpsGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestWhitelabelIpsIdGet() { var sg = GetClient("200"); @@ -5769,7 +5770,7 @@ public async Task TestWhitelabelIpsIdGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestWhitelabelIpsIdDelete() { var sg = GetClient("204"); @@ -5778,7 +5779,7 @@ public async Task TestWhitelabelIpsIdDelete() Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestWhitelabelIpsIdValidatePost() { var sg = GetClient("200"); @@ -5787,7 +5788,7 @@ public async Task TestWhitelabelIpsIdValidatePost() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestWhitelabelLinksPost() { var sg = GetClient("201"); @@ -5806,7 +5807,7 @@ public async Task TestWhitelabelLinksPost() Assert.Equal(HttpStatusCode.Created, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestWhitelabelLinksGet() { var sg = GetClient("200"); @@ -5817,7 +5818,7 @@ public async Task TestWhitelabelLinksGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestWhitelabelLinksDefaultGet() { var sg = GetClient("200"); @@ -5828,7 +5829,7 @@ public async Task TestWhitelabelLinksDefaultGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestWhitelabelLinksSubuserGet() { var sg = GetClient("200"); @@ -5839,7 +5840,7 @@ public async Task TestWhitelabelLinksSubuserGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestWhitelabelLinksSubuserDelete() { var sg = GetClient("204"); @@ -5850,7 +5851,7 @@ public async Task TestWhitelabelLinksSubuserDelete() Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestWhitelabelLinksIdPatch() { var sg = GetClient("200"); @@ -5864,7 +5865,7 @@ public async Task TestWhitelabelLinksIdPatch() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestWhitelabelLinksIdGet() { var sg = GetClient("200"); @@ -5873,7 +5874,7 @@ public async Task TestWhitelabelLinksIdGet() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestWhitelabelLinksIdDelete() { var sg = GetClient("204"); @@ -5882,7 +5883,7 @@ public async Task TestWhitelabelLinksIdDelete() Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestWhitelabelLinksIdValidatePost() { var sg = GetClient("200"); @@ -5891,7 +5892,7 @@ public async Task TestWhitelabelLinksIdValidatePost() Assert.Equal(HttpStatusCode.OK, response.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestWhitelabelLinksLinkIdSubuserPost() { var sg = GetClient("200"); @@ -5929,7 +5930,7 @@ public async Task TestTakesHttpClientFactoryAsConstructorArgumentAndUsesItInHttp Assert.Equal(httpResponse, response.Body.ReadAsStringAsync().Result); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestTakesProxyAsConstructorArgumentAndInitiailsesHttpClient() { var urlPath = "urlPath"; @@ -5939,7 +5940,7 @@ public void TestTakesProxyAsConstructorArgumentAndInitiailsesHttpClient() Assert.Equal(sg.UrlPath, urlPath); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestTakesNullProxyAsConstructorArgumentAndInitiailsesHttpClient() { var urlPath = "urlPath"; @@ -5955,7 +5956,7 @@ public void TestTakesNullProxyAsConstructorArgumentAndInitiailsesHttpClient() /// the client should NOT return a response code 200, but instead re-throw the exception. /// /// - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestWhenHttpCallTimesOutThenExceptionIsThrown() { /* **************************************************************************************** @@ -5998,7 +5999,7 @@ public async Task TestWhenHttpCallTimesOutThenExceptionIsThrown() /// JSON sent to SendGrid should never include reference handling ($id & $ref) /// /// - [Theory] + [Theory(Skip = SkipConfigureApiKey)] [InlineData("$id")] [InlineData("$ref")] public void TestJsonNetReferenceHandling(string referenceHandlingProperty) @@ -6063,7 +6064,7 @@ public void TestJsonNetReferenceHandling(string referenceHandlingProperty) Assert.False(containsReferenceHandlingProperty); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestRetryBehaviourThrowsTimeoutException() { var msg = new SendGridMessage(); @@ -6091,7 +6092,7 @@ public async Task TestRetryBehaviourThrowsTimeoutException() Assert.NotNull(exception); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async Task TestRetryBehaviourSucceedsOnSecondAttempt() { var msg = new SendGridMessage(); @@ -6120,13 +6121,13 @@ public async Task TestRetryBehaviourSucceedsOnSecondAttempt() Assert.Equal(HttpStatusCode.OK, result.StatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async void TestHttpErrorAsExceptionWhenSetInOptions() { await TestHttpErrorAsException((client, apiKey) => new SendGridClient(client, new SendGridClientOptions { ApiKey = apiKey, HttpErrorAsException = true })); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public async void TestHttpErrorAsExceptionWhenSetAsParameter() { await TestHttpErrorAsException((client, apiKey) => new SendGridClient(client, apiKey, httpErrorAsException: true)); @@ -6191,7 +6192,7 @@ public void TestStringToEmailAddress(string input, string expectedName, string e /// Tests the conditions in issue #670. /// /// - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestInjectSameHttpClientWithMultipleInstance() { var httpMessageHandler = new FixedStatusAndMessageHttpMessageHandler(HttpStatusCode.Accepted, string.Empty); @@ -6200,7 +6201,7 @@ public void TestInjectSameHttpClientWithMultipleInstance() var sg2 = new SendGridClient(clientToInject, fixture.apiKey); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestBadRequestIsSuccessStatusCodeReturnsFalse() { var message = new HttpResponseMessage(); @@ -6208,7 +6209,7 @@ public void TestBadRequestIsSuccessStatusCodeReturnsFalse() Assert.False(response.IsSuccessStatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestOkRequestIsSuccessStatusCodeReturnsTrue() { var message = new HttpResponseMessage(); @@ -6216,7 +6217,7 @@ public void TestOkRequestIsSuccessStatusCodeReturnsTrue() Assert.True(response.IsSuccessStatusCode); } - [Fact] + [Fact(Skip = SkipConfigureApiKey)] public void TestIsSuccessStatusCodeEvery2xxCodeReturnsTrue() { for (int i = 200; i <= 299; ++i) diff --git a/tests/SendGrid.Tests/ResponseTests.cs b/tests/SendGrid.Tests/ResponseTests.cs index 904258a7b..fad5a66e3 100644 --- a/tests/SendGrid.Tests/ResponseTests.cs +++ b/tests/SendGrid.Tests/ResponseTests.cs @@ -1,8 +1,11 @@ using Newtonsoft.Json.Linq; using System.Collections.Generic; +using System.Linq; using System.Net; using System.Net.Http; +using System.Text.Json; +using System.Text.Json.Nodes; using System.Threading.Tasks; using Xunit; @@ -25,7 +28,11 @@ public async Task DeserializeResponseBodyAsync_JsonHttpContent_ReturnsBodyAsDict var content = "{\"scopes\": [\"alerts.read\"]}"; var response = new Response(HttpStatusCode.OK, new StringContent(content), null); Dictionary responseBody = await response.DeserializeResponseBodyAsync(); - Assert.Equal(new JArray() { "alerts.read" }, responseBody["scopes"]); + var actual = responseBody["scopes"]; + var success = actual is JsonElement { ValueKind: JsonValueKind.Array } m && + m.EnumerateArray().Single() is { ValueKind: JsonValueKind.String } m2 && + m2.GetString() == "alerts.read"; + Assert.True(success, "Result is not [\"alerts.read\"]"); } [Fact] @@ -34,7 +41,11 @@ public async Task DeserializeResponseBodyAsync_OverrideHttpContent_ReturnsBodyAs var content = "{\"scopes\": [\"alerts.read\"]}"; var response = new Response(HttpStatusCode.OK, null, null); Dictionary responseBody = await response.DeserializeResponseBodyAsync(new StringContent(content)); - Assert.Equal(new JArray() { "alerts.read" }, responseBody["scopes"]); + var actual = responseBody["scopes"]; + var success = actual is JsonElement { ValueKind: JsonValueKind.Array } m && + m.EnumerateArray().Single() is { ValueKind: JsonValueKind.String } m2 && + m2.GetString() == "alerts.read"; + Assert.True(success, "Result is not [\"alerts.read\"]"); } [Fact] diff --git a/tests/SendGrid.Tests/SendGrid.Tests.csproj b/tests/SendGrid.Tests/SendGrid.Tests.csproj index f61ad8027..5e11f042e 100644 --- a/tests/SendGrid.Tests/SendGrid.Tests.csproj +++ b/tests/SendGrid.Tests/SendGrid.Tests.csproj @@ -1,7 +1,7 @@  - netcoreapp2.1 + net8.0 true false diff --git a/tests/SendGrid.Tests/TemplateDataSerialisationTests.cs b/tests/SendGrid.Tests/TemplateDataSerialisationTests.cs index 83137c4d1..d9da339bb 100644 --- a/tests/SendGrid.Tests/TemplateDataSerialisationTests.cs +++ b/tests/SendGrid.Tests/TemplateDataSerialisationTests.cs @@ -1,4 +1,4 @@ -using Newtonsoft.Json; +using System.Text.Json.Serialization; using SendGrid.Helpers.Mail; using Xunit; @@ -20,20 +20,22 @@ public void TestSetTemplateDataWorksWithSpecifiedJsonPropertyNames() }; msg.SetTemplateData(dynamicTemplateData); - Assert.Equal("{\"personalizations\":[{\"dynamic_template_data\":{\"myCamelCaseProperty\":\"camelCase\",\"my-kebab-case-property\":\"kebab-case\",\"MyPascalCaseProperty\":\"PascalCase\",\"my_snake_case_property\":\"snake_case\"}}]}", msg.Serialize()); + var actual = msg.Serialize(); + var expected = "{\"personalizations\":[{\"dynamic_template_data\":{\"myCamelCaseProperty\":\"camelCase\",\"my-kebab-case-property\":\"kebab-case\",\"MyPascalCaseProperty\":\"PascalCase\",\"my_snake_case_property\":\"snake_case\"}}]}"; + Assert.Equal(expected, actual); } private class TestTemplateData { - [JsonProperty("myCamelCaseProperty")] + [JsonPropertyName("myCamelCaseProperty")] public string MyCamelCaseProperty { get; set; } - [JsonProperty("my-kebab-case-property")] + [JsonPropertyName("my-kebab-case-property")] public string MyKebabCaseProperty { get; set; } public string MyPascalCaseProperty { get; set; } - [JsonProperty("my_snake_case_property")] + [JsonPropertyName("my_snake_case_property")] public string MySnakeCaseProperty { get; set; } } }