This commit is contained in:
Stef Heyenrath
2026-04-30 20:33:45 +02:00
parent 1e07f3f7f3
commit d0f9136570
6 changed files with 49 additions and 36 deletions

View File

@@ -2,8 +2,10 @@
using System.Text;
using JsonConverter.Abstractions;
using JsonConverter.Newtonsoft.Json;
using Stef.Validation;
using WireMock.Models;
using WireMock.Serialization;
using WireMock.Types;
using WireMock.Util;
@@ -119,11 +121,13 @@ public partial class Response
}
/// <inheritdoc />
public IResponseBuilder WithBody(string body, string? destination = BodyDestinationFormat.SameAsSource, Encoding? encoding = null)
public IResponseBuilder WithBody(string body, string? destination = BodyDestinationFormat.SameAsSource, Encoding? encoding = null, IJsonConverter? jsonConverter = null, JsonConverterOptions? options = null)
{
Guard.NotNull(body);
encoding ??= Encoding.UTF8;
jsonConverter ??= new NewtonsoftJsonConverter();
options ??= JsonSerializationConstants.JsonConverterOptionsWithDateParsingNone;
ResponseMessage.BodyDestination = destination;
ResponseMessage.BodyData = new BodyData
@@ -140,7 +144,7 @@ public partial class Response
case BodyDestinationFormat.Json:
ResponseMessage.BodyData.DetectedBodyType = BodyType.Json;
ResponseMessage.BodyData.BodyAsJson = JsonUtils.DeserializeObject(body);
ResponseMessage.BodyData.BodyAsJson = jsonConverter.Deserialize<object>(body, options);
break;
default:

View File

@@ -3,14 +3,15 @@
using System.Collections;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using JetBrains.Annotations;
using JsonConverter.Newtonsoft.Json;
using JsonConverter.System.Text.Json;
using Stef.Validation;
using WireMock.Constants;
using WireMock.Logging;
using WireMock.Models;
using WireMock.Types;
using WireMock.Transformers;
using WireMock.Types;
using WireMock.Util;
namespace WireMock.Settings;
@@ -58,11 +59,9 @@ public static class WireMockServerSettingsParser
DisableRequestBodyDecompressing = parser.GetBoolValue(nameof(WireMockServerSettings.DisableRequestBodyDecompressing)),
DisableDeserializeFormUrlEncoded = parser.GetBoolValue(nameof(WireMockServerSettings.DisableDeserializeFormUrlEncoded)),
DoNotSaveDynamicResponseInLogEntry = parser.GetBoolValue(nameof(WireMockServerSettings.DoNotSaveDynamicResponseInLogEntry)),
GraphQLSchemas = parser.GetObjectValueFromJson<Dictionary<string, GraphQLSchemaDetails>>(nameof(settings.GraphQLSchemas)),
HandleRequestsSynchronously = parser.GetBoolValue(nameof(WireMockServerSettings.HandleRequestsSynchronously)),
HostingScheme = parser.GetEnumValue<HostingScheme>(nameof(WireMockServerSettings.HostingScheme)),
MaxRequestLogCount = parser.GetIntValue(nameof(WireMockServerSettings.MaxRequestLogCount)),
ProtoDefinitions = parser.GetObjectValueFromJson<Dictionary<string, string[]>>(nameof(settings.ProtoDefinitions)),
QueryParameterMultipleValueSupport = parser.GetEnumValue<QueryParameterMultipleValueSupport>(nameof(WireMockServerSettings.QueryParameterMultipleValueSupport)),
ReadStaticMappings = parser.GetBoolValue(nameof(WireMockServerSettings.ReadStaticMappings)),
RequestLogExpirationDuration = parser.GetIntValue(nameof(WireMockServerSettings.RequestLogExpirationDuration)),
@@ -75,14 +74,13 @@ public static class WireMockServerSettingsParser
WatchStaticMappingsInSubdirectories = parser.GetBoolValue(nameof(WireMockServerSettings.WatchStaticMappingsInSubdirectories)),
};
settings.DefaultJsonBodyTransformer = new NewtonsoftJsonBodyTransformer(settings);
#if USE_ASPNETCORE
settings.CorsPolicyOptions = parser.GetEnumValue(nameof(WireMockServerSettings.CorsPolicyOptions), CorsPolicyOptions.None);
settings.ClientCertificateMode = parser.GetEnumValue(nameof(WireMockServerSettings.ClientCertificateMode), ClientCertificateMode.NoCertificate);
settings.AcceptAnyClientCertificate = parser.GetBoolValue(nameof(WireMockServerSettings.AcceptAnyClientCertificate));
#endif
ParseJsonSerializerSettings(settings, parser);
ParseLoggerSettings(settings, logger, parser);
ParsePortSettings(settings, parser);
ParseProxyAndRecordSettings(settings, parser);
@@ -91,6 +89,9 @@ public static class WireMockServerSettingsParser
ParseActivityTracingSettings(settings, parser);
ParseWebSocketSettings(settings, parser);
settings.GraphQLSchemas = parser.GetObjectValueFromJson<Dictionary<string, GraphQLSchemaDetails>>(nameof(settings.GraphQLSchemas), settings.DefaultJsonSerializer);
settings.ProtoDefinitions = parser.GetObjectValueFromJson<Dictionary<string, string[]>>(nameof(settings.ProtoDefinitions), settings.DefaultJsonSerializer);
return true;
}
@@ -262,4 +263,21 @@ public static class WireMockServerSettingsParser
};
}
}
private static void ParseJsonSerializerSettings(WireMockServerSettings settings, SimpleSettingsParser parser)
{
var defaultJsonSerializer = parser.GetStringValue(nameof(WireMockServerSettings.DefaultJsonSerializer));
settings.DefaultJsonSerializer = defaultJsonSerializer switch
{
nameof(SystemTextJsonConverter) => new SystemTextJsonConverter(),
_ => new NewtonsoftJsonConverter(),
};
var defaultJsonBodyTransformer = parser.GetStringValue(nameof(WireMockServerSettings.DefaultJsonBodyTransformer));
settings.DefaultJsonBodyTransformer = defaultJsonBodyTransformer switch
{
nameof(SystemTextJsonBodyTransformer) => new SystemTextJsonBodyTransformer(),
_ => new NewtonsoftJsonBodyTransformer(settings),
};
}
}

