This commit is contained in:
Stef Heyenrath
2025-08-31 09:21:08 +02:00
58 changed files with 345 additions and 214 deletions

View File

@@ -47,5 +47,5 @@ public class LogRequestMatchModel
/// <value>
/// The match details.
/// </value>
public IList<object> MatchDetails { get; set; }
public IList<object> MatchDetails { get; set; } = [];
}

View File

@@ -33,7 +33,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AwesomeAssertions" Version="9.0.0" />
<PackageReference Include="AwesomeAssertions" Version="9.1.0" />
</ItemGroup>
<ItemGroup>

View File

@@ -25,7 +25,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="JsonConverter.Newtonsoft.Json" Version="0.7.0" />
<PackageReference Include="JsonConverter.Newtonsoft.Json" Version="0.7.2" />
</ItemGroup>
<ItemGroup>

View File

@@ -1,7 +1,6 @@
// Copyright © WireMock.Net
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
@@ -33,16 +32,25 @@ internal class MimeKitUtils : IMimeKitUtils
StartsWithMultiPart(contentTypeHeader)
)
{
var bytes = requestMessage.BodyData?.DetectedBodyType switch
byte[] bytes;
switch (requestMessage.BodyData?.DetectedBodyType)
{
// If the body is bytes, use the BodyAsBytes to match on.
BodyType.Bytes => requestMessage.BodyData.BodyAsBytes!,
case BodyType.Bytes:
bytes = requestMessage.BodyData.BodyAsBytes!;
break;
// If the body is a String or MultiPart, use the BodyAsString to match on.
BodyType.String or BodyType.MultiPart => Encoding.UTF8.GetBytes(requestMessage.BodyData.BodyAsString!),
case BodyType.String or BodyType.MultiPart:
bytes = Encoding.UTF8.GetBytes(requestMessage.BodyData.BodyAsString!);
break;
_ => throw new NotSupportedException()
};
// Else return false.
default:
mimeMessageData = null;
return false;
}
var fixedBytes = FixBytes(bytes, contentTypeHeader[0]);

View File

@@ -12,7 +12,7 @@ namespace WireMock.Matchers.Request;
/// </summary>
public class RequestMessageMultiPartMatcher : IRequestMatcher
{
private static readonly IMimeKitUtils MimeKitUtils = TypeLoader.LoadStaticInstance<IMimeKitUtils>();
private readonly IMimeKitUtils _mimeKitUtils = LoadMimeKitUtils();
/// <summary>
/// The matchers.
@@ -62,7 +62,7 @@ public class RequestMessageMultiPartMatcher : IRequestMatcher
return requestMatchResult.AddScore(GetType(), score, null);
}
if (!MimeKitUtils.TryGetMimeMessage(requestMessage, out var message))
if (!_mimeKitUtils.TryGetMimeMessage(requestMessage, out var message))
{
return requestMatchResult.AddScore(GetType(), score, null);
}
@@ -96,4 +96,14 @@ public class RequestMessageMultiPartMatcher : IRequestMatcher
return requestMatchResult.AddScore(GetType(), score, exception);
}
private static IMimeKitUtils LoadMimeKitUtils()
{
if (TypeLoader.TryLoadStaticInstance<IMimeKitUtils>(out var mimeKitUtils))
{
return mimeKitUtils;
}
throw new InvalidOperationException("MimeKit is required for RequestMessageMultiPartMatcher. Please install the WireMock.Net.MimePart package.");
}
}

View File

@@ -179,9 +179,12 @@ namespace WireMock.Owin.Mappers
return (bodyData.Encoding ?? _utf8NoBom).GetBytes(jsonBody);
case BodyType.ProtoBuf:
var protoDefinitions = bodyData.ProtoDefinition?.Invoke().Texts;
var protoBufUtils = TypeLoader.LoadStaticInstance<IProtoBufUtils>();
return await protoBufUtils.GetProtoBufMessageWithHeaderAsync(protoDefinitions, bodyData.ProtoBufMessageType, bodyData.BodyAsJson).ConfigureAwait(false);
if (TypeLoader.TryLoadStaticInstance<IProtoBufUtils>(out var protoBufUtils))
{
var protoDefinitions = bodyData.ProtoDefinition?.Invoke().Texts;
return await protoBufUtils.GetProtoBufMessageWithHeaderAsync(protoDefinitions, bodyData.ProtoBufMessageType, bodyData.BodyAsJson).ConfigureAwait(false);
}
break;
case BodyType.Bytes:
return bodyData.BodyAsBytes;

