Compare commits

..

14 Commits

Author SHA1 Message Date
Stef Heyenrath
1f1bc05f00 1.5.27 2023-06-03 17:00:18 +02:00
Stef Heyenrath
c107e38e3b Fix WireMock.Net.FluentAssertions for net47 2023-06-02 12:03:12 +02:00
Stef Heyenrath
a77c4fe1ac Add ".NET Framework 4.7" to WireMock.Net.FluentAssertions (#949) 2023-06-01 18:06:28 +02:00
Stef Heyenrath
c1e71707c5 Add warning logging when sending a request to a Webhook does not return status 200 (#946) 2023-05-28 10:53:54 +02:00
Oleg Nenashev
69499afe43 Update Slack link (#944)
Better to use https://slack.wiremock.org/ to have proper Slack signup
2023-05-26 10:01:16 +02:00
Stef Heyenrath
aadac78577 add Slack 2023-05-25 23:49:12 +02:00
Stef Heyenrath
71393204cc 1.5.26 2023-05-25 21:36:01 +02:00
Cezary Piątek
e5cc6f570c Code generator improvements (#940)
* Fix quotation marks escaping in multiline string

* Add support for JsonPartialMatcher and JsonPartialWildcardMatcher in mapping code generator
2023-05-25 20:59:13 +02:00
Stef Heyenrath
7c3a0c815d Add GetParameter method to IRequestMessage (#942) 2023-05-25 15:14:02 +02:00
Stef Heyenrath
e61f08fe48 WireMockMiddleware should use HandleRequestsSynchronously correctly (#939) 2023-05-19 21:43:14 +02:00
Stef Heyenrath
11f4c47851 Add more unitests for CSharpFormatter utils (#938)
* Add unit-tests for CSharpFormatter

* .

* t
2023-05-19 16:14:26 +02:00
Stef Heyenrath
3956cd703b 1.5.25 (ReleaseNotes) 2023-05-13 11:17:03 +02:00
Stef Heyenrath
27682d0ce4 1.5.25 + Fixes in CSharpFormatter 2023-05-13 11:15:40 +02:00
Cezary Piątek
8444c8c506 Code generator improvements (#934)
* Handle new line escaping in C# mapping code generator

* Prevent date conversion when value persisted as string

* Handle object properties named as csharp keywords

* Refactor: Extract logic responsible for generating anonymous object definition to a separate class
2023-05-13 09:33:25 +02:00
17 changed files with 579 additions and 126 deletions

View File

@@ -1,3 +1,19 @@
# 1.5.27 (03 June 2023)
- [#946](https://github.com/WireMock-Net/WireMock.Net/pull/946) - Add warning logging when sending a request to a Webhook does not return status 200 [feature] contributed by [StefH](https://github.com/StefH)
- [#949](https://github.com/WireMock-Net/WireMock.Net/pull/949) - Add ".NET Framework 4.7" to WireMock.Net.FluentAssertions [feature] contributed by [StefH](https://github.com/StefH)
- [#928](https://github.com/WireMock-Net/WireMock.Net/issues/928) - TypeLoadException when using WithHeader method. [bug]
- [#945](https://github.com/WireMock-Net/WireMock.Net/issues/945) - Webhook logging [feature]
# 1.5.26 (25 May 2023)
- [#938](https://github.com/WireMock-Net/WireMock.Net/pull/938) - Add more unitests for CSharpFormatter utils [test] contributed by [StefH](https://github.com/StefH)
- [#939](https://github.com/WireMock-Net/WireMock.Net/pull/939) - WireMockMiddleware should use HandleRequestsSynchronously correctly [bug] contributed by [StefH](https://github.com/StefH)
- [#940](https://github.com/WireMock-Net/WireMock.Net/pull/940) - Code generator improvements contributed by [cezarypiatek](https://github.com/cezarypiatek)
- [#942](https://github.com/WireMock-Net/WireMock.Net/pull/942) - Add GetParameter method to IRequestMessage [feature] contributed by [StefH](https://github.com/StefH)
- [#941](https://github.com/WireMock-Net/WireMock.Net/issues/941) - RequestMessage.GetParameter method missing from IRequestMessage interface [feature]
# 1.5.25 (13 May 2023)
- [#934](https://github.com/WireMock-Net/WireMock.Net/pull/934) - Code generator improvements [feature] contributed by [cezarypiatek](https://github.com/cezarypiatek)
# 1.5.24 (07 May 2023)
- [#926](https://github.com/WireMock-Net/WireMock.Net/pull/926) - Fix C# mapping code generator for header names [bug] contributed by [cezarypiatek](https://github.com/cezarypiatek)
- [#927](https://github.com/WireMock-Net/WireMock.Net/pull/927) - Enrich generated code with status code [feature] contributed by [cezarypiatek](https://github.com/cezarypiatek)

View File

@@ -4,7 +4,7 @@
</PropertyGroup>
<PropertyGroup>
<VersionPrefix>1.5.24</VersionPrefix>
<VersionPrefix>1.5.27</VersionPrefix>
<PackageIcon>WireMock.Net-Logo.png</PackageIcon>
<PackageProjectUrl>https://github.com/WireMock-Net/WireMock.Net</PackageProjectUrl>
<PackageLicenseExpression>Apache-2.0</PackageLicenseExpression>

View File

@@ -1,6 +1,6 @@
rem https://github.com/StefH/GitHubReleaseNotes
SET version=1.5.24
SET version=1.5.27
GitHubReleaseNotes --output CHANGELOG.md --skip-empty-releases --exclude-labels question invalid doc duplicate --version %version% --token %GH_TOKEN%

View File

@@ -1,8 +1,7 @@
# 1.5.24 (07 May 2023)
- #926 Fix C# mapping code generator for header names [bug]
- #927 Enrich generated code with status code [feature]
- #930 Update C# mapping code generator for WithStatusCode [feature]
- #931 Add property 'IsStartedWithAdminInterface' to 'IWireMockServer' [feature]
- #933 C# code generator improvements [feature]
# 1.5.27 (03 June 2023)
- #946 Add warning logging when sending a request to a Webhook does not return status 200 [feature]
- #949 Add &quot;.NET Framework 4.7&quot; to WireMock.Net.FluentAssertions [feature]
- #928 TypeLoadException when using WithHeader method. [bug]
- #945 Webhook logging [feature]
The full release notes can be found here: https://github.com/WireMock-Net/WireMock.Net/blob/master/CHANGELOG.md

View File

@@ -22,7 +22,7 @@ For more info, see also this WIKI page: [What is WireMock.Net](https://github.co
| | |
| --- | --- |
| ***Project*** | &nbsp; |
| &nbsp;&nbsp;**Chat** | [![Gitter](https://img.shields.io/gitter/room/wiremock_dotnet/Lobby.svg)](https://gitter.im/wiremock_dotnet/Lobby) |
| &nbsp;&nbsp;**Chat** | [![Slack](https://badgen.net/badge/icon/slack?icon=slack&label)](https://slack.wiremock.org/) [![Gitter](https://img.shields.io/gitter/room/wiremock_dotnet/Lobby.svg)](https://gitter.im/wiremock_dotnet/Lobby) |
| &nbsp;&nbsp;**Issues** | [![GitHub issues](https://img.shields.io/github/issues/WireMock-Net/WireMock.Net.svg)](https://github.com/WireMock-Net/WireMock.Net/issues) |
| | |
| ***Quality*** | &nbsp; |

View File

@@ -143,6 +143,14 @@ public interface IRequestMessage
/// </summary>
string Origin { get; }
/// <summary>
/// Get a query parameter.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="ignoreCase">Defines if the key should be matched using case-ignore.</param>
/// <returns>The query parameter value as WireMockList or null when not found.</returns>
WireMockList<string>? GetParameter(string key, bool ignoreCase = false);
#if NETSTANDARD1_3_OR_GREATER || NET461
/// <summary>
/// Gets the connection's client certificate

View File

@@ -1,49 +1,49 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<Description>FluentAssertions extensions for WireMock.Net</Description>
<AssemblyTitle>WireMock.Net.FluentAssertions</AssemblyTitle>
<Authors>Mahmoud Ali;Stef Heyenrath</Authors>
<TargetFrameworks>net451;netstandard1.3;netstandard2.0;netstandard2.1</TargetFrameworks>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<AssemblyName>WireMock.Net.FluentAssertions</AssemblyName>
<PackageId>WireMock.Net.FluentAssertions</PackageId>
<PackageTags>wiremock;FluentAssertions;UnitTest;Assert;Assertions</PackageTags>
<RootNamespace>WireMock.FluentAssertions</RootNamespace>
<ProjectGuid>{B6269AAC-170A-4346-8B9A-579DED3D9A95}</ProjectGuid>
<PublishRepositoryUrl>true</PublishRepositoryUrl>
<AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder>
<EmbedUntrackedSources>true</EmbedUntrackedSources>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>
<CodeAnalysisRuleSet>../WireMock.Net/WireMock.Net.ruleset</CodeAnalysisRuleSet>
<SignAssembly>true</SignAssembly>
<AssemblyOriginatorKeyFile>../WireMock.Net/WireMock.Net.snk</AssemblyOriginatorKeyFile>
<!--<DelaySign>true</DelaySign>-->
<PublicSign Condition=" '$(OS)' != 'Windows_NT' ">true</PublicSign>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<LangVersion>10</LangVersion>
</PropertyGroup>
<PropertyGroup>
<Description>FluentAssertions extensions for WireMock.Net</Description>
<AssemblyTitle>WireMock.Net.FluentAssertions</AssemblyTitle>
<Authors>Mahmoud Ali;Stef Heyenrath</Authors>
<TargetFrameworks>net451;net47;netstandard1.3;netstandard2.0;netstandard2.1</TargetFrameworks>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<AssemblyName>WireMock.Net.FluentAssertions</AssemblyName>
<PackageId>WireMock.Net.FluentAssertions</PackageId>
<PackageTags>wiremock;FluentAssertions;UnitTest;Assert;Assertions</PackageTags>
<RootNamespace>WireMock.FluentAssertions</RootNamespace>
<ProjectGuid>{B6269AAC-170A-4346-8B9A-579DED3D9A95}</ProjectGuid>
<PublishRepositoryUrl>true</PublishRepositoryUrl>
<AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder>
<EmbedUntrackedSources>true</EmbedUntrackedSources>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>
<CodeAnalysisRuleSet>../WireMock.Net/WireMock.Net.ruleset</CodeAnalysisRuleSet>
<SignAssembly>true</SignAssembly>
<AssemblyOriginatorKeyFile>../WireMock.Net/WireMock.Net.snk</AssemblyOriginatorKeyFile>
<!--<DelaySign>true</DelaySign>-->
<PublicSign Condition=" '$(OS)' != 'Windows_NT' ">true</PublicSign>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<LangVersion>10</LangVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="JetBrains.Annotations" Version="2022.3.1" PrivateAssets="All" />
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="JetBrains.Annotations" Version="2022.3.1" PrivateAssets="All" />
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.1.1" PrivateAssets="All" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net451' or '$(TargetFramework)' == 'netstandard1.3'">
<PackageReference Include="FluentAssertions" Version="5.10.3" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net451' or '$(TargetFramework)' == 'netstandard1.3'">
<PackageReference Include="FluentAssertions" Version="5.10.3" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' != 'net451' and '$(TargetFramework)' != 'netstandard1.3'">
<PackageReference Include="FluentAssertions" Version="6.5.1" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' != 'net451' and '$(TargetFramework)' != 'netstandard1.3'">
<PackageReference Include="FluentAssertions" Version="6.5.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\WireMock.Net.Abstractions\WireMock.Net.Abstractions.csproj" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\WireMock.Net.Abstractions\WireMock.Net.Abstractions.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,17 @@
{
"help": "https://go.microsoft.com/fwlink/?linkid=866610",
"root": true,
"dependentFileProviders": {
"add": {
"addedExtension": {},
"pathSegment": {
"add": {
".*": [
".cs"
]
}
}
}
}
}

View File

@@ -60,7 +60,7 @@ namespace WireMock.Owin
public Task Invoke(IContext ctx)
#endif
{
if (_options.HandleRequestsSynchronously.GetValueOrDefault(true))
if (_options.HandleRequestsSynchronously.GetValueOrDefault(false))
{
lock (_lock)
{
@@ -216,7 +216,12 @@ namespace WireMock.Owin
{
try
{
await webhookSender.SendAsync(httpClientForWebhook, mapping, webhookRequest, request, response).ConfigureAwait(false);
var result = await webhookSender.SendAsync(httpClientForWebhook, mapping, webhookRequest, request, response).ConfigureAwait(false);
if (!result.IsSuccessStatusCode)
{
var content = await result.Content.ReadAsStringAsync().ConfigureAwait(false);
_options.Logger.Warn($"Sending message to Webhook [{webHookIndex}] from Mapping '{mapping.Guid}' failed. HttpStatusCode: {result.StatusCode} Content: {content}");
}
}
catch (Exception ex)
{

View File

@@ -180,12 +180,7 @@ public class RequestMessage : IRequestMessage
#endif
}
/// <summary>
/// Get a query parameter.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="ignoreCase">Defines if the key should be matched using case-ignore.</param>
/// <returns>The query parameter.</returns>
/// <inheritdoc />
public WireMockList<string>? GetParameter(string key, bool ignoreCase = false)
{
if (Query == null)

View File

@@ -5,7 +5,6 @@ using System.Net;
using System.Text;
using System.Threading;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Stef.Validation;
using WireMock.Admin.Mappings;
using WireMock.Constants;
@@ -19,6 +18,7 @@ using WireMock.Settings;
using WireMock.Types;
using WireMock.Util;
using static WireMock.Util.CSharpFormatter;
namespace WireMock.Serialization;
internal class MappingConverter
@@ -107,11 +107,28 @@ internal class MappingConverter
if (bodyMatcher is { Matchers: { } })
{
var wildcardMatcher = bodyMatcher.Matchers.OfType<WildcardMatcher>().FirstOrDefault();
if (wildcardMatcher is { } && wildcardMatcher.GetPatterns().Any())
if (bodyMatcher.Matchers.OfType<WildcardMatcher>().FirstOrDefault() is { } wildcardMatcher && wildcardMatcher.GetPatterns().Any())
{
sb.AppendLine($" .WithBody({GetString(wildcardMatcher)})");
}
else if (bodyMatcher.Matchers.OfType<JsonPartialMatcher>().FirstOrDefault() is { Value: { } } jsonPartialMatcher)
{
sb.AppendLine(@$" .WithBody(new JsonPartialMatcher(
value: {ToCSharpStringLiteral(jsonPartialMatcher.Value.ToString())},
ignoreCase: {ToCSharpBooleanLiteral(jsonPartialMatcher.IgnoreCase)},
throwException: {ToCSharpBooleanLiteral(jsonPartialMatcher.ThrowException)},
regex: {ToCSharpBooleanLiteral(jsonPartialMatcher.Regex)}
))");
}
else if (bodyMatcher.Matchers.OfType<JsonPartialWildcardMatcher>().FirstOrDefault() is { Value: { } } jsonPartialWildcardMatcher)
{
sb.AppendLine(@$" .WithBody(new JsonPartialWildcardMatcher(
value: {ToCSharpStringLiteral(jsonPartialWildcardMatcher.Value.ToString())},
ignoreCase: {ToCSharpBooleanLiteral(jsonPartialWildcardMatcher.IgnoreCase)},
throwException: {ToCSharpBooleanLiteral(jsonPartialWildcardMatcher.ThrowException)},
regex: {ToCSharpBooleanLiteral(jsonPartialWildcardMatcher.Regex)}
))");
}
}
sb.AppendLine(@" )");
@@ -150,18 +167,17 @@ internal class MappingConverter
{
case BodyType.String:
case BodyType.FormUrlEncoded:
sb.AppendLine($" .WithBody(\"{EscapeCSharpString(bodyData.BodyAsString)}\")");
sb.AppendLine($" .WithBody({ToCSharpStringLiteral(bodyData.BodyAsString)})");
break;
case BodyType.Json:
if (bodyData.BodyAsJson is string bodyStringValue)
{
sb.AppendLine($" .WithBody(\"{EscapeCSharpString(bodyStringValue)}\")");
sb.AppendLine($" .WithBody({ToCSharpStringLiteral(bodyStringValue)})");
}
else
else if(bodyData.BodyAsJson is {} jsonBody)
{
var serializedBody = JsonConvert.SerializeObject(bodyData.BodyAsJson);
var deserializedBody = JToken.Parse(serializedBody);
sb.AppendLine($" .WithBodyAsJson({ConvertJsonToAnonymousObjectDefinition(deserializedBody, 2)})");
var anonymousObjectDefinition = ConvertToAnonymousObjectDefinition(jsonBody);
sb.AppendLine($" .WithBodyAsJson({anonymousObjectDefinition})");
}
break;
@@ -406,7 +422,7 @@ internal class MappingConverter
private static string GetString(IStringMatcher stringMatcher)
{
return stringMatcher.GetPatterns().Select(p => $"\"{p.GetPattern()}\"").First();
return stringMatcher.GetPatterns().Select(p => ToCSharpStringLiteral(p.GetPattern())).First();
}
private static string[] GetStringArray(IReadOnlyList<IStringMatcher> stringMatchers)
@@ -459,11 +475,9 @@ internal class MappingConverter
private static string ToValueArguments(string[]? values, string defaultValue = "")
{
return values is { } ? string.Join(", ", values.Select(v => $"\"{EscapeCSharpString(v)}\"")) : $"\"{EscapeCSharpString(defaultValue)}\"";
return values is { } ? string.Join(", ", values.Select(ToCSharpStringLiteral)) : ToCSharpStringLiteral(defaultValue);
}
private static string? EscapeCSharpString(string? value) => value?.Replace("\"", "\\\"");
private static WebProxyModel? MapWebProxy(WebProxySettings? settings)
{
return settings != null ? new WebProxyModel
@@ -493,48 +507,5 @@ internal class MappingConverter
return newDictionary;
}
private static string ConvertJsonToAnonymousObjectDefinition(JToken token, int ind = 0)
{
return token switch
{
JArray jArray => FormatArray(jArray, ind),
JObject jObject => FormatObject(jObject, ind),
JProperty jProperty => $"{jProperty.Name} = {ConvertJsonToAnonymousObjectDefinition(jProperty.Value, ind)}",
JValue jValue => jValue.Type switch
{
JTokenType.None => "null",
JTokenType.Integer => jValue.Value?.ToString() ?? "null",
JTokenType.Float => jValue.Value?.ToString() ?? "null",
JTokenType.String => $"\"{EscapeCSharpString(jValue.Value?.ToString())}\"",
JTokenType.Boolean => jValue.Value?.ToString()?.ToLower() ?? "null",
JTokenType.Null => "null",
JTokenType.Undefined => "null",
_ => $"UNHANDLED_CASE: {jValue.Type}"
},
_ => $"UNHANDLED_CASE: {token}"
};
}
private static string FormatObject(JObject jObject, int ind)
{
var indStr = new string(' ', 4 * ind);
var indStrSub = new string(' ', 4 * (ind + 1));
var items = jObject.Properties().Select(x => ConvertJsonToAnonymousObjectDefinition(x, ind + 1));
return $"new\r\n{indStr}{{\r\n{indStrSub}{string.Join($",\r\n{indStrSub}", items)}\r\n{indStr}}}";
}
private static string FormatArray(JArray jArray, int ind)
{
var hasComplexItems = jArray.FirstOrDefault() is JObject or JArray;
var items = jArray.Select(x => ConvertJsonToAnonymousObjectDefinition(x, hasComplexItems ? ind + 1 : ind));
if (hasComplexItems)
{
var indStr = new string(' ', 4 * ind);
var indStrSub = new string(' ', 4 * (ind + 1));
return $"new []\r\n{indStr}{{\r\n{indStrSub}{string.Join($",\r\n{indStrSub}", items)}\r\n{indStr}}}";
}
return $"new [] {{ {string.Join(", ", items)} }}";
}
}

View File

@@ -0,0 +1,180 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace WireMock.Util;
internal static class CSharpFormatter
{
#region Reserved Keywords
private static readonly HashSet<string> CSharpReservedKeywords = new(new[]
{
"abstract",
"as",
"base",
"bool",
"break",
"byte",
"case",
"catch",
"char",
"checked",
"class",
"const",
"continue",
"decimal",
"default",
"delegate",
"do",
"double",
"else",
"enum",
"event",
"explicit",
"extern",
"false",
"finally",
"fixed",
"float",
"for",
"foreach",
"goto",
"if",
"implicit",
"in",
"int",
"interface",
"internal",
"is",
"lock",
"long",
"namespace",
"new",
"null",
"object",
"operator",
"out",
"override",
"params",
"private",
"protected",
"public",
"readonly",
"ref",
"return",
"sbyte",
"sealed",
"short",
"sizeof",
"stackalloc",
"static",
"string",
"struct",
"switch",
"this",
"throw",
"true",
"try",
"typeof",
"uint",
"ulong",
"unchecked",
"unsafe",
"ushort",
"using",
"virtual",
"void",
"volatile",
"while"
});
#endregion
private const string Null = "null";
public static object ConvertToAnonymousObjectDefinition(object jsonBody)
{
var serializedBody = JsonConvert.SerializeObject(jsonBody);
using var jsonReader = new JsonTextReader(new StringReader(serializedBody));
jsonReader.DateParseHandling = DateParseHandling.None;
var deserializedBody = JObject.Load(jsonReader);
return ConvertJsonToAnonymousObjectDefinition(deserializedBody, 2);
}
public static string ConvertJsonToAnonymousObjectDefinition(JToken token, int ind = 0)
{
return token switch
{
JArray jArray => FormatArray(jArray, ind),
JObject jObject => FormatObject(jObject, ind),
JProperty jProperty => $"{FormatPropertyName(jProperty.Name)} = {ConvertJsonToAnonymousObjectDefinition(jProperty.Value, ind)}",
JValue jValue => jValue.Type switch
{
JTokenType.None => Null,
JTokenType.Integer => jValue.Value != null ? string.Format(CultureInfo.InvariantCulture, "{0}", jValue.Value) : Null,
JTokenType.Float => jValue.Value != null ? string.Format(CultureInfo.InvariantCulture, "{0}", jValue.Value) : Null,
JTokenType.String => ToCSharpStringLiteral(jValue.Value?.ToString()),
JTokenType.Boolean => jValue.Value != null ? string.Format(CultureInfo.InvariantCulture, "{0}", jValue.Value).ToLower() : Null,
JTokenType.Null => Null,
JTokenType.Undefined => Null,
JTokenType.Date when jValue.Value is DateTime dateValue =>
$"DateTime.Parse({ToCSharpStringLiteral(dateValue.ToString("s"))})",
_ => $"UNHANDLED_CASE: {jValue.Type}"
},
_ => $"UNHANDLED_CASE: {token}"
};
}
public static string ToCSharpBooleanLiteral(bool value) => value ? "true" : "false";
public static string ToCSharpStringLiteral(string? value)
{
if (string.IsNullOrEmpty(value))
{
return "\"\"";
}
if (value.Contains("\n"))
{
var escapedValue = value?.Replace("\"", "\"\"") ?? string.Empty;
return $"@\"{escapedValue}\"";
}
else
{
var escapedValue = value?.Replace("\"", "\\\"") ?? string.Empty;
return $"\"{escapedValue}\"";
}
}
public static string FormatPropertyName(string propertyName)
{
return CSharpReservedKeywords.Contains(propertyName) ? "@" + propertyName : propertyName;
}
private static string FormatObject(JObject jObject, int ind)
{
var indStr = new string(' ', 4 * ind);
var indStrSub = new string(' ', 4 * (ind + 1));
var items = jObject.Properties().Select(x => ConvertJsonToAnonymousObjectDefinition(x, ind + 1));
return $"new\r\n{indStr}{{\r\n{indStrSub}{string.Join($",\r\n{indStrSub}", items)}\r\n{indStr}}}";
}
private static string FormatArray(JArray jArray, int ind)
{
var hasComplexItems = jArray.FirstOrDefault() is JObject or JArray;
var items = jArray.Select(x => ConvertJsonToAnonymousObjectDefinition(x, hasComplexItems ? ind + 1 : ind));
if (hasComplexItems)
{
var indStr = new string(' ', 4 * ind);
var indStrSub = new string(' ', 4 * (ind + 1));
return $"new []\r\n{indStr}{{\r\n{indStrSub}{string.Join($",\r\n{indStrSub}", items)}\r\n{indStr}}}";
}
return $"new [] {{ {string.Join(", ", items)} }}";
}
}

View File

@@ -10,17 +10,17 @@ public class BytesEncodingUtilsTests
[Fact]
public void TryGetEncoding_UTF32()
{
var result = BytesEncodingUtils.TryGetEncoding(new byte[] { 0xff, 0xfe, 0x00, 0x00 }, out Encoding encoding);
var result = BytesEncodingUtils.TryGetEncoding(new byte[] { 0xff, 0xfe, 0x00, 0x00 }, out var encoding);
// Assert
result.Should().BeTrue();
encoding.CodePage.Should().Be(Encoding.UTF32.CodePage);
encoding?.CodePage.Should().Be(Encoding.UTF32.CodePage);
}
[Fact]
public void TryGetEncoding_Invalid()
{
var result = BytesEncodingUtils.TryGetEncoding(new byte[] { 0xff }, out Encoding encoding);
var result = BytesEncodingUtils.TryGetEncoding(new byte[] { 0xff }, out var encoding);
// Assert
result.Should().BeFalse();

View File

@@ -0,0 +1,105 @@
using FluentAssertions;
using Newtonsoft.Json.Linq;
using WireMock.Util;
using Xunit;
namespace WireMock.Net.Tests.Util;
public class CSharpFormatterTests
{
[Fact]
public void ConvertToAnonymousObjectDefinition_ShouldReturn_ValidValue_WhenJsonBodyIsValidJsonString()
{
// Arrange
var jsonBody = new { Key1 = "value1", Key2 = 42, F = 1.2 };
var expectedOutput = "new\r\n {\r\n Key1 = \"value1\",\r\n Key2 = 42,\r\n F = 1.2\r\n }";
// Act
var result = CSharpFormatter.ConvertToAnonymousObjectDefinition(jsonBody);
// Assert
result.Should().Be(expectedOutput);
}
[Fact]
public void ToCSharpStringLiteral_ShouldReturn_ValidValue_WhenStringIsNotNull()
{
// Arrange
var inputString = "test string";
var expectedOutput = "\"test string\"";
// Act
var result = CSharpFormatter.ToCSharpStringLiteral(inputString);
// Assert
result.Should().Be(expectedOutput);
}
[Fact]
public void ToCSharpStringLiteral_ShouldReturn_ValidValue_WhenStringContainsNewLineCharacters()
{
// Arrange
var inputString = "line1\nline2\nline3";
var expectedOutput = "@\"line1\nline2\nline3\"";
// Action
var result = CSharpFormatter.ToCSharpStringLiteral(inputString);
// Assert
result.Should().Be(expectedOutput);
}
[Fact]
public void FormatPropertyName_ShouldReturn_ValidPropertyName_WhenPropertyNameIsNotReserved()
{
// Arrange
var propertyName = "propertyname";
var expectedOutput = "propertyname";
// Action
var result = CSharpFormatter.FormatPropertyName(propertyName);
// Assert
result.Should().Be(expectedOutput);
}
[Fact]
public void FormatPropertyName_ShouldReturn_ValidPropertyName_WhenPropertyNameIsReserved()
{
// Arrange
var propertyName = "class";
var expectedOutput = "@class";
// Action
var result = CSharpFormatter.FormatPropertyName(propertyName);
// Assert
result.Should().Be(expectedOutput);
}
[Fact]
public void ConvertJsonToAnonymousObjectDefinition_ShouldReturn_ValidObject_WhenJsonInputIsValid()
{
// Arrange
var jObject = new JObject
(
new JProperty("Name", "John Smith"),
new JProperty("Age", 25.1f),
new JProperty("Gender", "Male"),
new JProperty("address", new JObject
(
new JProperty("Street", "123 Main St"),
new JProperty("City", "Anytown"),
new JProperty("State", "CA"),
new JProperty("Zip", "90001")
)
));
var expectedOutput = "new\r\n{\r\n Name = \"John Smith\",\r\n Age = 25.1,\r\n Gender = \"Male\",\r\n address = new\r\n {\r\n Street = \"123 Main St\",\r\n City = \"Anytown\",\r\n State = \"CA\",\r\n Zip = \"90001\"\r\n }\r\n}";
// Action
var result = CSharpFormatter.ConvertJsonToAnonymousObjectDefinition(jObject);
// Assert
result.Should().Be(expectedOutput);
}
}

View File

@@ -36,7 +36,7 @@ server
.WithStatusCode(208)
.WithBodyAsJson(new
{
a = 1,
@as = 1,
b = 1.2,
d = true,
e = false,
@@ -59,7 +59,32 @@ server
b = 3
}
}
}
},
date_field = "2023-05-08T11:20:19",
string_field_with_date = "2021-03-13T21:04:00Z",
multiline_text = @"This
is
multiline
text
"
})
);
server
.Given(Request.Create()
.UsingMethod("POST")
.WithPath("/foo3")
.WithBody(new JsonPartialMatcher(
value: "{ a = 1, b = 2 }",
ignoreCase: false,
throwException: false,
regex: false
))
)
.WithGuid("4126dec8-470b-4eff-93bb-c24f83b8b1fd")
.RespondWith(Response.Create()
.WithStatusCode(200)
.WithBody(@"Line1
Some ""value"" in Line2")
);

View File

@@ -18,6 +18,7 @@ using WireMock.Admin.Settings;
using WireMock.Client;
using WireMock.Handlers;
using WireMock.Logging;
using WireMock.Matchers;
using WireMock.Models;
using WireMock.Net.Tests.VerifyExtensions;
using WireMock.RequestBuilders;
@@ -719,6 +720,7 @@ public class WireMockAdminApiTests
var guid1 = Guid.Parse("90356dba-b36c-469a-a17e-669cd84f1f05");
var guid2 = Guid.Parse("1b731398-4a5b-457f-a6e3-d65e541c428f");
var guid3 = Guid.Parse("f74fd144-df53-404f-8e35-da22a640bd5f");
var guid4 = Guid.Parse("4126DEC8-470B-4EFF-93BB-C24F83B8B1FD");
var server = WireMockServer.StartWithAdminInterface();
server
@@ -762,14 +764,32 @@ public class WireMockAdminApiTests
.RespondWith(
Response.Create()
.WithStatusCode(HttpStatusCode.AlreadyReported)
.WithBodyAsJson(new { a = 1, b=1.2, d=true, e=false, f=new[]{1,2,3,4}, g= new{z1=1, z2=2, z3=new []{"a","b","c"}, z4=new[]{new {a=1, b=2},new {a=2, b=3}}} })
.WithBodyAsJson(new { @as = 1, b=1.2, d=true, e=false, f=new[]{1,2,3,4}, g= new{z1=1, z2=2, z3=new []{"a","b","c"}, z4=new[]{new {a=1, b=2},new {a=2, b=3}}}, date_field = new DateTime(2023,05,08,11,20,19), string_field_with_date="2021-03-13T21:04:00Z", multiline_text= @"This
is
multiline
text
" })
);
server
.Given(
Request.Create()
.WithPath("/foo3")
.WithBody(new JsonPartialMatcher(new { a=1, b=2}))
.UsingPost()
)
.WithGuid(guid4)
.RespondWith(
Response.Create()
.WithStatusCode(200)
.WithBody("Line1\r\nSome \"value\" in Line2")
);
// Act
var api = RestClient.For<IWireMockAdminApi>(server.Url);
var mappings = await api.GetMappingsAsync().ConfigureAwait(false);
mappings.Should().HaveCount(3);
mappings.Should().HaveCount(4);
var code = await api.GetMappingsCodeAsync().ConfigureAwait(false);

View File

@@ -4,10 +4,13 @@ using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using FluentAssertions;
using Moq;
using WireMock.Logging;
using WireMock.Models;
using WireMock.RequestBuilders;
using WireMock.ResponseBuilders;
using WireMock.Server;
using WireMock.Settings;
using WireMock.Types;
using WireMock.Util;
using Xunit;
@@ -71,7 +74,7 @@ public class WireMockServerWebhookTests
// Assert
var response = await new HttpClient().SendAsync(request).ConfigureAwait(false);
string content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
response.StatusCode.Should().Be(HttpStatusCode.OK);
content.Should().Be("a-response");
@@ -120,7 +123,7 @@ public class WireMockServerWebhookTests
// Assert
var response = await new HttpClient().SendAsync(request).ConfigureAwait(false);
string content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
response.StatusCode.Should().Be(HttpStatusCode.OK);
content.Should().Be("a-response");
@@ -132,6 +135,115 @@ public class WireMockServerWebhookTests
serverReceivingTheWebhook.Dispose();
}
[Fact]
public async Task WireMockServer_WithWebhook_When_WebhookEndPointReturnsError_Should_LogWarning()
{
// Arrange
var serverReceivingTheWebhook = WireMockServer.Start();
serverReceivingTheWebhook.Given(Request.Create().WithPath("/x").UsingPost()).RespondWith(Response.Create().WithBody("!Server Error!").WithStatusCode(500));
var loggerMock = new Mock<IWireMockLogger>();
var settings = new WireMockServerSettings
{
Logger = loggerMock.Object
};
// Act
var guid = "942cb963-c9a3-4e9c-8e71-c1b26d2a4a05";
var server = WireMockServer.Start(settings);
server.Given(Request.Create().UsingPost())
.WithWebhook(new Webhook
{
Request = new WebhookRequest
{
Url = serverReceivingTheWebhook.Url! + "/{{request.Query.q}}",
Method = "post",
BodyData = new BodyData
{
BodyAsString = "abc",
DetectedBodyType = BodyType.String,
DetectedBodyTypeFromContentType = BodyType.String
},
UseTransformer = true
}
})
.WithGuid(guid)
.RespondWith(Response.Create().WithBody("a-response"));
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri($"{server.Urls[0]}/TST?q=x"),
Content = new StringContent("test")
};
// Assert
var response = await new HttpClient().SendAsync(request).ConfigureAwait(false);
var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
response.StatusCode.Should().Be(HttpStatusCode.OK);
content.Should().Be("a-response");
loggerMock.Verify(l => l.Warn("Sending message to Webhook [0] from Mapping '942cb963-c9a3-4e9c-8e71-c1b26d2a4a05' failed. HttpStatusCode: InternalServerError Content: !Server Error!"));
serverReceivingTheWebhook.LogEntries.Should().HaveCount(1);
serverReceivingTheWebhook.LogEntries.First().MappingGuid.Should().NotBeNull();
server.Dispose();
serverReceivingTheWebhook.Dispose();
}
[Fact]
public async Task WireMockServer_WithWebhook_When_WebhookEndPointDoesNotExists_Should_LogError()
{
// Arrange
var loggerMock = new Mock<IWireMockLogger>();
var settings = new WireMockServerSettings
{
Logger = loggerMock.Object
};
// Act
var guid = "942cb963-c9a3-4e9c-8e71-c1b26d2a4a05";
var server = WireMockServer.Start(settings);
server.Given(Request.Create().UsingPost())
.WithWebhook(new Webhook
{
Request = new WebhookRequest
{
Url = "http://error-not-does-exist-" + Guid.NewGuid(),
Method = "post",
BodyData = new BodyData
{
BodyAsString = "abc",
DetectedBodyType = BodyType.String,
DetectedBodyTypeFromContentType = BodyType.String
},
UseTransformer = true
}
})
.WithGuid(guid)
.RespondWith(Response.Create().WithBody("a-response"));
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri(server.Urls[0]),
Content = new StringContent("test")
};
// Assert
var response = await new HttpClient().SendAsync(request).ConfigureAwait(false);
var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
response.StatusCode.Should().Be(HttpStatusCode.OK);
content.Should().Be("a-response");
loggerMock.Verify(l => l.Error(It.Is<string>(formatString => formatString.Contains("Sending message to Webhook [0] from Mapping '942cb963-c9a3-4e9c-8e71-c1b26d2a4a05' failed. Exception"))));
server.Dispose();
}
[Fact]
public async Task WireMockServer_WithWebhookArgs_Should_Send_StringMessage_To_Webhook()
{
@@ -142,7 +254,7 @@ public class WireMockServerWebhookTests
// Act
var server = WireMockServer.Start();
server.Given(Request.Create().UsingPost())
.WithWebhook(serverReceivingTheWebhook.Urls[0], "post", null, "OK !", true, TransformerType.Handlebars)
.WithWebhook(serverReceivingTheWebhook.Urls[0], "post", null, "OK !")
.RespondWith(Response.Create().WithBody("a-response"));
var request = new HttpRequestMessage
@@ -154,7 +266,7 @@ public class WireMockServerWebhookTests
// Assert
var response = await new HttpClient().SendAsync(request).ConfigureAwait(false);
string content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
response.StatusCode.Should().Be(HttpStatusCode.OK);
content.Should().Be("a-response");
@@ -176,7 +288,7 @@ public class WireMockServerWebhookTests
// Act
var server = WireMockServer.Start();
server.Given(Request.Create().UsingPost())
.WithWebhook(serverReceivingTheWebhook.Urls[0], "post", null, new { Status = "OK" }, true, TransformerType.Handlebars)
.WithWebhook(serverReceivingTheWebhook.Urls[0], "post", null, new { Status = "OK" })
.RespondWith(Response.Create().WithBody("a-response"));
var request = new HttpRequestMessage
@@ -188,7 +300,7 @@ public class WireMockServerWebhookTests
// Assert
var response = await new HttpClient().SendAsync(request).ConfigureAwait(false);
string content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
response.StatusCode.Should().Be(HttpStatusCode.OK);
content.Should().Be("a-response");