View File

@@ -1,8 +1,6 @@
// Copyright © WireMock.Net
using System;
using System.Text;
using System.Threading.Tasks;
using JsonConverter.Abstractions;
using WireMock.Models;
@@ -19,8 +17,10 @@ public interface IBodyResponseBuilder : IFaultResponseBuilder
/// <param name="body">The body.</param>
/// <param name="destination">The Body Destination format (SameAsSource, String or Bytes).</param>
/// <param name="encoding">The body encoding.</param>
/// <param name="jsonConverter">The JSON converter.</param>
/// <param name="options">The JSON converter options.</param>
/// <returns>A <see cref="IResponseBuilder"/>.</returns>
IResponseBuilder WithBody(string body, string? destination = BodyDestinationFormat.SameAsSource, Encoding? encoding = null);
IResponseBuilder WithBody(string body, string? destination = BodyDestinationFormat.SameAsSource, Encoding? encoding = null, IJsonConverter? jsonConverter = null, JsonConverterOptions? options = null);
/// <summary>
/// WithBody : Create a ... response based on a callback function.

View File

@@ -1,6 +1,7 @@
// Copyright © WireMock.Net
using System.Collections;
using JsonConverter.Abstractions;
using WireMock.Extensions;
using WireMock.Util;
@@ -191,9 +192,9 @@ internal class SimpleSettingsParser
return GetValue(name, values => values.FirstOrDefault());
}
public T? GetObjectValueFromJson<T>(string name)
public T? GetObjectValueFromJson<T>(string name, IJsonConverter jsonConverter)
{
var value = GetValue(name, values => values.FirstOrDefault());
return string.IsNullOrWhiteSpace(value) ? default : JsonUtils.DeserializeObject<T>(value!);
return string.IsNullOrWhiteSpace(value) ? default : jsonConverter.Deserialize<T>(value!);
}
}

View File