View File

@@ -184,16 +184,9 @@ public class RequestMessage : IRequestMessage
//#endif
#if MIMEKIT
try
if (TypeLoader.TryLoadStaticInstance<IMimeKitUtils>(out var mimeKitUtils) && mimeKitUtils.TryGetMimeMessage(this, out var mimeMessage))
{
if (TypeLoader.LoadStaticInstance<IMimeKitUtils>().TryGetMimeMessage(this, out var mimeMessage))
{
BodyAsMimeMessage = mimeMessage;
}
}
catch
{
// Ignore exception from MimeMessage.Load
BodyAsMimeMessage = mimeMessage;
}
#endif
}

View File

@@ -55,7 +55,12 @@ internal class MatcherMapper
case "CSharpCodeMatcher":
if (_settings.AllowCSharpCodeMatcher == true)
{
return TypeLoader.LoadNewInstance<ICSharpCodeMatcher>(matchBehaviour, matchOperator, stringPatterns);
if (TypeLoader.TryLoadNewInstance<ICSharpCodeMatcher>(out var csharpCodeMatcher, matchBehaviour, matchOperator, stringPatterns))
{
return csharpCodeMatcher;
}
throw new InvalidOperationException("The 'CSharpCodeMatcher' cannot be loaded. Please install the WireMock.Net.Matchers.CSharpCode package.");
}
throw new NotSupportedException("It's not allowed to use the 'CSharpCodeMatcher' because WireMockServerSettings.AllowCSharpCodeMatcher is not set to 'true'.");
@@ -75,7 +80,12 @@ internal class MatcherMapper
case "GraphQLMatcher":
var patternAsString = stringPatterns[0].GetPattern();
var schema = new AnyOf<string, StringPattern, ISchemaData>(patternAsString);
return TypeLoader.LoadNewInstance<IGraphQLMatcher>(schema, matcherModel.CustomScalars, matchBehaviour, matchOperator);
if (TypeLoader.TryLoadNewInstance<IGraphQLMatcher>(out var graphQLMatcher, schema, matcherModel.CustomScalars, matchBehaviour, matchOperator))
{
return graphQLMatcher;
}
throw new InvalidOperationException("The 'GraphQLMatcher' cannot be loaded. Please install the WireMock.Net.GraphQL package.");
case "MimePartMatcher":
return CreateMimePartMatcher(matchBehaviour, matcherModel);
@@ -282,18 +292,34 @@ internal class MatcherMapper
var contentTransferEncodingMatcher = Map(matcher.ContentTransferEncodingMatcher) as IStringMatcher;
var contentMatcher = Map(matcher.ContentMatcher);
return TypeLoader.LoadNewInstance<IMimePartMatcher>(matchBehaviour, contentTypeMatcher, contentDispositionMatcher, contentTransferEncodingMatcher, contentMatcher);
if (TypeLoader.TryLoadNewInstance<IMimePartMatcher>(
out var mimePartMatcher,
matchBehaviour,
contentTypeMatcher,
contentDispositionMatcher,
contentTransferEncodingMatcher,
contentMatcher))
{
return mimePartMatcher;
}
throw new InvalidOperationException("The 'MimePartMatcher' cannot be loaded. Please install the WireMock.Net.MimePart package.");
}
private IProtoBufMatcher CreateProtoBufMatcher(MatchBehaviour? matchBehaviour, IReadOnlyList<string> protoDefinitions, MatcherModel matcher)
{
var objectMatcher = Map(matcher.ContentMatcher) as IObjectMatcher;
return TypeLoader.LoadNewInstance<IProtoBufMatcher>(
if (TypeLoader.TryLoadNewInstance<IProtoBufMatcher>(
out var protobufMatcher,
() => ProtoDefinitionUtils.GetIdOrTexts(_settings, protoDefinitions.ToArray()),
matcher.ProtoBufMessageType!,
matchBehaviour ?? MatchBehaviour.AcceptOnMatch,
objectMatcher
);
objectMatcher))
{
return protobufMatcher;
}
throw new InvalidOperationException("The 'ProtoBufMatcher' cannot be loaded. Please install the WireMock.Net.ProtoBuf package.");
}
}

View File

@@ -366,10 +366,8 @@ public partial class WireMockServer
}
else if (responseModel.BodyAsJson != null)
{
if (responseModel.ProtoBufMessageType != null)
if (responseModel.ProtoBufMessageType != null && TypeLoader.TryLoadStaticInstance<IProtoBufUtils>(out var protoBufUtils))
{
var protoBufUtils = TypeLoader.LoadStaticInstance<IProtoBufUtils>();
if (responseModel.ProtoDefinition != null)
{
responseBuilder = protoBufUtils.UpdateResponseBuilder(responseBuilder, responseModel.ProtoBufMessageType, responseModel.BodyAsJson, responseModel.ProtoDefinition);

View File

@@ -100,7 +100,10 @@ public class RequestMessageGraphQLMatcher : IRequestMatcher
IDictionary<string, Type>? customScalars
)
{
var graphQLMatcher = TypeLoader.LoadNewInstance<IGraphQLMatcher>(schema, customScalars, matchBehaviour, MatchOperator.Or);
return [graphQLMatcher];
if (TypeLoader.TryLoadNewInstance<IGraphQLMatcher>(out var graphQLMatcher, schema, customScalars, matchBehaviour, MatchOperator.Or))
{
return [graphQLMatcher];
}
return [];
}
}

View File

@@ -25,7 +25,10 @@ public class RequestMessageProtoBufMatcher : IRequestMatcher
/// <param name="matcher">The optional matcher to use to match the ProtoBuf as (json) object.</param>
public RequestMessageProtoBufMatcher(MatchBehaviour matchBehaviour, Func<IdOrTexts> protoDefinition, string messageType, IObjectMatcher? matcher = null)
{
Matcher = TypeLoader.LoadNewInstance<IProtoBufMatcher>(protoDefinition, messageType, matchBehaviour, matcher);
if (TypeLoader.TryLoadNewInstance<IProtoBufMatcher>(out var protoBufMatcher, protoDefinition, messageType, matchBehaviour, matcher))
{
Matcher = protoBufMatcher;
}
}
/// <inheritdoc />

View File

@@ -14,68 +14,130 @@ internal static class TypeLoader
{
private static readonly ConcurrentDictionary<string, Type> Assemblies = new();
private static readonly ConcurrentDictionary<Type, object> Instances = new();
private static readonly ConcurrentBag<(string FullName, Type Type)> InstancesWhichCannotBeFoundByFullName = [];
private static readonly ConcurrentBag<(string FullName, Type Type)> StaticInstancesWhichCannotBeFoundByFullName = [];
private static readonly ConcurrentBag<Type> InstancesWhichCannotBeFound = [];
private static readonly ConcurrentBag<Type> StaticInstancesWhichCannotBeFound = [];
public static TInterface LoadNewInstance<TInterface>(params object?[] args) where TInterface : class
public static bool TryLoadNewInstance<TInterface>([NotNullWhen(true)] out TInterface? instance, params object?[] args) where TInterface : class
{
var pluginType = GetPluginType<TInterface>();
var type = typeof(TInterface);
if (InstancesWhichCannotBeFound.Contains(type))
{
instance = null;
return false;
}
return (TInterface)Activator.CreateInstance(pluginType, args)!;
if (TryGetPluginType<TInterface>(out var pluginType))
{
instance = (TInterface)Activator.CreateInstance(pluginType, args)!;
return true;
}
InstancesWhichCannotBeFound.Add(type);
instance = null;
return false;
}
public static TInterface LoadStaticInstance<TInterface>(params object?[] args) where TInterface : class
public static bool TryLoadStaticInstance<TInterface>([NotNullWhen(true)] out TInterface? staticInstance, params object?[] args) where TInterface : class
{
var pluginType = GetPluginType<TInterface>();
var type = typeof(TInterface);
if (StaticInstancesWhichCannotBeFound.Contains(type))
{
staticInstance = null;
return false;
}
return (TInterface)Instances.GetOrAdd(pluginType, key => Activator.CreateInstance(key, args)!);
if (TryGetPluginType<TInterface>(out var pluginType))
{
staticInstance = (TInterface)Instances.GetOrAdd(pluginType, key => Activator.CreateInstance(key, args)!);
return true;
}
StaticInstancesWhichCannotBeFound.Add(type);
staticInstance = null;
return false;
}
public static TInterface LoadNewInstanceByFullName<TInterface>(string implementationTypeFullName, params object?[] args) where TInterface : class
public static bool TryLoadNewInstanceByFullName<TInterface>([NotNullWhen(true)] out TInterface? instance, string implementationTypeFullName, params object?[] args) where TInterface : class
{
Guard.NotNullOrEmpty(implementationTypeFullName);
var pluginType = GetPluginTypeByFullName<TInterface>(implementationTypeFullName);
var type = typeof(TInterface);
if (InstancesWhichCannotBeFoundByFullName.Contains((implementationTypeFullName, type)))
{
instance = null;
return false;
}
return (TInterface)Activator.CreateInstance(pluginType, args)!;
if (TryGetPluginTypeByFullName<TInterface>(implementationTypeFullName, out var pluginType))
{
instance = (TInterface)Activator.CreateInstance(pluginType, args)!;
return true;
}
InstancesWhichCannotBeFoundByFullName.Add((implementationTypeFullName, type));
instance = null;
return false;
}
public static TInterface LoadStaticInstanceByFullName<TInterface>(string implementationTypeFullName, params object?[] args) where TInterface : class
public static bool TryLoadStaticInstanceByFullName<TInterface>([NotNullWhen(true)] out TInterface? staticInstance, string implementationTypeFullName, params object?[] args) where TInterface : class
{
Guard.NotNullOrEmpty(implementationTypeFullName);
var pluginType = GetPluginTypeByFullName<TInterface>(implementationTypeFullName);
var type = typeof(TInterface);
if (StaticInstancesWhichCannotBeFoundByFullName.Contains((implementationTypeFullName, type)))
{
staticInstance = null;
return false;
}
return (TInterface)Instances.GetOrAdd(pluginType, key => Activator.CreateInstance(key, args)!);
if (TryGetPluginTypeByFullName<TInterface>(implementationTypeFullName, out var pluginType))
{
staticInstance = (TInterface)Instances.GetOrAdd(pluginType, key => Activator.CreateInstance(key, args)!);
return true;
}
StaticInstancesWhichCannotBeFoundByFullName.Add((implementationTypeFullName, type));
staticInstance = null;
return false;
}
private static Type GetPluginType<TInterface>() where TInterface : class
private static bool TryGetPluginType<TInterface>([NotNullWhen(true)] out Type? foundType) where TInterface : class
{
var key = typeof(TInterface).FullName!;
return Assemblies.GetOrAdd(key, _ =>
if (Assemblies.TryGetValue(key, out foundType))
{
if (TryFindTypeInDlls<TInterface>(null, out var foundType))
{
return foundType;
}
return true;
}
throw new DllNotFoundException($"No dll found which implements interface '{key}'.");
});
if (TryFindTypeInDlls<TInterface>(null, out foundType))
{
Assemblies.TryAdd(key, foundType);
return true;
}
return false;
}
private static Type GetPluginTypeByFullName<TInterface>(string implementationTypeFullName) where TInterface : class
private static bool TryGetPluginTypeByFullName<TInterface>(string implementationTypeFullName, [NotNullWhen(true)] out Type? foundType) where TInterface : class
{
var @interface = typeof(TInterface).FullName;
var key = $"{@interface}_{implementationTypeFullName}";
return Assemblies.GetOrAdd(key, _ =>
if (Assemblies.TryGetValue(key, out foundType))
{
if (TryFindTypeInDlls<TInterface>(implementationTypeFullName, out var foundType))
{
return foundType;
}
return true;
}
throw new DllNotFoundException($"No dll found which implements Interface '{@interface}' and has FullName '{implementationTypeFullName}'.");
});
if (TryFindTypeInDlls<TInterface>(implementationTypeFullName, out foundType))
{
Assemblies.TryAdd(key, foundType);
return true;
}
return false;
}
private static bool TryFindTypeInDlls<TInterface>(string? implementationTypeFullName, [NotNullWhen(true)] out Type? pluginType) where TInterface : class