@@ -60,17 +60,6 @@ internal static class JsonUtils
return JsonConvert.DeserializeObject(json, JsonSerializationConstants.JsonDeserializerSettingsWithDateParsingNone)!;
}
/// <summary>
/// Deserializes the JSON to the specified .NET type.
/// Using : DateParseHandling = DateParseHandling.None
/// </summary>
/// <param name="json">A System.String that contains JSON.</param>
/// <returns>The deserialized object from the JSON string.</returns>
public static T DeserializeObject<T>(string json)
{
return JsonConvert.DeserializeObject<T>(json, JsonSerializationConstants.JsonDeserializerSettingsWithDateParsingNone)!;
}
public static T? TryDeserializeObject<T>(string json)
{
try

View File

@@ -1,5 +1,6 @@
// Copyright © WireMock.Net
using JsonConverter.Newtonsoft.Json;
using WireMock.Settings;
using WireMock.Types;
@@ -18,7 +19,7 @@ public class SimpleSettingsParserTests
public void SimpleCommandLineParser_Parse_Arguments()
{
// Assign
_parser.Parse(new[] { "--test1", "one", "--test2", "2", "--test3", "3", "--test4", "true", "--test5", "Https" });
_parser.Parse(["--test1", "one", "--test2", "2", "--test3", "3", "--test4", "true", "--test5", "Https"]);
// Act
string? stringValue = _parser.GetStringValue("test1");
@@ -46,7 +47,7 @@ public class SimpleSettingsParserTests
{ "WireMockServerSettings__test1", "one" },
{ "WireMockServerSettings__test2", "two" }
};
_parser.Parse(new string[0], env);
_parser.Parse([], env);
// Act
string? value1 = _parser.GetStringValue("test1");
@@ -61,7 +62,7 @@ public class SimpleSettingsParserTests
public void SimpleCommandLineParser_Parse_ArgumentsAsCombinedKeyAndValue()
{
// Assign
_parser.Parse(new[] { "--test1 one", "--test2 two", "--test3 three" });
_parser.Parse(["--test1 one", "--test2 two", "--test3 three"]);
// Act
string? value1 = _parser.GetStringValue("test1");
@@ -78,7 +79,7 @@ public class SimpleSettingsParserTests
public void SimpleCommandLineParser_Parse_ArgumentsMixed()
{
// Assign
_parser.Parse(new[] { "--test1 one", "--test2", "two", "--test3 three" });
_parser.Parse(["--test1 one", "--test2", "two", "--test3 three"]);
// Act
string? value1 = _parser.GetStringValue("test1");
@@ -95,7 +96,7 @@ public class SimpleSettingsParserTests
public void SimpleCommandLineParser_Parse_GetBoolValue()
{
// Assign
_parser.Parse(new[] { "'--test1", "false'", "--test2 true" });
_parser.Parse(["'--test1", "false'", "--test2 true"]);
// Act
bool value1 = _parser.GetBoolValue("test1");
@@ -112,7 +113,7 @@ public class SimpleSettingsParserTests
public void SimpleCommandLineParser_Parse_GetBoolWithDefault()
{
// Assign
_parser.Parse(new[] { "--test1", "true", "--test2", "false" });
_parser.Parse(["--test1", "true", "--test2", "false"]);
// Act
bool value1 = _parser.GetBoolWithDefault("test1", "test1_fallback", defaultValue: false);
@@ -134,7 +135,7 @@ public class SimpleSettingsParserTests
{ "WireMockServerSettings__test1", "false" },
{ "WireMockServerSettings__test2", "true" }
};
_parser.Parse(new string[0], env);
_parser.Parse([], env);
// Act
bool value1 = _parser.GetBoolValue("test1");
@@ -151,7 +152,7 @@ public class SimpleSettingsParserTests
public void SimpleCommandLineParser_Parse_GetIntValue()
{
// Assign
_parser.Parse(new[] { "--test1", "42", "--test2 55" });
_parser.Parse(["--test1", "42", "--test2 55"]);
// Act
int? value1 = _parser.GetIntValue("test1");
@@ -175,7 +176,7 @@ public class SimpleSettingsParserTests
{ "WireMockServerSettings__test1", "42" },
{ "WireMockServerSETTINGS__TEST2", "55" }
};
_parser.Parse(new string[0], env);
_parser.Parse([], env);
// Act
int? value1 = _parser.GetIntValue("test1");
@@ -194,10 +195,10 @@ public class SimpleSettingsParserTests
public void SimpleCommandLineParser_Parse_GetObjectValueFromJson()
{
// Assign
_parser.Parse(new[] { @"--json {""k1"":""v1"",""k2"":""v2""}" });
_parser.Parse([@"--json {""k1"":""v1"",""k2"":""v2""}"]);
// Act
var value = _parser.GetObjectValueFromJson<Dictionary<string, string>>("json");
var value = _parser.GetObjectValueFromJson<Dictionary<string, string>>("json", new NewtonsoftJsonConverter());
// Assert
var expected = new Dictionary<string, string>
@@ -207,4 +208,4 @@ public class SimpleSettingsParserTests
};
value.Should().BeEquivalentTo(expected);
}
}
}