View File

@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<Description>A fluent testcontainer builder for the Docker version of WireMock.Net</Description>
@@ -39,7 +39,7 @@
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Stef.Validation" Version="0.2.0" />
<PackageReference Include="Testcontainers" Version="4.5.0" />
<PackageReference Include="Testcontainers" Version="4.7.0" />
</ItemGroup>
<ItemGroup>

View File

@@ -27,7 +27,7 @@
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Stef.Validation" Version="0.1.1" />
<PackageReference Include="Stef.Validation" Version="0.2.0" />
<PackageReference Include="xUnit.abstractions" Version="2.0.3" />
</ItemGroup>

View File

@@ -34,7 +34,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AnyOf" Version="0.4.0" />
<PackageReference Include="AnyOf" Version="0.5.0.1" />
<PackageReference Include="RestEase" Version="1.6.4" />
</ItemGroup>

View File

@@ -0,0 +1,19 @@
// Copyright © WireMock.Net
using System.Text.Json.Serialization;
using WireMock.Admin.Mappings;
using WireMock.Admin.Requests;
using WireMock.Types;
namespace WireMock.Net.Json;
[JsonSourceGenerationOptions(WriteIndented = true)]
[JsonSerializable(typeof(EncodingModel))]
[JsonSerializable(typeof(LogEntryModel))]
[JsonSerializable(typeof(LogRequestModel))]
[JsonSerializable(typeof(LogResponseModel))]
[JsonSerializable(typeof(LogRequestMatchModel))]
[JsonSerializable(typeof(WireMockList<string>))]
internal partial class SourceGenerationContext : JsonSerializerContext
{
}

View File

@@ -5,6 +5,7 @@ using System.Text.Json;
using Microsoft.Extensions.Logging;
using WireMock.Admin.Requests;
using WireMock.Logging;
using WireMock.Net.Json;
namespace WireMock.Net;
@@ -55,7 +56,7 @@ public class WireMockLogger : IWireMockLogger
/// <see cref="IWireMockLogger.DebugRequestResponse"/>
public void DebugRequestResponse(LogEntryModel logEntryModel, bool isAdminRequest)
{
string message = JsonSerializer.Serialize(logEntryModel, _options);
string message = JsonSerializer.Serialize(logEntryModel, SourceGenerationContext.Default.LogEntryModel);
_logger.LogDebug("Admin[{IsAdmin}] {Message}", isAdminRequest, message);
}

View File

@@ -1,27 +1,27 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<PackAsTool>true</PackAsTool>
<ToolCommandName>dotnet-wiremock</ToolCommandName>
<Description>A dotnet commandline tool for WireMock.Net (A Lightweight Http Mocking Server for .NET)</Description>
<PackageTags>tdd;mock;http;wiremock;test;server;unittest;dotnet;tool;dotnet-tool</PackageTags>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<Authors>Stef Heyenrath</Authors>
</PropertyGroup>
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<PackAsTool>true</PackAsTool>
<RootNamespace>WireMock.Net</RootNamespace>
<ToolCommandName>dotnet-wiremock</ToolCommandName>
<Description>A dotnet commandline tool for WireMock.Net (A Lightweight Http Mocking Server for .NET)</Description>
<PackageTags>tdd;mock;http;wiremock;test;server;unittest;dotnet;tool;dotnet-tool</PackageTags>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<Authors>Stef Heyenrath</Authors>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)' == 'Release'">
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)' == 'Release'">
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="8.0.0" />
<PackageReference Include="System.Text.Json" Version="8.0.5" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="8.0.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\WireMock.Net.StandAlone\WireMock.Net.StandAlone.csproj" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\WireMock.Net.StandAlone\WireMock.Net.StandAlone.csproj" />
</ItemGroup>
</Project>