Compare commits

..

1 Commits

Author SHA1 Message Date
Stef Heyenrath
7880bfcc63 [WIP] - Riok.Mapperly 2024-08-15 13:51:44 +02:00
73 changed files with 520 additions and 1261 deletions

View File

@@ -1,28 +1,3 @@
# 1.6.3 (07 September 2024)
- [#1165](https://github.com/WireMock-Net/WireMock.Net/pull/1165) - Fix listen on AnyIP for url 0.0.0.0 contributed by [cocoon](https://github.com/cocoon)
- [#1154](https://github.com/WireMock-Net/WireMock.Net/issues/1154) - Listen on all ips [bug]
# 1.6.2 (04 September 2024)
- [#1152](https://github.com/WireMock-Net/WireMock.Net/pull/1152) - Update MappingConverter to correctly write the Matcher as C# code [bug] contributed by [StefH](https://github.com/StefH)
- [#1163](https://github.com/WireMock-Net/WireMock.Net/pull/1163) - Upgrade Aspire to version 8.2.0 [feature] contributed by [StefH](https://github.com/StefH)
- [#1166](https://github.com/WireMock-Net/WireMock.Net/pull/1166) - Also update IWireMockMiddlewareOptions when settings are updated via admin interface [bug] contributed by [StefH](https://github.com/StefH)
- [#1151](https://github.com/WireMock-Net/WireMock.Net/issues/1151) - MappingsToCSharpCode should use RegexMatcher when specified [bug]
- [#1164](https://github.com/WireMock-Net/WireMock.Net/issues/1164) - WithParam not working. [bug]
# 1.6.1 (22 August 2024)
- [#1160](https://github.com/WireMock-Net/WireMock.Net/pull/1160) - Use default timeout for Regex [bug] contributed by [StefH](https://github.com/StefH)
- [#1159](https://github.com/WireMock-Net/WireMock.Net/issues/1159) - RegexMatchTimeoutException when trying to parse HTTP version [bug]
# 1.6.0 (16 August 2024)
- [#1042](https://github.com/WireMock-Net/WireMock.Net/pull/1042) - Update + add fluent builder methods [feature] contributed by [StefH](https://github.com/StefH)
- [#1109](https://github.com/WireMock-Net/WireMock.Net/pull/1109) - Add Aspire Extension [feature] contributed by [StefH](https://github.com/StefH)
- [#1148](https://github.com/WireMock-Net/WireMock.Net/pull/1148) - Use Guid.TryParseExact with format "D" contributed by [StefH](https://github.com/StefH)
- [#1157](https://github.com/WireMock-Net/WireMock.Net/pull/1157) - Fix FormUrlEncodedMatcher (MatchOperator.And) [bug] contributed by [StefH](https://github.com/StefH)
- [#1158](https://github.com/WireMock-Net/WireMock.Net/pull/1158) - Allow setting Content-Length header on the response [feature] contributed by [StefH](https://github.com/StefH)
- [#720](https://github.com/WireMock-Net/WireMock.Net/issues/720) - Response Header Content-Length not available when call HEAD Method [feature]
- [#1145](https://github.com/WireMock-Net/WireMock.Net/issues/1145) - Response is auto converting string to guid [bug]
- [#1156](https://github.com/WireMock-Net/WireMock.Net/issues/1156) - FormUrlEncodedMatcher is not requiring to match all properties when MatchOperator.And [bug]
# 1.5.62 (27 July 2024)
- [#1147](https://github.com/WireMock-Net/WireMock.Net/pull/1147) - Add FormUrlEncodedMatcher [feature] contributed by [StefH](https://github.com/StefH)
- [#1143](https://github.com/WireMock-Net/WireMock.Net/issues/1143) - FormEncoded Request fails (404 Not Found) if key value pairs order in mapping is different from request body order [bug]

View File

@@ -4,7 +4,7 @@
</PropertyGroup>
<PropertyGroup>
<VersionPrefix>1.6.3</VersionPrefix>
<VersionPrefix>1.5.62</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.6.3
SET version=1.5.62
GitHubReleaseNotes --output CHANGELOG.md --skip-empty-releases --exclude-labels question invalid doc duplicate example environment --version %version% --token %GH_TOKEN%

View File

@@ -1,5 +1,5 @@
# 1.6.3 (07 September 2024)
- #1165 Fix listen on AnyIP for url 0.0.0.0
- #1154 Listen on all ips [bug]
# 1.5.62 (27 July 2024)
- #1147 Add FormUrlEncodedMatcher [feature]
- #1143 FormEncoded Request fails (404 Not Found) if key value pairs order in mapping is different from request body order [bug]
The full release notes can be found here: https://github.com/WireMock-Net/WireMock.Net/blob/master/CHANGELOG.md

View File

@@ -39,16 +39,16 @@ For more info, see also this WIKI page: [What is WireMock.Net](https://github.co
| | Official | Preview [:information_source:](https://github.com/WireMock-Net/WireMock.Net/wiki/MyGet-preview-versions) |
| - | - | - |
| &nbsp;&nbsp;**WireMock.Net** | [![NuGet Badge WireMock.Net](https://img.shields.io/nuget/v/WireMock.Net)](https://www.nuget.org/packages/WireMock.Net) | [![MyGet Badge WireMock.Net](https://img.shields.io/myget/wiremock-net/vpre/WireMock.Net?includePreReleases=true&label=MyGet)](https://www.myget.org/feed/wiremock-net/package/nuget/WireMock.Net)
| &nbsp;&nbsp;**WireMock.Net.StandAlone** | [![NuGet Badge WireMock.Net](https://img.shields.io/nuget/v/WireMock.Net.StandAlone)](https://www.nuget.org/packages/WireMock.Net.StandAlone) | [![MyGet Badge WireMock.Net.StandAlone](https://img.shields.io/myget/wiremock-net/vpre/WireMock.Net.StandAlone?includePreReleases=true&label=MyGet)](https://www.myget.org/feed/wiremock-net/package/nuget/WireMock.Net.StandAlone)
| &nbsp;&nbsp;**WireMock.Net.FluentAssertions** | [![NuGet Badge WireMock.Net.FluentAssertions](https://img.shields.io/nuget/v/WireMock.Net.FluentAssertions)](https://www.nuget.org/packages/WireMock.Net.FluentAssertions) | [![MyGet Badge WireMock.Net.FluentAssertions](https://img.shields.io/myget/wiremock-net/vpre/WireMock.Net.FluentAssertions?includePreReleases=true&label=MyGet)](https://www.myget.org/feed/wiremock-net/package/nuget/WireMock.Net.FluentAssertions)
| &nbsp;&nbsp;**WireMock.Net.Matchers.CSharpCode** | [![NuGet Badge WireMock.Net.Matchers.CSharpCode](https://img.shields.io/nuget/v/WireMock.Net.Matchers.CSharpCode)](https://www.nuget.org/packages/WireMock.Net.Matchers.CSharpCode) | [![MyGet Badge WireMock.Net.Matchers.CSharpCode](https://img.shields.io/myget/wiremock-net/vpre/WireMock.Net.Matchers.CSharpCode?includePreReleases=true&label=MyGet)](https://www.myget.org/feed/wiremock-net/package/nuget/WireMock.Net.Matchers.CSharpCode)
| &nbsp;&nbsp;**WireMock.Net.OpenApiParser** | [![NuGet Badge WireMock.Net.OpenApiParser](https://img.shields.io/nuget/v/WireMock.Net.OpenApiParser)](https://www.nuget.org/packages/WireMock.Net.OpenApiParser) | [![MyGet Badge WireMock.Net.OpenApiParser](https://img.shields.io/myget/wiremock-net/vpre/WireMock.Net.OpenApiParser?includePreReleases=true&label=MyGet)](https://www.myget.org/feed/wiremock-net/package/nuget/WireMock.Net.OpenApiParser)
| &nbsp;&nbsp;**WireMock.Net.RestClient** | [![NuGet Badge WireMock.Net.RestClient](https://img.shields.io/nuget/v/WireMock.Net.RestClient)](https://www.nuget.org/packages/WireMock.Net.RestClient) | [![MyGet Badge WireMock.Net.RestClient](https://img.shields.io/myget/wiremock-net/vpre/WireMock.Net.RestClient?includePreReleases=true&label=MyGet)](https://www.myget.org/feed/wiremock-net/package/nuget/WireMock.Net.RestClient)
| &nbsp;&nbsp;**WireMock.Net.xUnit** | [![NuGet Badge WireMock.Net.xUnit](https://img.shields.io/nuget/v/WireMock.Net.xUnit)](https://www.nuget.org/packages/WireMock.Net.xUnit) | [![MyGet Badge WireMock.Net.xUnit](https://img.shields.io/myget/wiremock-net/vpre/WireMock.Net.xUnit?includePreReleases=true&label=MyGet)](https://www.myget.org/feed/wiremock-net/package/nuget/WireMock.Net.xUnit)
| &nbsp;&nbsp;**WireMock.Net.Testcontainers** | [![NuGet Badge WireMock.Net.Testcontainers](https://img.shields.io/nuget/v/WireMock.Net.Testcontainers)](https://www.nuget.org/packages/WireMock.Net.Testcontainers) | [![MyGet Badge WireMock.Net.Testcontainers](https://img.shields.io/myget/wiremock-net/vpre/WireMock.Net.Testcontainers?includePreReleases=true&label=MyGet)](https://www.myget.org/feed/wiremock-net/package/nuget/WireMock.Net.Testcontainers)
| &nbsp;&nbsp;**WireMock.Net.Aspire** | [![NuGet Badge WireMock.Net.Aspire](https://img.shields.io/nuget/v/WireMock.Net.Aspire)](https://www.nuget.org/packages/WireMock.Net.Aspire) | [![MyGet Badge WireMock.Net.Aspire](https://img.shields.io/myget/wiremock-net/vpre/WireMock.Net.Aspire?includePreReleases=true&label=MyGet)](https://www.myget.org/feed/wiremock-net/package/nuget/WireMock.Net.Aspire)
| &nbsp;&nbsp;**WireMock.Org.RestClient** | [![NuGet Badge WireMock.Org.RestClient](https://img.shields.io/nuget/v/WireMock.Org.RestClient)](https://www.nuget.org/packages/WireMock.Org.RestClient) | [![MyGet Badge WireMock.Org.RestClient](https://img.shields.io/myget/wiremock-net/vpre/WireMock.Org.RestClient?includePreReleases=true&label=MyGet)](https://www.myget.org/feed/wiremock-net/package/nuget/WireMock.Org.RestClient)
| &nbsp;&nbsp;**WireMock.Net** | [![NuGet Badge WireMock.Net](https://buildstats.info/nuget/WireMock.Net)](https://www.nuget.org/packages/WireMock.Net) | [![MyGet Badge WireMock.Net](https://buildstats.info/myget/wiremock-net/WireMock.Net?includePreReleases=true)](https://www.myget.org/feed/wiremock-net/package/nuget/WireMock.Net)
| &nbsp;&nbsp;**WireMock.Net.StandAlone** | [![NuGet Badge WireMock.Net](https://buildstats.info/nuget/WireMock.Net.StandAlone)](https://www.nuget.org/packages/WireMock.Net.StandAlone) | [![MyGet Badge WireMock.Net.StandAlone](https://buildstats.info/myget/wiremock-net/WireMock.Net.StandAlone?includePreReleases=true)](https://www.myget.org/feed/wiremock-net/package/nuget/WireMock.Net.StandAlone)
| &nbsp;&nbsp;**WireMock.Net.FluentAssertions** | [![NuGet Badge WireMock.Net.FluentAssertions](https://buildstats.info/nuget/WireMock.Net.FluentAssertions)](https://www.nuget.org/packages/WireMock.Net.FluentAssertions) | [![MyGet Badge WireMock.Net.FluentAssertions](https://buildstats.info/myget/wiremock-net/WireMock.Net.FluentAssertions?includePreReleases=true)](https://www.myget.org/feed/wiremock-net/package/nuget/WireMock.Net.FluentAssertions)
| &nbsp;&nbsp;**WireMock.Net.Matchers.CSharpCode** | [![NuGet Badge WireMock.Net.Matchers.CSharpCode](https://buildstats.info/nuget/WireMock.Net.Matchers.CSharpCode)](https://www.nuget.org/packages/WireMock.Net.Matchers.CSharpCode) | [![MyGet Badge WireMock.Net.Matchers.CSharpCode](https://buildstats.info/myget/wiremock-net/WireMock.Net.Matchers.CSharpCode?includePreReleases=true)](https://www.myget.org/feed/wiremock-net/package/nuget/WireMock.Net.Matchers.CSharpCode)
| &nbsp;&nbsp;**WireMock.Net.OpenApiParser** | [![NuGet Badge WireMock.Net.OpenApiParser](https://buildstats.info/nuget/WireMock.Net.OpenApiParser)](https://www.nuget.org/packages/WireMock.Net.OpenApiParser) | [![MyGet Badge WireMock.Net.OpenApiParser](https://buildstats.info/myget/wiremock-net/WireMock.Net.OpenApiParser?includePreReleases=true)](https://www.myget.org/feed/wiremock-net/package/nuget/WireMock.Net.OpenApiParser)
| &nbsp;&nbsp;**WireMock.Net.RestClient** | [![NuGet Badge WireMock.Net.RestClient](https://buildstats.info/nuget/WireMock.Net.RestClient)](https://www.nuget.org/packages/WireMock.Net.RestClient) | [![MyGet Badge WireMock.Net.RestClient](https://buildstats.info/myget/wiremock-net/WireMock.Net.RestClient?includePreReleases=true)](https://www.myget.org/feed/wiremock-net/package/nuget/WireMock.Net.RestClient)
| &nbsp;&nbsp;**WireMock.Net.xUnit** | [![NuGet Badge WireMock.Net.xUnit](https://buildstats.info/nuget/WireMock.Net.xUnit)](https://www.nuget.org/packages/WireMock.Net.xUnit) | [![MyGet Badge WireMock.Net.xUnit](https://buildstats.info/myget/wiremock-net/WireMock.Net.xUnit?includePreReleases=true)](https://www.myget.org/feed/wiremock-net/package/nuget/WireMock.Net.xUnit)
| &nbsp;&nbsp;**WireMock.Net.Testcontainers** | [![NuGet Badge WireMock.Net.Testcontainers](https://buildstats.info/nuget/WireMock.Net.Testcontainers)](https://www.nuget.org/packages/WireMock.Net.Testcontainers) | [![MyGet Badge WireMock.Net.Testcontainers](https://buildstats.info/myget/wiremock-net/WireMock.Net.Testcontainers?includePreReleases=true)](https://www.myget.org/feed/wiremock-net/package/nuget/WireMock.Net.Testcontainers)
| &nbsp;&nbsp;**WireMock.Net.Aspire** | [![NuGet Badge WireMock.Net.Aspire](https://buildstats.info/nuget/WireMock.Net.Aspire)](https://www.nuget.org/packages/WireMock.Net.Aspire) | [![MyGet Badge WireMock.Net.Aspire](https://buildstats.info/myget/wiremock-net/WireMock.Net.Aspire?includePreReleases=true)](https://www.myget.org/feed/wiremock-net/package/nuget/WireMock.Net.Aspire)
| &nbsp;&nbsp;**WireMock.Org.RestClient** | [![NuGet Badge WireMock.Org.RestClient](https://buildstats.info/nuget/WireMock.Org.RestClient)](https://www.nuget.org/packages/WireMock.Org.RestClient) | [![MyGet Badge WireMock.Org.RestClient](https://buildstats.info/myget/wiremock-net/WireMock.Org.RestClient?includePreReleases=true)](https://www.myget.org/feed/wiremock-net/package/nuget/WireMock.Org.RestClient)
## :memo: Development

View File

@@ -33,7 +33,6 @@
<s:Boolean x:Key="/Default/UserDictionary/Words/=Guids/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Heyenrath/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Jmes/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Levenstein/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=openapi/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Pacticipant/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=protobuf/@EntryIndexedValue">True</s:Boolean>

View File

@@ -53,13 +53,8 @@ jobs:
inputs:
script: |
dotnet-coverage collect "dotnet test ./test/WireMock.Net.Tests/WireMock.Net.Tests.csproj --configuration Debug --no-build --framework net8.0" -f xml -o "wiremock-coverage-1.xml"
displayName: 'Execute WireMock.Net.Tests with Coverage'
- task: CmdLine@2
inputs:
script: |
dotnet-coverage collect "dotnet test ./test/WireMock.Net.Aspire.Tests/WireMock.Net.Aspire.Tests.csproj --configuration Debug --no-build" -f xml -o "wiremock-coverage-2.xml"
displayName: 'Execute WireMock.Net.Aspire.Tests with Coverage'
displayName: 'Execute Unit Tests with Coverage'
- task: CmdLine@2
displayName: 'Merge coverage files'

View File

@@ -17,7 +17,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Aspire.Hosting.AppHost" Version="8.2.0" />
<PackageReference Include="Aspire.Hosting.AppHost" Version="8.0.0" />
</ItemGroup>
</Project>

View File

@@ -14,7 +14,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Aspire.Hosting.AppHost" Version="8.2.0" />
<PackageReference Include="Aspire.Hosting.AppHost" Version="8.0.0" />
</ItemGroup>
</Project>

View File

@@ -137,6 +137,7 @@ message HelloReply {
public static void Run()
{
RunOnLocal();
return;
var mappingBuilder = new MappingBuilder();
mappingBuilder
@@ -307,6 +308,17 @@ message HelloReply {
.RespondWith(Response.Create()
.WithBody("GraphQL is ok")
);
//server
// .AddGraphQLSchema("my-graphql", TestSchema, customScalars)
// .Given(Request.Create()
// .WithPath("/graphql2")
// .UsingPost()
// )
// .WithGraphQLSchema("my-graphql")
// .RespondWith(Response.Create()
// .WithBody("GraphQL is ok")
// );
#endif
#if MIMEKIT
@@ -365,15 +377,6 @@ message HelloReply {
.WithHeader("Content-Type", "text/plain")
);
server
.Given(Request.Create()
.UsingHead()
.WithPath("/cl")
)
.RespondWith(Response.Create()
.WithHeader("Content-Length", "42")
);
server
.Given(Request.Create()
.UsingMethod("GET")

View File

@@ -1,6 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<Version>0.0.1-preview-05</Version>
<ImplicitUsings>enable</ImplicitUsings>
<Description>Aspire extension to start a WireMock.Net server to stub an api.</Description>
<AssemblyTitle>WireMock.Net.Aspire</AssemblyTitle>
@@ -35,7 +36,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Aspire.Hosting" Version="8.2.0" />
<PackageReference Include="Aspire.Hosting" Version="8.0.0" />
</ItemGroup>
<ItemGroup>

View File

@@ -10,7 +10,6 @@ using Stef.Validation;
using WireMock.Exceptions;
using WireMock.Extensions;
using WireMock.Models;
using WireMock.Util;
namespace WireMock.Matchers;
@@ -93,17 +92,6 @@ internal class CSharpCodeMatcher : ICSharpCodeMatcher
return new MatchResult(MatchBehaviourHelper.Convert(MatchBehaviour, score), exception);
}
/// <inheritdoc />
public string GetCSharpCodeArguments()
{
return $"new {Name}" +
$"(" +
$"{MatchBehaviour.GetFullyQualifiedEnumValue()}, " +
$"{MatchOperator.GetFullyQualifiedEnumValue()}, " +
$"{MappingConverterUtils.ToCSharpCodeArguments(_patterns)}" +
$")";
}
private bool IsMatch(dynamic input, string pattern)
{
var isMatchWithString = input is string;

View File

@@ -10,7 +10,6 @@ using Microsoft.IdentityModel.Protocols;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;
using Stef.Validation;
using WireMock.Constants;
using WireMock.Matchers;
using WireMock.Models;
@@ -42,7 +41,7 @@ internal class AzureADAuthenticationMatcher : IStringMatcher
return EmptyArray<AnyOf<string, StringPattern>>.Value;
}
public MatchOperator MatchOperator => MatchOperator.Or;
public MatchOperator MatchOperator { get; } = MatchOperator.Or;
public MatchResult IsMatch(string? input)
{
@@ -51,7 +50,7 @@ internal class AzureADAuthenticationMatcher : IStringMatcher
return MatchScores.Mismatch;
}
var token = Regex.Replace(input, BearerPrefix, string.Empty, RegexOptions.IgnoreCase, WireMockConstants.DefaultRegexTimeout);
var token = Regex.Replace(input, BearerPrefix, string.Empty, RegexOptions.IgnoreCase);
try
{
@@ -76,11 +75,5 @@ internal class AzureADAuthenticationMatcher : IStringMatcher
return new MatchResult(MatchScores.Mismatch, ex);
}
}
/// <inheritdoc />
public virtual string GetCSharpCodeArguments()
{
throw new NotImplementedException();
}
}
#endif

View File

@@ -6,9 +6,12 @@ using WireMock.Matchers;
namespace WireMock.Authentication;
internal class BasicAuthenticationMatcher(string username, string password)
: RegexMatcher(BuildPattern(username, password))
internal class BasicAuthenticationMatcher : RegexMatcher
{
public BasicAuthenticationMatcher(string username, string password) : base(BuildPattern(username, password))
{
}
public override string Name => nameof(BasicAuthenticationMatcher);
private static string BuildPattern(string username, string password)

View File

@@ -2,7 +2,6 @@
#if NET451 || NET452 || NET46 || NET451 || NET461 || NETSTANDARD1_3 || NETSTANDARD2_0
using System.Text.RegularExpressions;
using WireMock.Constants;
// ReSharper disable once CheckNamespace
namespace System;
@@ -12,7 +11,7 @@ internal static class StringExtensions
public static string Replace(this string text, string oldValue, string newValue, StringComparison stringComparison)
{
var options = stringComparison == StringComparison.OrdinalIgnoreCase ? RegexOptions.IgnoreCase : RegexOptions.None;
return Regex.Replace(text, oldValue, newValue, options, WireMockConstants.DefaultRegexTimeout);
return Regex.Replace(text, oldValue, newValue, options);
}
}
#endif

View File

@@ -1,19 +1,15 @@
// Copyright © WireMock.Net
using System;
namespace WireMock.Constants;
internal static class WireMockConstants
{
internal static readonly TimeSpan DefaultRegexTimeout = TimeSpan.FromSeconds(10);
internal const int AdminPriority = int.MinValue;
internal const int MinPriority = -1_000_000;
internal const int ProxyPriority = -2_000_000;
public const int AdminPriority = int.MinValue;
public const int MinPriority = -1_000_000;
public const int ProxyPriority = -2_000_000;
internal const string ContentTypeJson = "application/json";
internal const string ContentTypeTextPlain = "text/plain";
public const string ContentTypeJson = "application/json";
public const string ContentTypeTextPlain = "text/plain";
internal const string NoMatchingFound = "No matching mapping found";
}
public const string NoMatchingFound = "No matching mapping found";
}

View File

@@ -14,12 +14,12 @@ namespace WireMock.Http;
/// </summary>
internal static class HttpKnownHeaderNames
{
// - https://docs.microsoft.com/en-us/dotnet/api/system.net.webheadercollection.isrestricted
// - ContentLength is allowed per #720
// https://docs.microsoft.com/en-us/dotnet/api/system.net.webheadercollection.isrestricted
private static readonly string[] RestrictedResponseHeaders =
{
Accept,
Connection,
ContentLength,
ContentType,
Date, // RFC1123Pattern
Expect,

View File

@@ -130,10 +130,7 @@ public class MappingBuilder : IMappingBuilder
private IMapping[] GetNonAdminMappings()
{
return _options.Mappings.Values
.Where(m => !m.IsAdminInterface)
.OrderBy(m => m.Guid)
.ToArray();
return _options.Mappings.Values.Where(m => !m.IsAdminInterface).OrderBy(m => m.UpdatedAt).ToArray();
}
private void RegisterMapping(IMapping mapping, bool saveToFile)

View File

@@ -2,10 +2,7 @@
using System.Net.Http.Headers;
using AnyOfTypes;
using Stef.Validation;
using WireMock.Extensions;
using WireMock.Models;
using WireMock.Util;
namespace WireMock.Matchers;
@@ -22,7 +19,7 @@ public class ContentTypeMatcher : WildcardMatcher
/// </summary>
/// <param name="pattern">The pattern.</param>
/// <param name="ignoreCase">IgnoreCase (default false)</param>
public ContentTypeMatcher(AnyOf<string, StringPattern> pattern, bool ignoreCase = false) : this([pattern], ignoreCase)
public ContentTypeMatcher(AnyOf<string, StringPattern> pattern, bool ignoreCase = false) : this(new[] { pattern }, ignoreCase)
{
}
@@ -32,8 +29,7 @@ public class ContentTypeMatcher : WildcardMatcher
/// <param name="matchBehaviour">The match behaviour.</param>
/// <param name="pattern">The pattern.</param>
/// <param name="ignoreCase">IgnoreCase (default false)</param>
public ContentTypeMatcher(MatchBehaviour matchBehaviour, AnyOf<string, StringPattern> pattern, bool ignoreCase = false) : this(matchBehaviour,
[pattern], ignoreCase)
public ContentTypeMatcher(MatchBehaviour matchBehaviour, AnyOf<string, StringPattern> pattern, bool ignoreCase = false) : this(matchBehaviour, new[] { pattern }, ignoreCase)
{
}
@@ -54,7 +50,7 @@ public class ContentTypeMatcher : WildcardMatcher
/// <param name="ignoreCase">IgnoreCase (default false)</param>
public ContentTypeMatcher(MatchBehaviour matchBehaviour, AnyOf<string, StringPattern>[] patterns, bool ignoreCase = false) : base(matchBehaviour, patterns, ignoreCase)
{
_patterns = Guard.NotNull(patterns);
_patterns = patterns;
}
/// <inheritdoc />
@@ -76,15 +72,4 @@ public class ContentTypeMatcher : WildcardMatcher
/// <inheritdoc />
public override string Name => nameof(ContentTypeMatcher);
/// <inheritdoc />
public override string GetCSharpCodeArguments()
{
return $"new {Name}" +
$"(" +
$"{MatchBehaviour.GetFullyQualifiedEnumValue()}, " +
$"{MappingConverterUtils.ToCSharpCodeArguments(_patterns)}, " +
$"{CSharpFormatter.ToCSharpBooleanLiteral(IgnoreCase)}" +
$")";
}
}

View File

@@ -4,9 +4,7 @@ using System;
using System.Linq;
using AnyOfTypes;
using Stef.Validation;
using WireMock.Extensions;
using WireMock.Models;
using WireMock.Util;
namespace WireMock.Matchers;
@@ -88,20 +86,8 @@ public class ExactMatcher : IStringMatcher, IIgnoreCaseMatcher
public MatchOperator MatchOperator { get; }
/// <inheritdoc />
public string Name => nameof(ExactMatcher);
public string Name => "ExactMatcher";
/// <inheritdoc />
public bool IgnoreCase { get; }
/// <inheritdoc />
public string GetCSharpCodeArguments()
{
return $"new {Name}" +
$"(" +
$"{MatchBehaviour.GetFullyQualifiedEnumValue()}, " +
$"{CSharpFormatter.ToCSharpBooleanLiteral(IgnoreCase)}, " +
$"{MatchOperator.GetFullyQualifiedEnumValue()}, " +
$"{MappingConverterUtils.ToCSharpCodeArguments(_values)}" +
$")";
}
}

View File

@@ -72,11 +72,5 @@ public class ExactObjectMatcher : IObjectMatcher
}
/// <inheritdoc />
public string Name => nameof(ExactObjectMatcher);
/// <inheritdoc />
public string GetCSharpCodeArguments()
{
return "NotImplemented";
}
public string Name => "ExactObjectMatcher";
}

View File

@@ -4,7 +4,6 @@ using System.Collections.Generic;
using System.Linq;
using AnyOfTypes;
using Stef.Validation;
using WireMock.Extensions;
using WireMock.Models;
using WireMock.Util;
@@ -164,16 +163,4 @@ public class FormUrlEncodedMatcher : IStringMatcher, IIgnoreCaseMatcher
/// <inheritdoc />
public MatchOperator MatchOperator { get; }
/// <inheritdoc />
public string GetCSharpCodeArguments()
{
return $"new {Name}" +
$"(" +
$"{MatchBehaviour.GetFullyQualifiedEnumValue()}, " +
$"{MappingConverterUtils.ToCSharpCodeArguments(_patterns)}, " +
$"{CSharpFormatter.ToCSharpBooleanLiteral(IgnoreCase)}, " +
$"{MatchOperator.GetFullyQualifiedEnumValue()}" +
$")";
}
}

View File

@@ -156,12 +156,6 @@ public class GraphQLMatcher : IStringMatcher
/// <inheritdoc />
public string Name => nameof(GraphQLMatcher);
/// <inheritdoc />
public string GetCSharpCodeArguments()
{
return "NotImplemented";
}
private static bool TryGetGraphQLRequest(string input, [NotNullWhen(true)] out GraphQLRequest? graphQLRequest)
{
try

View File

@@ -16,10 +16,4 @@ public interface IMatcher
/// Gets the match behaviour.
/// </summary>
MatchBehaviour MatchBehaviour { get; }
/// <summary>
/// Get the C# code arguments.
/// </summary>
/// <returns></returns>
string GetCSharpCodeArguments();
}

View File

@@ -7,7 +7,6 @@ using Newtonsoft.Json.Linq;
using Stef.Validation;
using WireMock.Extensions;
using WireMock.Models;
using WireMock.Util;
namespace WireMock.Matchers;
@@ -90,7 +89,7 @@ public class JsonPathMatcher : IStringMatcher, IObjectMatcher
Exception? exception = null;
// When input is null or byte[], return Mismatch.
if (input != null && input is not byte[])
if (input != null && !(input is byte[]))
{
try
{
@@ -117,18 +116,7 @@ public class JsonPathMatcher : IStringMatcher, IObjectMatcher
public MatchOperator MatchOperator { get; }
/// <inheritdoc />
public string Name => nameof(JsonPathMatcher);
/// <inheritdoc />
public string GetCSharpCodeArguments()
{
return $"new {Name}" +
$"(" +
$"{MatchBehaviour.GetFullyQualifiedEnumValue()}, " +
$"{MatchOperator.GetFullyQualifiedEnumValue()}, " +
$"{MappingConverterUtils.ToCSharpCodeArguments(_patterns)}" +
$")";
}
public string Name => "JsonPathMatcher";
private double IsMatch(JToken jToken)
{

View File

@@ -8,7 +8,6 @@ using Newtonsoft.Json;
using Stef.Validation;
using WireMock.Extensions;
using WireMock.Models;
using WireMock.Util;
namespace WireMock.Matchers;
@@ -116,15 +115,4 @@ public class JmesPathMatcher : IStringMatcher, IObjectMatcher
/// <inheritdoc />
public string Name => nameof(JmesPathMatcher);
/// <inheritdoc />
public string GetCSharpCodeArguments()
{
return $"new {Name}" +
$"(" +
$"{MatchBehaviour.GetFullyQualifiedEnumValue()}, " +
$"{MatchOperator.GetFullyQualifiedEnumValue()}, " +
$"{MappingConverterUtils.ToCSharpCodeArguments(_patterns)}" +
$")";
}
}

View File

@@ -5,7 +5,6 @@ using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json.Linq;
using Stef.Validation;
using WireMock.Extensions;
using WireMock.Util;
using JsonUtils = WireMock.Util.JsonUtils;
@@ -99,18 +98,6 @@ public class JsonMatcher : IJsonMatcher
return new MatchResult(MatchBehaviourHelper.Convert(MatchBehaviour, score), error);
}
/// <inheritdoc />
public virtual string GetCSharpCodeArguments()
{
return $"new {Name}" +
$"(" +
$"{MatchBehaviour.GetFullyQualifiedEnumValue()}, " +
$"{CSharpFormatter.ConvertToAnonymousObjectDefinition(Value, 3)}, " +
$"{CSharpFormatter.ToCSharpBooleanLiteral(IgnoreCase)}, " +
$"{CSharpFormatter.ToCSharpBooleanLiteral(Regex)}" +
$")";
}
/// <summary>
/// Compares the input against the matcher value
/// </summary>

View File

@@ -1,8 +1,5 @@
// Copyright © WireMock.Net
using WireMock.Extensions;
using WireMock.Util;
namespace WireMock.Matchers;
/// <summary>
@@ -37,16 +34,4 @@ public class JsonPartialMatcher : AbstractJsonPartialMatcher
var exactStringMatcher = new ExactMatcher(MatchBehaviour.AcceptOnMatch, IgnoreCase, MatchOperator.Or, value);
return exactStringMatcher.IsMatch(input).IsPerfect();
}
/// <inheritdoc />
public override string GetCSharpCodeArguments()
{
return $"new {Name}" +
$"(" +
$"{MatchBehaviour.GetFullyQualifiedEnumValue()}, " +
$"{CSharpFormatter.ConvertToAnonymousObjectDefinition(Value, 3)}, " +
$"{CSharpFormatter.ToCSharpBooleanLiteral(IgnoreCase)}, " +
$"{CSharpFormatter.ToCSharpBooleanLiteral(Regex)}" +
$")";
}
}

View File

@@ -1,8 +1,5 @@
// Copyright © WireMock.Net
using WireMock.Extensions;
using WireMock.Util;
namespace WireMock.Matchers;
/// <summary>
@@ -37,16 +34,4 @@ public class JsonPartialWildcardMatcher : AbstractJsonPartialMatcher
var wildcardStringMatcher = new WildcardMatcher(MatchBehaviour.AcceptOnMatch, value, IgnoreCase);
return wildcardStringMatcher.IsMatch(input).IsPerfect();
}
/// <inheritdoc />
public override string GetCSharpCodeArguments()
{
return $"new {Name}" +
$"(" +
$"{MatchBehaviour.GetFullyQualifiedEnumValue()}, " +
$"{CSharpFormatter.ConvertToAnonymousObjectDefinition(Value, 3)}, " +
$"{CSharpFormatter.ToCSharpBooleanLiteral(IgnoreCase)}, " +
$"{CSharpFormatter.ToCSharpBooleanLiteral(Regex)}" +
$")";
}
}

View File

@@ -9,7 +9,6 @@ using Stef.Validation;
using WireMock.Extensions;
using WireMock.Json;
using WireMock.Models;
using WireMock.Util;
namespace WireMock.Matchers;
@@ -137,15 +136,4 @@ public class LinqMatcher : IObjectMatcher, IStringMatcher
/// <inheritdoc />
public string Name => nameof(LinqMatcher);
/// <inheritdoc />
public string GetCSharpCodeArguments()
{
return $"new {Name}" +
$"(" +
$"{MatchBehaviour.GetFullyQualifiedEnumValue()}, " +
$"{MatchOperator.GetFullyQualifiedEnumValue()}, " +
$"{MappingConverterUtils.ToCSharpCodeArguments(_patterns)}" +
$")";
}
}

View File

@@ -3,7 +3,6 @@
#if MIMEKIT
using System;
using MimeKit;
using WireMock.Extensions;
using WireMock.Matchers;
using WireMock.Matchers.Helpers;
using WireMock.Models;
@@ -61,13 +60,13 @@ public class MimePartMatcher : IMatcher
ContentTransferEncodingMatcher = contentTransferEncodingMatcher;
ContentMatcher = contentMatcher;
_funcs =
[
_funcs = new[]
{
mp => ContentTypeMatcher?.IsMatch(GetContentTypeAsString(mp.ContentType)) ?? MatchScores.Perfect,
mp => ContentDispositionMatcher?.IsMatch(mp.ContentDisposition.ToString().Replace("Content-Disposition: ", string.Empty)) ?? MatchScores.Perfect,
mp => ContentTransferEncodingMatcher?.IsMatch(mp.ContentTransferEncoding.ToString().ToLowerInvariant()) ?? MatchScores.Perfect,
MatchOnContent
];
};
}
/// <summary>
@@ -95,12 +94,6 @@ public class MimePartMatcher : IMatcher
return new MatchResult(MatchBehaviourHelper.Convert(MatchBehaviour, score), exception);
}
/// <inheritdoc />
public string GetCSharpCodeArguments()
{
return "NotImplemented";
}
private MatchResult MatchOnContent(MimePart mimePart)
{
if (ContentMatcher == null)

View File

@@ -3,9 +3,7 @@
using System;
using System.Linq;
using AnyOfTypes;
using WireMock.Extensions;
using WireMock.Models;
using WireMock.Util;
namespace WireMock.Matchers;
@@ -72,14 +70,5 @@ public class NotNullOrEmptyMatcher : IObjectMatcher, IStringMatcher
}
/// <inheritdoc />
public MatchOperator MatchOperator => MatchOperator.Or;
/// <inheritdoc />
public string GetCSharpCodeArguments()
{
return $"new {Name}" +
$"(" +
$"{MatchBehaviour.GetFullyQualifiedEnumValue()}" +
$")";
}
public MatchOperator MatchOperator { get; } = MatchOperator.Or;
}

View File

@@ -89,12 +89,6 @@ public class ProtoBufMatcher : IProtoBufMatcher
return DecodeAsync(input, false, cancellationToken);
}
/// <inheritdoc />
public string GetCSharpCodeArguments()
{
return "NotImplemented";
}
private async Task<object?> DecodeAsync(byte[]? input, bool throwException, CancellationToken cancellationToken)
{
if (input == null)

View File

@@ -5,12 +5,10 @@ using System.Linq;
using System.Text.RegularExpressions;
using AnyOfTypes;
using JetBrains.Annotations;
using Stef.Validation;
using WireMock.Constants;
using WireMock.Extensions;
using WireMock.Models;
using WireMock.RegularExpressions;
using WireMock.Util;
using Stef.Validation;
namespace WireMock.Matchers;
@@ -23,7 +21,6 @@ public class RegexMatcher : IStringMatcher, IIgnoreCaseMatcher
{
private readonly AnyOf<string, StringPattern>[] _patterns;
private readonly Regex[] _expressions;
private readonly bool _useRegexExtended;
/// <inheritdoc />
public MatchBehaviour MatchBehaviour { get; }
@@ -40,7 +37,7 @@ public class RegexMatcher : IStringMatcher, IIgnoreCaseMatcher
bool ignoreCase = false,
bool useRegexExtended = true,
MatchOperator matchOperator = MatchOperator.Or) :
this(MatchBehaviour.AcceptOnMatch, [pattern], ignoreCase, useRegexExtended, matchOperator)
this(MatchBehaviour.AcceptOnMatch, new[] { pattern }, ignoreCase, useRegexExtended, matchOperator)
{
}
@@ -58,7 +55,7 @@ public class RegexMatcher : IStringMatcher, IIgnoreCaseMatcher
bool ignoreCase = false,
bool useRegexExtended = true,
MatchOperator matchOperator = MatchOperator.Or) :
this(matchBehaviour, [pattern], ignoreCase, useRegexExtended, matchOperator)
this(matchBehaviour, new[] { pattern }, ignoreCase, useRegexExtended, matchOperator)
{
}
@@ -79,18 +76,17 @@ public class RegexMatcher : IStringMatcher, IIgnoreCaseMatcher
{
_patterns = Guard.NotNull(patterns);
IgnoreCase = ignoreCase;
_useRegexExtended = useRegexExtended;
MatchBehaviour = matchBehaviour;
MatchOperator = matchOperator;
var options = RegexOptions.Compiled | RegexOptions.Multiline;
RegexOptions options = RegexOptions.Compiled | RegexOptions.Multiline;
if (ignoreCase)
{
options |= RegexOptions.IgnoreCase;
}
_expressions = patterns.Select(p => useRegexExtended ? new RegexExtended(p.GetPattern(), options) : new Regex(p.GetPattern(), options, WireMockConstants.DefaultRegexTimeout)).ToArray();
_expressions = patterns.Select(p => useRegexExtended ? new RegexExtended(p.GetPattern(), options) : new Regex(p.GetPattern(), options)).ToArray();
}
/// <inheritdoc />
@@ -129,16 +125,4 @@ public class RegexMatcher : IStringMatcher, IIgnoreCaseMatcher
/// <inheritdoc />
public MatchOperator MatchOperator { get; }
/// <inheritdoc />
public virtual string GetCSharpCodeArguments()
{
return $"new {Name}" +
$"(" +
$"{MatchBehaviour.GetFullyQualifiedEnumValue()}, " +
$"{MappingConverterUtils.ToCSharpCodeArguments(_patterns)}, " +
$"{CSharpFormatter.ToCSharpBooleanLiteral(IgnoreCase)}, " +
$"{CSharpFormatter.ToCSharpBooleanLiteral(_useRegexExtended)}, " +
$"{MatchOperator.GetFullyQualifiedEnumValue()}" +
$")";
}
}

View File

@@ -8,7 +8,6 @@ using SimMetrics.Net.Metric;
using Stef.Validation;
using WireMock.Extensions;
using WireMock.Models;
using WireMock.Util;
namespace WireMock.Matchers;
@@ -89,18 +88,6 @@ public class SimMetricsMatcher : IStringMatcher
return MatchBehaviourHelper.Convert(MatchBehaviour, score);
}
/// <inheritdoc />
public virtual string GetCSharpCodeArguments()
{
return $"new {Name}" +
$"(" +
$"{MatchBehaviour.GetFullyQualifiedEnumValue()}, " +
$"{MappingConverterUtils.ToCSharpCodeArguments(_patterns)}, " +
$"{_simMetricType.GetFullyQualifiedEnumValue()}, " +
$"{MatchOperator.GetFullyQualifiedEnumValue()}" +
$")";
}
private IStringMetric GetStringMetricType()
{
return _simMetricType switch

View File

@@ -6,7 +6,6 @@ using AnyOfTypes;
using Stef.Validation;
using WireMock.Extensions;
using WireMock.Models;
using WireMock.Util;
namespace WireMock.Matchers;
@@ -71,18 +70,6 @@ public class WildcardMatcher : RegexMatcher
/// <inheritdoc />
public override string Name => nameof(WildcardMatcher);
/// <inheritdoc />
public override string GetCSharpCodeArguments()
{
return $"new {Name}" +
$"(" +
$"{MatchBehaviour.GetFullyQualifiedEnumValue()}, " +
$"{MappingConverterUtils.ToCSharpCodeArguments(_patterns)}, " +
$"{CSharpFormatter.ToCSharpBooleanLiteral(IgnoreCase)}, " +
$"{MatchOperator.GetFullyQualifiedEnumValue()}" +
$")";
}
private static AnyOf<string, StringPattern>[] CreateArray(AnyOf<string, StringPattern>[] patterns)
{
return patterns

View File

@@ -10,7 +10,6 @@ using WireMock.Extensions;
using WireMock.Models;
using Stef.Validation;
using WireMock.Admin.Mappings;
using WireMock.Util;
#if !NETSTANDARD1_3
using Wmhelp.XPath2;
#endif
@@ -90,6 +89,11 @@ public class XPathMatcher : IStringMatcher
return CreateMatchResult(score);
}
private MatchResult CreateMatchResult(double score, Exception? exception = null)
{
return new MatchResult(MatchBehaviourHelper.Convert(MatchBehaviour, score), exception);
}
/// <inheritdoc />
public AnyOf<string, StringPattern>[] GetPatterns()
{
@@ -102,23 +106,6 @@ public class XPathMatcher : IStringMatcher
/// <inheritdoc />
public string Name => nameof(XPathMatcher);
/// <inheritdoc />
public string GetCSharpCodeArguments()
{
return $"new {Name}" +
$"(" +
$"{MatchBehaviour.GetFullyQualifiedEnumValue()}, " +
$"{MatchOperator.GetFullyQualifiedEnumValue()}, " +
$"null, " +
$"{MappingConverterUtils.ToCSharpCodeArguments(_patterns)}" +
$")";
}
private MatchResult CreateMatchResult(double score, Exception? exception = null)
{
return new MatchResult(MatchBehaviourHelper.Convert(MatchBehaviour, score), exception);
}
private sealed class XPathEvaluator
{
private XmlDocument? _xmlDocument;
@@ -143,7 +130,6 @@ public class XPathMatcher : IStringMatcher
{
return _xpathNavigator == null ? [] : patterns.Select(pattern => true.Equals(Evaluate(_xpathNavigator, pattern, xmlNamespaceMap))).ToArray();
}
private object Evaluate(XPathNavigator navigator, AnyOf<string, StringPattern> pattern, IEnumerable<XmlNamespace>? xmlNamespaceMap)
{
var xpath = $"boolean({pattern.GetPattern()})";

View File

@@ -75,15 +75,8 @@ namespace WireMock.Owin
private static void Listen(KestrelServerOptions kestrelOptions, HostUrlDetails urlDetail, Action<ListenOptions> configure)
{
// Listens on any IP with the given port.
if (urlDetail is { Port: > 0, Host: "0.0.0.0" })
{
kestrelOptions.ListenAnyIP(urlDetail.Port, configure);
return;
}
// Listens on ::1 and 127.0.0.1 with the given port.
if (urlDetail is { Port: > 0, Host: "localhost" or "127.0.0.1" or "::1" })
if (urlDetail is { Port: > 0, Host: "localhost" or "127.0.0.1" or "0.0.0.0" or "::1" })
{
kestrelOptions.ListenLocalhost(urlDetail.Port, configure);
return;
@@ -120,4 +113,4 @@ namespace WireMock.Owin
}
}
}
#endif
#endif

View File

@@ -37,20 +37,13 @@ namespace WireMock.Owin.Mappers
private readonly Encoding _utf8NoBom = new UTF8Encoding(false);
// https://msdn.microsoft.com/en-us/library/78h415ay(v=vs.110).aspx
private static readonly IDictionary<string, Action<IResponse, bool, WireMockList<string>>> ResponseHeadersToFix =
new Dictionary<string, Action<IResponse, bool, WireMockList<string>>>(StringComparer.OrdinalIgnoreCase)
{
{ HttpKnownHeaderNames.ContentType, (r, _, v) => r.ContentType = v.FirstOrDefault() },
{ HttpKnownHeaderNames.ContentLength, (r, hasBody, v) =>
{
// Only set the Content-Length header if the response does not have a body
if (!hasBody && long.TryParse(v.FirstOrDefault(), out var contentLength))
{
r.ContentLength = contentLength;
}
}
}
};
#if !USE_ASPNETCORE
private static readonly IDictionary<string, Action<IResponse, WireMockList<string>>> ResponseHeadersToFix = new Dictionary<string, Action<IResponse, WireMockList<string>>>(StringComparer.OrdinalIgnoreCase) {
#else
private static readonly IDictionary<string, Action<IResponse, WireMockList<string>>> ResponseHeadersToFix = new Dictionary<string, Action<IResponse, WireMockList<string>>>(StringComparer.OrdinalIgnoreCase) {
#endif
{ HttpKnownHeaderNames.ContentType, (r, v) => r.ContentType = v.FirstOrDefault() }
};
/// <summary>
/// Constructor
@@ -90,21 +83,23 @@ namespace WireMock.Owin.Mappers
}
var statusCodeType = responseMessage.StatusCode?.GetType();
if (statusCodeType != null)
switch (statusCodeType)
{
if (statusCodeType == typeof(int) || statusCodeType == typeof(int?) || statusCodeType.GetTypeInfo().IsEnum)
{
case { } when statusCodeType == typeof(int) || statusCodeType == typeof(int?) || statusCodeType.GetTypeInfo().IsEnum:
response.StatusCode = MapStatusCode((int)responseMessage.StatusCode!);
}
else if (statusCodeType == typeof(string))
{
// Note: this case will also match on null
int.TryParse(responseMessage.StatusCode as string, out var statusCodeTypeAsInt);
response.StatusCode = MapStatusCode(statusCodeTypeAsInt);
}
break;
case { } when statusCodeType == typeof(string):
// Note: this case will also match on null
int.TryParse(responseMessage.StatusCode as string, out var result);
response.StatusCode = MapStatusCode(result);
break;
default:
break;
}
SetResponseHeaders(responseMessage, bytes, response);
SetResponseHeaders(responseMessage, response);
if (bytes != null)
{
@@ -165,7 +160,7 @@ namespace WireMock.Owin.Mappers
return null;
}
private static void SetResponseHeaders(IResponseMessage responseMessage, byte[]? bytes, IResponse response)
private static void SetResponseHeaders(IResponseMessage responseMessage, IResponse response)
{
// Force setting the Date header (#577)
AppendResponseHeader(
@@ -184,11 +179,11 @@ namespace WireMock.Owin.Mappers
var value = item.Value;
if (ResponseHeadersToFix.TryGetValue(headerName, out var action))
{
action?.Invoke(response, bytes != null, value);
action?.Invoke(response, value);
}
else
{
// Check if this response header can be added (#148, #227 and #720)
// Check if this response header can be added (#148 and #227)
if (!HttpKnownHeaderNames.IsRestrictedResponseHeader(headerName))
{
AppendResponseHeader(response, headerName, value.ToArray());
@@ -211,7 +206,7 @@ namespace WireMock.Owin.Mappers
var value = item.Value;
if (ResponseHeadersToFix.TryGetValue(headerName, out var action))
{
action?.Invoke(response, false, value);
action?.Invoke(response, value);
}
else
{

View File

@@ -1,6 +1,5 @@
// Copyright © WireMock.Net
using System;
using Stef.Validation;
using WireMock.Settings;
@@ -8,31 +7,21 @@ namespace WireMock.Owin;
internal static class WireMockMiddlewareOptionsHelper
{
public static IWireMockMiddlewareOptions InitFromSettings(
WireMockServerSettings settings,
IWireMockMiddlewareOptions? options = null,
Action<IWireMockMiddlewareOptions>? postConfigure = null
)
public static IWireMockMiddlewareOptions InitFromSettings(WireMockServerSettings settings, IWireMockMiddlewareOptions? options = null)
{
Guard.NotNull(settings);
options ??= new WireMockMiddlewareOptions();
options.AllowBodyForAllHttpMethods = settings.AllowBodyForAllHttpMethods;
options.AllowOnlyDefinedHttpStatusCodeInResponse = settings.AllowOnlyDefinedHttpStatusCodeInResponse;
options.AllowPartialMapping = settings.AllowPartialMapping;
options.DisableJsonBodyParsing = settings.DisableJsonBodyParsing;
options.DisableRequestBodyDecompressing = settings.DisableRequestBodyDecompressing;
options.DoNotSaveDynamicResponseInLogEntry = settings.DoNotSaveDynamicResponseInLogEntry;
options.FileSystemHandler = settings.FileSystemHandler;
options.HandleRequestsSynchronously = settings.HandleRequestsSynchronously;
options.Logger = settings.Logger;
options.MaxRequestLogCount = settings.MaxRequestLogCount;
options.PostWireMockMiddlewareInit = settings.PostWireMockMiddlewareInit;
options.PreWireMockMiddlewareInit = settings.PreWireMockMiddlewareInit;
options.QueryParameterMultipleValueSupport = settings.QueryParameterMultipleValueSupport;
options.RequestLogExpirationDuration = settings.RequestLogExpirationDuration;
options.PostWireMockMiddlewareInit = settings.PostWireMockMiddlewareInit;
options.Logger = settings.Logger;
options.DisableJsonBodyParsing = settings.DisableJsonBodyParsing;
options.HandleRequestsSynchronously = settings.HandleRequestsSynchronously;
options.SaveUnmatchedRequests = settings.SaveUnmatchedRequests;
options.DoNotSaveDynamicResponseInLogEntry = settings.DoNotSaveDynamicResponseInLogEntry;
options.QueryParameterMultipleValueSupport = settings.QueryParameterMultipleValueSupport;
if (settings.CustomCertificateDefined)
{
@@ -43,8 +32,6 @@ internal static class WireMockMiddlewareOptionsHelper
options.X509CertificatePassword = settings.CertificateSettings.X509CertificatePassword;
}
postConfigure?.Invoke(options);
return options;
}
}

View File

@@ -23,11 +23,16 @@ using static WireMock.Util.CSharpFormatter;
namespace WireMock.Serialization;
internal class MappingConverter(MatcherMapper mapper)
internal class MappingConverter
{
private static readonly string AcceptOnMatch = MatchBehaviour.AcceptOnMatch.GetFullyQualifiedEnumValue();
private readonly MatcherMapper _mapper = Guard.NotNull(mapper);
private readonly MatcherMapper _mapper;
public MappingConverter(MatcherMapper mapper)
{
_mapper = Guard.NotNull(mapper);
}
public string ToCSharpCode(IMapping mapping, MappingConverterSettings? settings = null)
{
@@ -72,26 +77,26 @@ internal class MappingConverter(MatcherMapper mapper)
sb.AppendLine(" .Given(Request.Create()");
sb.AppendLine($" .UsingMethod({To1Or2Or3Arguments(methodMatcher?.MatchBehaviour, methodMatcher?.MatchOperator, methodMatcher?.Methods, HttpRequestMethod.GET)})");
if (pathMatcher?.Matchers != null)
if (pathMatcher is { Matchers: { } })
{
sb.AppendLine($" .WithPath({To1Or2Arguments(pathMatcher.MatchOperator, pathMatcher.Matchers)})");
}
else if (urlMatcher?.Matchers != null)
else if (urlMatcher is { Matchers: { } })
{
sb.AppendLine($" .WithUrl({To1Or2Arguments(urlMatcher.MatchOperator, urlMatcher.Matchers)})");
}
foreach (var paramsMatcher in paramsMatchers.Where(pm => pm.Matchers != null))
foreach (var paramsMatcher in paramsMatchers)
{
sb.AppendLine($" .WithParam({To2Or3Arguments(paramsMatcher.Key, paramsMatcher.MatchBehaviour, paramsMatcher.Matchers!)})");
sb.AppendLine($" .WithParam({To1Or2Or3Arguments(paramsMatcher.Key, paramsMatcher.MatchBehaviour, paramsMatcher.Matchers!)})");
}
if (clientIPMatcher?.Matchers != null)
if (clientIPMatcher is { Matchers: { } })
{
sb.AppendLine($" .WithClientIP({ToValueArguments(GetStringArray(clientIPMatcher.Matchers))})");
}
foreach (var headerMatcher in headerMatchers.Where(h => h.Matchers != null))
foreach (var headerMatcher in headerMatchers.Where(h => h.Matchers is { }))
{
var headerBuilder = new StringBuilder($"\"{headerMatcher.Name}\", {ToValueArguments(GetStringArray(headerMatcher.Matchers!))}, true");
if (headerMatcher.MatchOperator != MatchOperator.Or)
@@ -101,7 +106,7 @@ internal class MappingConverter(MatcherMapper mapper)
sb.AppendLine($" .WithHeader({headerBuilder})");
}
foreach (var cookieMatcher in cookieMatchers.Where(c => c.Matchers != null))
foreach (var cookieMatcher in cookieMatchers.Where(h => h.Matchers is { }))
{
sb.AppendLine($" .WithCookie(\"{cookieMatcher.Name}\", {ToValueArguments(GetStringArray(cookieMatcher.Matchers!))}, true)");
}
@@ -112,7 +117,7 @@ internal class MappingConverter(MatcherMapper mapper)
}
#if GRAPHQL
if (requestMessageGraphQLMatcher?.Matchers != null)
if (requestMessageGraphQLMatcher is { Matchers: { } })
{
if (requestMessageGraphQLMatcher.Matchers.OfType<GraphQLMatcher>().FirstOrDefault() is { } graphQLMatcher && graphQLMatcher.GetPatterns().Any())
{
@@ -122,7 +127,7 @@ internal class MappingConverter(MatcherMapper mapper)
#endif
#if MIMEKIT
if (requestMessageMultiPartMatcher?.Matchers != null)
if (requestMessageMultiPartMatcher is { Matchers: { } })
{
if (requestMessageMultiPartMatcher.Matchers.OfType<MimePartMatcher>().Any())
{
@@ -132,13 +137,13 @@ internal class MappingConverter(MatcherMapper mapper)
#endif
#if PROTOBUF
if (requestMessageProtoBufMatcher?.Matcher != null)
if (requestMessageProtoBufMatcher is { Matcher: { } })
{
sb.AppendLine(" // .WithBodyAsProtoBuf() is not yet supported");
}
#endif
if (requestMessageBodyMatcher?.Matchers != null)
if (requestMessageBodyMatcher is { Matchers: { } })
{
var firstMatcher = requestMessageBodyMatcher.Matchers.FirstOrDefault();
@@ -149,15 +154,15 @@ internal class MappingConverter(MatcherMapper mapper)
break;
case JsonMatcher jsonMatcher:
{
var matcherType = jsonMatcher.GetType().Name;
sb.AppendLine($" .WithBody(new {matcherType}(");
sb.AppendLine($" value: {ConvertToAnonymousObjectDefinition(jsonMatcher.Value, 3)},");
sb.AppendLine($" ignoreCase: {ToCSharpBooleanLiteral(jsonMatcher.IgnoreCase)},");
sb.AppendLine($" regex: {ToCSharpBooleanLiteral(jsonMatcher.Regex)}");
sb.AppendLine(@" ))");
break;
}
{
var matcherType = jsonMatcher.GetType().Name;
sb.AppendLine($" .WithBody(new {matcherType}(");
sb.AppendLine($" value: {ConvertToAnonymousObjectDefinition(jsonMatcher.Value, 3)},");
sb.AppendLine($" ignoreCase: {ToCSharpBooleanLiteral(jsonMatcher.IgnoreCase)},");
sb.AppendLine($" regex: {ToCSharpBooleanLiteral(jsonMatcher.Regex)}");
sb.AppendLine(@" ))");
break;
}
}
}
@@ -304,7 +309,7 @@ internal class MappingConverter(MatcherMapper mapper)
Response = new ResponseModel()
};
if (methodMatcher != null)
if (methodMatcher is { Methods: { } })
{
mappingModel.Request.Methods = methodMatcher.Methods;
mappingModel.Request.MethodsRejectOnMatch = methodMatcher.MatchBehaviour == MatchBehaviour.RejectOnMatch ? true : null;
@@ -316,7 +321,7 @@ internal class MappingConverter(MatcherMapper mapper)
mappingModel.Request.HttpVersion = httpVersionMatcher.HttpVersion;
}
if (clientIPMatcher?.Matchers != null)
if (clientIPMatcher is { Matchers: { } })
{
var clientIPMatchers = _mapper.Map(clientIPMatcher.Matchers);
mappingModel.Request.Path = new ClientIPModel
@@ -326,7 +331,7 @@ internal class MappingConverter(MatcherMapper mapper)
};
}
if (pathMatcher?.Matchers != null)
if (pathMatcher is { Matchers: { } })
{
var pathMatchers = _mapper.Map(pathMatcher.Matchers);
mappingModel.Request.Path = new PathModel
@@ -335,7 +340,7 @@ internal class MappingConverter(MatcherMapper mapper)
MatchOperator = pathMatchers?.Length > 1 ? pathMatcher.MatchOperator.ToString() : null
};
}
else if (urlMatcher?.Matchers != null)
else if (urlMatcher is { Matchers: { } })
{
var urlMatchers = _mapper.Map(urlMatcher.Matchers);
mappingModel.Request.Url = new UrlModel
@@ -533,7 +538,7 @@ internal class MappingConverter(MatcherMapper mapper)
return stringMatchers.SelectMany(m => m.GetPatterns()).Select(p => p.GetPattern()).ToArray();
}
private static string To2Or3Arguments(string key, MatchBehaviour? matchBehaviour, IReadOnlyList<IStringMatcher> matchers)
private static string To1Or2Or3Arguments(string key, MatchBehaviour? matchBehaviour, IReadOnlyList<IStringMatcher> matchers)
{
var sb = new StringBuilder($"\"{key}\", ");
@@ -542,7 +547,7 @@ internal class MappingConverter(MatcherMapper mapper)
sb.AppendFormat("{0}, ", matchBehaviour.Value.GetFullyQualifiedEnumValue());
}
sb.AppendFormat("{0}", MappingConverterUtils.ToCSharpCodeArguments(matchers));
sb.AppendFormat("{0}", ToValueArguments(GetStringArray(matchers), string.Empty));
return sb.ToString();
}
@@ -561,16 +566,7 @@ internal class MappingConverter(MatcherMapper mapper)
private static string To1Or2Arguments(MatchOperator? matchOperator, IReadOnlyList<IStringMatcher> matchers)
{
var sb = new StringBuilder();
if (matchOperator.HasValue && matchOperator != MatchOperator.Or)
{
sb.AppendFormat("{0}, ", matchOperator.Value.GetFullyQualifiedEnumValue());
}
sb.AppendFormat("{0}", MappingConverterUtils.ToCSharpCodeArguments(matchers));
return sb.ToString();
return To1Or2Arguments(matchOperator, GetStringArray(matchers), string.Empty);
}
private static string To1Or2Arguments(MatchOperator? matchOperator, string[]? values, string defaultValue)

View File

@@ -18,7 +18,6 @@ using WireMock.Http;
using WireMock.Logging;
using WireMock.Matchers;
using WireMock.Matchers.Request;
using WireMock.Owin;
using WireMock.RequestBuilders;
using WireMock.ResponseProviders;
using WireMock.Serialization;
@@ -322,26 +321,28 @@ public partial class WireMockServer
InitSettings(_settings);
// _options
if (settings.GlobalProcessingDelay != null)
{
_options.RequestProcessingDelay = TimeSpan.FromMilliseconds(settings.GlobalProcessingDelay.Value);
}
_options.AllowBodyForAllHttpMethods = settings.AllowBodyForAllHttpMethods;
_options.AllowPartialMapping = settings.AllowPartialMapping;
_options.HandleRequestsSynchronously = settings.HandleRequestsSynchronously;
_options.MaxRequestLogCount = settings.MaxRequestLogCount;
_options.RequestLogExpirationDuration = settings.RequestLogExpirationDuration;
// _settings & _options
#if USE_ASPNETCORE
if (Enum.TryParse<CorsPolicyOptions>(settings.CorsPolicyOptions, true, out var corsPolicyOptions))
{
_settings.CorsPolicyOptions = corsPolicyOptions;
_options.CorsPolicyOptions = corsPolicyOptions;
}
#endif
WireMockMiddlewareOptionsHelper.InitFromSettings(_settings, _options, o =>
{
if (settings.GlobalProcessingDelay != null)
{
o.RequestProcessingDelay = TimeSpan.FromMilliseconds(settings.GlobalProcessingDelay.Value);
}
#if USE_ASPNETCORE
o.CorsPolicyOptions = corsPolicyOptions;
o.ClientCertificateMode = _settings.ClientCertificateMode;
o.AcceptAnyClientCertificate = _settings.AcceptAnyClientCertificate;
_options.ClientCertificateMode = _settings.ClientCertificateMode;
_options.AcceptAnyClientCertificate = _settings.AcceptAnyClientCertificate;
#endif
});
return ResponseMessageBuilder.Create(200, "Settings updated");
}

View File

@@ -20,6 +20,7 @@ using WireMock.Exceptions;
using WireMock.Handlers;
using WireMock.Http;
using WireMock.Logging;
using WireMock.Matchers.Request;
using WireMock.Models;
using WireMock.Owin;
using WireMock.RequestBuilders;
@@ -368,10 +369,9 @@ public partial class WireMockServer : IWireMockServer
}
}
WireMockMiddlewareOptionsHelper.InitFromSettings(settings, _options, o =>
{
o.LogEntries.CollectionChanged += LogEntries_CollectionChanged;
});
WireMockMiddlewareOptionsHelper.InitFromSettings(settings, _options);
_options.LogEntries.CollectionChanged += LogEntries_CollectionChanged;
_matcherMapper = new MatcherMapper(_settings);
_mappingConverter = new MappingConverter(_matcherMapper);
@@ -649,11 +649,13 @@ public partial class WireMockServer : IWireMockServer
{
if (settings.AllowBodyForAllHttpMethods == true)
{
_options.AllowBodyForAllHttpMethods = _settings.AllowBodyForAllHttpMethods;
_settings.Logger.Info("AllowBodyForAllHttpMethods is set to True");
}
if (settings.AllowOnlyDefinedHttpStatusCodeInResponse == true)
{
_options.AllowOnlyDefinedHttpStatusCodeInResponse = _settings.AllowOnlyDefinedHttpStatusCodeInResponse;
_settings.Logger.Info("AllowOnlyDefinedHttpStatusCodeInResponse is set to True");
}

View File

@@ -1,8 +1,8 @@
// Copyright © WireMock.Net
using System;
using System.Text.RegularExpressions;
using Stef.Validation;
using WireMock.Constants;
namespace WireMock.Util;
@@ -11,7 +11,7 @@ namespace WireMock.Util;
/// </summary>
internal static class HttpVersionParser
{
private static readonly Regex HttpVersionRegex = new(@"HTTP/(\d+(\.\d+)?(?!\.))", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled, WireMockConstants.DefaultRegexTimeout);
private static readonly Regex HttpVersionRegex = new(@"HTTP/(\d+(\.\d+)?(?!\.))", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled, TimeSpan.FromMilliseconds(100));
/// <summary>
/// Try to extract the version (as a string) from the protocol.

View File

@@ -1,23 +0,0 @@
// Copyright © WireMock.Net
using System.Collections.Generic;
using System.Linq;
using AnyOfTypes;
using WireMock.Extensions;
using WireMock.Matchers;
using WireMock.Models;
namespace WireMock.Util;
internal static class MappingConverterUtils
{
internal static string ToCSharpCodeArguments(IReadOnlyList<IMatcher> matchers)
{
return string.Join(", ", matchers.Select(m => m.GetCSharpCodeArguments()));
}
internal static string ToCSharpCodeArguments(AnyOf<string, StringPattern>[] patterns)
{
return string.Join(", ", patterns.Select(p => CSharpFormatter.ToCSharpStringLiteral(p.GetPattern())));
}
}

View File

@@ -5,7 +5,6 @@ using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Sockets;
using System.Text.RegularExpressions;
using WireMock.Constants;
namespace WireMock.Util;
@@ -14,7 +13,7 @@ namespace WireMock.Util;
/// </summary>
internal static class PortUtils
{
private static readonly Regex UrlDetailsRegex = new(@"^((?<proto>\w+)://)(?<host>[^/]+?):(?<port>\d+)\/?$", RegexOptions.Compiled, WireMockConstants.DefaultRegexTimeout);
private static readonly Regex UrlDetailsRegex = new(@"^((?<proto>\w+)://)(?<host>[^/]+?):(?<port>\d+)\/?$", RegexOptions.Compiled);
/// <summary>
/// Finds a free TCP port.

View File

@@ -1,14 +1,16 @@
// Copyright © WireMock.Net
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using WireMock.Constants;
using WireMock.RegularExpressions;
namespace WireMock.Util;
internal static class RegexUtils
{
private static readonly TimeSpan RegexTimeOut = new(0, 0, 10);
public static Dictionary<string, string> GetNamedGroups(Regex regex, string input)
{
var namedGroupsDictionary = new Dictionary<string, string>();
@@ -36,11 +38,11 @@ internal static class RegexUtils
{
if (useRegexExtended)
{
var regexExtended = new RegexExtended(pattern!, RegexOptions.None, WireMockConstants.DefaultRegexTimeout);
var regexExtended = new RegexExtended(pattern!, RegexOptions.None, RegexTimeOut);
return (true, regexExtended.IsMatch(input));
}
var regex = new Regex(pattern, RegexOptions.None, WireMockConstants.DefaultRegexTimeout);
var regex = new Regex(pattern, RegexOptions.None, RegexTimeOut);
return (true, regex.IsMatch(input));
}
catch

View File

@@ -1,56 +1,24 @@
// Copyright © WireMock.Net
using Nelibur.ObjectMapper;
using Riok.Mapperly.Abstractions;
using WireMock.Admin.Mappings;
using WireMock.Admin.Settings;
using WireMock.Settings;
namespace WireMock.Util;
internal sealed class TinyMapperUtils
[Mapper]
internal static partial class TinyMapperUtils
{
public static TinyMapperUtils Instance { get; } = new();
public static partial ProxyAndRecordSettingsModel? Map(ProxyAndRecordSettings? instance);
private TinyMapperUtils()
{
TinyMapper.Bind<ProxyAndRecordSettings, ProxyAndRecordSettingsModel>();
TinyMapper.Bind<WebProxySettings, WebProxySettingsModel>();
TinyMapper.Bind<WebProxySettings, WebProxyModel>();
TinyMapper.Bind<ProxyUrlReplaceSettings, ProxyUrlReplaceSettingsModel>();
public static partial ProxyAndRecordSettings? Map(ProxyAndRecordSettingsModel? model);
TinyMapper.Bind<ProxyAndRecordSettingsModel, ProxyAndRecordSettings>();
TinyMapper.Bind<WebProxySettingsModel, WebProxySettings>();
TinyMapper.Bind<WebProxyModel, WebProxySettings>();
TinyMapper.Bind<ProxyUrlReplaceSettingsModel, ProxyUrlReplaceSettings>();
}
public static partial ProxyUrlReplaceSettingsModel? Map(ProxyUrlReplaceSettings? instance);
public ProxyAndRecordSettingsModel? Map(ProxyAndRecordSettings? instance)
{
return instance == null ? null : TinyMapper.Map<ProxyAndRecordSettingsModel>(instance);
}
public static partial ProxyUrlReplaceSettings? Map(ProxyUrlReplaceSettingsModel? model);
public ProxyAndRecordSettings? Map(ProxyAndRecordSettingsModel? model)
{
return model == null ? null : TinyMapper.Map<ProxyAndRecordSettings>(model);
}
public static partial WebProxyModel? Map(WebProxySettings? instance);
public ProxyUrlReplaceSettingsModel? Map(ProxyUrlReplaceSettings? instance)
{
return instance == null ? null : TinyMapper.Map<ProxyUrlReplaceSettingsModel>(instance);
}
public ProxyUrlReplaceSettings? Map(ProxyUrlReplaceSettingsModel? model)
{
return model == null ? null : TinyMapper.Map<ProxyUrlReplaceSettings>(model);
}
public WebProxyModel? Map(WebProxySettings? instance)
{
return instance == null ? null : TinyMapper.Map<WebProxyModel>(instance);
}
public WebProxySettings? Map(WebProxyModel? model)
{
return model == null ? null : TinyMapper.Map<WebProxySettings>(model);
}
public static partial WebProxySettings? Map(WebProxyModel? model);
}

View File

@@ -63,10 +63,10 @@
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="NJsonSchema.Extensions" Version="0.1.0" />
<PackageReference Include="NSwag.Core" Version="13.16.1" />
<PackageReference Include="Riok.Mapperly" Version="3.6.0" />
<PackageReference Include="SimMetrics.Net" Version="1.0.5" />
<PackageReference Include="JmesPath.Net" Version="1.0.125" />
<PackageReference Include="AnyOf" Version="0.3.0" />
<PackageReference Include="TinyMapper" Version="3.0.3" />
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' != 'netstandard1.3' ">

View File

@@ -18,7 +18,7 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Aspire.Hosting.AppHost" Version="8.2.0" />
<PackageReference Include="Aspire.Hosting.AppHost" Version="8.0.0" />
</ItemGroup>
<ItemGroup>

View File

@@ -8,7 +8,10 @@ namespace WireMock.Net.Aspire.Tests;
[ExcludeFromCodeCoverage]
internal static class DockerUtils
{
public static Lazy<bool> IsDockerRunningLinuxContainerMode => new(() => IsDockerRunning() && IsLinuxContainerMode());
public static bool IsDockerRunningLinuxContainerMode()
{
return IsDockerRunning() && IsLinuxContainerMode();
}
private static bool IsDockerRunning()
{

View File

@@ -1,16 +0,0 @@
// Copyright © WireMock.Net
namespace WireMock.Net.Aspire.Tests.Facts;
public sealed class DockerIsRunningInLinuxContainerModeFact : FactAttribute
{
private const string SkipReason = "Docker is not running in Linux container mode. Skipping test.";
public DockerIsRunningInLinuxContainerModeFact()
{
if (!DockerUtils.IsDockerRunningLinuxContainerMode.Value)
{
Skip = SkipReason;
}
}
}

View File

@@ -3,7 +3,6 @@
using System.Net.Http.Json;
using FluentAssertions;
using Projects;
using WireMock.Net.Aspire.Tests.Facts;
using Xunit.Abstractions;
namespace WireMock.Net.Aspire.Tests;
@@ -12,9 +11,15 @@ public class IntegrationTests(ITestOutputHelper output)
{
private record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary);
[DockerIsRunningInLinuxContainerModeFact]
[Fact]
public async Task StartAppHostWithWireMockAndCreateHttpClientToCallTheMockedWeatherForecastEndpoint()
{
if (!DockerUtils.IsDockerRunningLinuxContainerMode())
{
output.WriteLine("Docker is not running in Linux container mode. Skipping test.");
return;
}
// Arrange
var appHostBuilder = await DistributedApplicationTestingBuilder.CreateAsync<WireMock_Net_Aspire_TestAppHost>();
await using var app = await appHostBuilder.BuildAsync();
@@ -39,9 +44,15 @@ public class IntegrationTests(ITestOutputHelper output)
weatherForecasts2.Should().HaveCount(5);
}
[DockerIsRunningInLinuxContainerModeFact]
[Fact]
public async Task StartAppHostWithWireMockAndCreateWireMockAdminClientToCallTheAdminEndpoint()
{
if (!DockerUtils.IsDockerRunningLinuxContainerMode())
{
output.WriteLine("Docker is not running in Linux container mode. Skipping test.");
return;
}
// Arrange
var appHostBuilder = await DistributedApplicationTestingBuilder.CreateAsync<WireMock_Net_Aspire_TestAppHost>();
await using var app = await appHostBuilder.BuildAsync();

View File

@@ -12,7 +12,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Aspire.Hosting.Testing" Version="8.2.0" />
<PackageReference Include="Aspire.Hosting.Testing" Version="8.0.0" />
<PackageReference Include="Codecov" Version="1.13.0" />
<PackageReference Include="coverlet.msbuild" Version="6.0.2">
<PrivateAssets>all</PrivateAssets>

View File

@@ -47,7 +47,6 @@ message HelloReply {
.WithPath("/grpc/greet.Greeter/SayHello")
.WithBodyAsProtoBuf(ProtoDefinition, "greet.HelloRequest", protoBufJsonMatcher)
)
.WithGuid(_guidUtilsMock.Object.NewGuid())
.RespondWith(Response.Create()
.WithHeader("Content-Type", "application/grpc")
.WithBodyAsProtoBuf(ProtoDefinition, "greet.HelloReply",
@@ -67,7 +66,6 @@ message HelloReply {
.WithBodyAsProtoBuf("greet.HelloRequest", protoBufJsonMatcher)
)
.WithProtoDefinition(ProtoDefinition)
.WithGuid(_guidUtilsMock.Object.NewGuid())
.RespondWith(Response.Create()
.WithHeader("Content-Type", "application/grpc")
.WithBodyAsProtoBuf("greet.HelloReply",
@@ -88,7 +86,6 @@ message HelloReply {
.WithBodyAsProtoBuf("greet.HelloRequest", protoBufJsonMatcher)
)
.WithProtoDefinition("my-greeter")
.WithGuid(_guidUtilsMock.Object.NewGuid())
.RespondWith(Response.Create()
.WithHeader("Content-Type", "application/grpc")
.WithBodyAsProtoBuf("greet.HelloReply",
@@ -109,7 +106,6 @@ message HelloReply {
.WithBodyAsProtoBuf("greet.HelloRequest")
)
.WithProtoDefinition("my-greeter")
.WithGuid(_guidUtilsMock.Object.NewGuid())
.RespondWith(Response.Create()
.WithHeader("Content-Type", "application/grpc")
.WithBodyAsProtoBuf("greet.HelloReply",

View File

@@ -2,8 +2,8 @@
server
.Given(Request.Create()
.UsingMethod("GET")
.WithPath(new WildcardMatcher(WireMock.Matchers.MatchBehaviour.AcceptOnMatch, "/foo1", false, WireMock.Matchers.MatchOperator.Or))
.WithParam("p1", new ExactMatcher(WireMock.Matchers.MatchBehaviour.AcceptOnMatch, false, WireMock.Matchers.MatchOperator.And, "xyz"))
.WithPath("/foo1")
.WithParam("p1", "xyz")
)
.WithGuid("90356dba-b36c-469a-a17e-669cd84f1f05")
.RespondWith(Response.Create()

View File

@@ -2,7 +2,25 @@
server
.Given(Request.Create()
.UsingMethod("POST")
.WithPath(new WildcardMatcher(WireMock.Matchers.MatchBehaviour.AcceptOnMatch, "/users/post2", false, WireMock.Matchers.MatchOperator.Or))
.WithPath("/users/post1")
.WithBody(new JsonMatcher(
value: new
{
city = "Amsterdam",
country = "The Netherlands"
},
ignoreCase: false,
regex: false
))
)
.WithGuid("90356dba-b36c-469a-a17e-669cd84f1f05")
.RespondWith(Response.Create()
);
server
.Given(Request.Create()
.UsingMethod("POST")
.WithPath("/users/post2")
.WithBody(new JsonPartialMatcher(
value: new
{
@@ -19,11 +37,23 @@ server
Some ""value"" in Line2")
);
server
.Given(Request.Create()
.UsingMethod("GET")
.WithPath("/foo1")
.WithParam("p1", "xyz")
)
.WithGuid("f74fd144-df53-404f-8e35-da22a640bd5f")
.RespondWith(Response.Create()
.WithStatusCode(200)
.WithBody("1")
);
server
.Given(Request.Create()
.UsingMethod("POST")
.WithPath(new WildcardMatcher(WireMock.Matchers.MatchBehaviour.AcceptOnMatch, "/foo2", false, WireMock.Matchers.MatchOperator.Or))
.WithParam("p2", new ExactMatcher(WireMock.Matchers.MatchBehaviour.AcceptOnMatch, false, WireMock.Matchers.MatchOperator.And, "abc"))
.WithPath("/foo2")
.WithParam("p2", "abc")
.WithHeader("h1", "W/\"234f2q3r\"", true)
)
.WithGuid("4126dec8-470b-4eff-93bb-c24f83b8b1fd")
@@ -34,28 +64,10 @@ server
.WithBody("2")
);
server
.Given(Request.Create()
.UsingMethod("POST")
.WithPath(new WildcardMatcher(WireMock.Matchers.MatchBehaviour.AcceptOnMatch, "/users/post1", false, WireMock.Matchers.MatchOperator.Or))
.WithBody(new JsonMatcher(
value: new
{
city = "Amsterdam",
country = "The Netherlands"
},
ignoreCase: false,
regex: false
))
)
.WithGuid("90356dba-b36c-469a-a17e-669cd84f1f05")
.RespondWith(Response.Create()
);
server
.Given(Request.Create()
.UsingMethod("DELETE")
.WithUrl(new WildcardMatcher(WireMock.Matchers.MatchBehaviour.AcceptOnMatch, "https://localhost/test", false, WireMock.Matchers.MatchOperator.Or))
.WithUrl("https://localhost/test")
)
.WithGuid("c9929240-7ae8-4a5d-8ed8-0913479f6eeb")
.RespondWith(Response.Create()
@@ -96,15 +108,3 @@ text
})
);
server
.Given(Request.Create()
.UsingMethod("GET")
.WithPath(new WildcardMatcher(WireMock.Matchers.MatchBehaviour.AcceptOnMatch, "/foo1", false, WireMock.Matchers.MatchOperator.Or))
.WithParam("p1", new ExactMatcher(WireMock.Matchers.MatchBehaviour.AcceptOnMatch, false, WireMock.Matchers.MatchOperator.And, "xyz"))
)
.WithGuid("f74fd144-df53-404f-8e35-da22a640bd5f")
.RespondWith(Response.Create()
.WithStatusCode(200)
.WithBody("1")
);

View File

@@ -30,7 +30,6 @@ using WireMock.ResponseBuilders;
using WireMock.Server;
using WireMock.Settings;
using WireMock.Types;
using WireMock.Util;
using Xunit;
namespace WireMock.Net.Tests.AdminApi;
@@ -40,14 +39,6 @@ public partial class WireMockAdminApiTests
{
private static readonly VerifySettings VerifySettings = new();
private readonly Mock<IGuidUtils> _guidUtilsMock = new();
public WireMockAdminApiTests()
{
var startGuid = 1000;
_guidUtilsMock.Setup(g => g.NewGuid()).Returns(() => new Guid($"98fae52e-76df-47d9-876f-2ee32e93{startGuid++}"));
}
static WireMockAdminApiTests()
{
VerifyNewtonsoftJson.Enable(VerifySettings);

View File

@@ -1,22 +0,0 @@
// Copyright © WireMock.Net
using System;
using Xunit;
namespace WireMock.Net.Tests.Facts;
public sealed class IgnoreOnContinuousIntegrationFact : FactAttribute
{
private const string SkipReason = "Ignore when run via CI/CD";
private static readonly bool IsContinuousIntegrationAzure = bool.TryParse(Environment.GetEnvironmentVariable("TF_BUILD"), out var isTF) && isTF;
private static readonly bool IsContinuousIntegrationGithub = bool.TryParse(Environment.GetEnvironmentVariable("GITHUB_ACTIONS"), out var isGH) && isGH;
private static readonly bool IsContinuousIntegration = IsContinuousIntegrationAzure || IsContinuousIntegrationGithub;
public IgnoreOnContinuousIntegrationFact()
{
if (IsContinuousIntegration)
{
Skip = SkipReason;
}
}
}

View File

@@ -32,35 +32,6 @@
Body: { msg: "Hello world!"}
}
},
{
Guid: 98fae52e-76df-47d9-876f-2ee32e931001,
UpdatedAt: 2023-01-14 15:16:17,
Request: {
Path: {
Matchers: [
{
Name: WildcardMatcher,
Pattern: /users/post1,
IgnoreCase: false
}
]
},
Methods: [
POST
],
Body: {
Matcher: {
Name: JsonMatcher,
Pattern: {
Request: Hello?
},
IgnoreCase: false,
Regex: false
}
}
},
Response: {}
},
{
Guid: 98fae52e-76df-47d9-876f-2ee32e931002,
UpdatedAt: 2023-01-14 15:16:17,
@@ -135,33 +106,31 @@
Response: {}
},
{
Guid: 98fae52e-76df-47d9-876f-2ee32e931004,
Guid: 98fae52e-76df-47d9-876f-2ee32e931001,
UpdatedAt: 2023-01-14 15:16:17,
Request: {
Path: {
Matchers: [
{
Name: WildcardMatcher,
Pattern: /regex,
Pattern: /users/post1,
IgnoreCase: false
}
]
},
Methods: [
GET
POST
],
Params: [
{
Name: foo,
Matchers: [
{
Name: RegexMatcher,
Pattern: .*,
IgnoreCase: false
}
]
Body: {
Matcher: {
Name: JsonMatcher,
Pattern: {
Request: Hello?
},
IgnoreCase: false,
Regex: false
}
]
}
},
Response: {}
}

View File

@@ -2,8 +2,8 @@
builder
.Given(Request.Create()
.UsingMethod("GET")
.WithPath(new WildcardMatcher(WireMock.Matchers.MatchBehaviour.AcceptOnMatch, "/foo", false, WireMock.Matchers.MatchOperator.Or))
.WithParam("test", new LinqMatcher(WireMock.Matchers.MatchBehaviour.AcceptOnMatch, WireMock.Matchers.MatchOperator.Or, "it.Length < 10"))
.WithPath("/foo")
.WithParam("test", "it.Length < 10")
)
.WithGuid("41372914-1838-4c67-916b-b9aacdd096ce")
.RespondWith(Response.Create()
@@ -13,24 +13,7 @@ builder
builder
.Given(Request.Create()
.UsingMethod("POST")
.WithPath(new WildcardMatcher(WireMock.Matchers.MatchBehaviour.AcceptOnMatch, "/users/post1", false, WireMock.Matchers.MatchOperator.Or))
.WithBody(new JsonMatcher(
value: new
{
Request = "Hello?"
},
ignoreCase: false,
regex: false
))
)
.WithGuid("98fae52e-76df-47d9-876f-2ee32e931001")
.RespondWith(Response.Create()
);
builder
.Given(Request.Create()
.UsingMethod("POST")
.WithPath(new WildcardMatcher(WireMock.Matchers.MatchBehaviour.AcceptOnMatch, "/users/post2", false, WireMock.Matchers.MatchOperator.Or))
.WithPath("/users/post2")
.WithBody(new JsonMatcher(
value: new
{
@@ -48,7 +31,7 @@ builder
builder
.Given(Request.Create()
.UsingMethod("POST")
.WithPath(new WildcardMatcher(WireMock.Matchers.MatchBehaviour.AcceptOnMatch, "/form-urlencoded", false, WireMock.Matchers.MatchOperator.Or))
.WithPath("/form-urlencoded")
.WithHeader("Content-Type", "application/x-www-form-urlencoded", true)
.WithBody("name=John Doe")
)
@@ -58,11 +41,18 @@ builder
builder
.Given(Request.Create()
.UsingMethod("GET")
.WithPath(new WildcardMatcher(WireMock.Matchers.MatchBehaviour.AcceptOnMatch, "/regex", false, WireMock.Matchers.MatchOperator.Or))
.WithParam("foo", new RegexMatcher(WireMock.Matchers.MatchBehaviour.AcceptOnMatch, ".*", false, true, WireMock.Matchers.MatchOperator.Or))
.UsingMethod("POST")
.WithPath("/users/post1")
.WithBody(new JsonMatcher(
value: new
{
Request = "Hello?"
},
ignoreCase: false,
regex: false
))
)
.WithGuid("98fae52e-76df-47d9-876f-2ee32e931004")
.WithGuid("98fae52e-76df-47d9-876f-2ee32e931001")
.RespondWith(Response.Create()
);

View File

@@ -2,8 +2,8 @@
server
.Given(Request.Create()
.UsingMethod("GET")
.WithPath(new WildcardMatcher(WireMock.Matchers.MatchBehaviour.AcceptOnMatch, "/foo", false, WireMock.Matchers.MatchOperator.Or))
.WithParam("test", new LinqMatcher(WireMock.Matchers.MatchBehaviour.AcceptOnMatch, WireMock.Matchers.MatchOperator.Or, "it.Length < 10"))
.WithPath("/foo")
.WithParam("test", "it.Length < 10")
)
.WithGuid("41372914-1838-4c67-916b-b9aacdd096ce")
.RespondWith(Response.Create()
@@ -13,24 +13,7 @@ server
server
.Given(Request.Create()
.UsingMethod("POST")
.WithPath(new WildcardMatcher(WireMock.Matchers.MatchBehaviour.AcceptOnMatch, "/users/post1", false, WireMock.Matchers.MatchOperator.Or))
.WithBody(new JsonMatcher(
value: new
{
Request = "Hello?"
},
ignoreCase: false,
regex: false
))
)
.WithGuid("98fae52e-76df-47d9-876f-2ee32e931001")
.RespondWith(Response.Create()
);
server
.Given(Request.Create()
.UsingMethod("POST")
.WithPath(new WildcardMatcher(WireMock.Matchers.MatchBehaviour.AcceptOnMatch, "/users/post2", false, WireMock.Matchers.MatchOperator.Or))
.WithPath("/users/post2")
.WithBody(new JsonMatcher(
value: new
{
@@ -48,7 +31,7 @@ server
server
.Given(Request.Create()
.UsingMethod("POST")
.WithPath(new WildcardMatcher(WireMock.Matchers.MatchBehaviour.AcceptOnMatch, "/form-urlencoded", false, WireMock.Matchers.MatchOperator.Or))
.WithPath("/form-urlencoded")
.WithHeader("Content-Type", "application/x-www-form-urlencoded", true)
.WithBody("name=John Doe")
)
@@ -58,11 +41,18 @@ server
server
.Given(Request.Create()
.UsingMethod("GET")
.WithPath(new WildcardMatcher(WireMock.Matchers.MatchBehaviour.AcceptOnMatch, "/regex", false, WireMock.Matchers.MatchOperator.Or))
.WithParam("foo", new RegexMatcher(WireMock.Matchers.MatchBehaviour.AcceptOnMatch, ".*", false, true, WireMock.Matchers.MatchOperator.Or))
.UsingMethod("POST")
.WithPath("/users/post1")
.WithBody(new JsonMatcher(
value: new
{
Request = "Hello?"
},
ignoreCase: false,
regex: false
))
)
.WithGuid("98fae52e-76df-47d9-876f-2ee32e931004")
.WithGuid("98fae52e-76df-47d9-876f-2ee32e931001")
.RespondWith(Response.Create()
);

View File

@@ -32,34 +32,6 @@
Body: { msg: "Hello world!"}
}
},
{
Guid: 98fae52e-76df-47d9-876f-2ee32e931001,
UpdatedAt: 2023-01-14T15:16:17,
Request: {
Path: {
Matchers: [
{
Name: WildcardMatcher,
Pattern: /users/post1,
IgnoreCase: false
}
]
},
Methods: [
POST
],
Body: {
Matcher: {
Name: JsonMatcher,
Pattern: {
Request: Hello?
},
IgnoreCase: false,
Regex: false
}
}
}
},
{
Guid: 98fae52e-76df-47d9-876f-2ee32e931002,
UpdatedAt: 2023-01-14T15:16:17,
@@ -132,33 +104,31 @@
}
},
{
Guid: 98fae52e-76df-47d9-876f-2ee32e931004,
Guid: 98fae52e-76df-47d9-876f-2ee32e931001,
UpdatedAt: 2023-01-14T15:16:17,
Request: {
Path: {
Matchers: [
{
Name: WildcardMatcher,
Pattern: /regex,
Pattern: /users/post1,
IgnoreCase: false
}
]
},
Methods: [
GET
POST
],
Params: [
{
Name: foo,
Matchers: [
{
Name: RegexMatcher,
Pattern: .*,
IgnoreCase: false
}
]
Body: {
Matcher: {
Name: JsonMatcher,
Pattern: {
Request: Hello?
},
IgnoreCase: false,
Regex: false
}
]
}
}
}
]

View File

@@ -102,13 +102,6 @@ public class MappingBuilderTests
.WithHeader("Content-Type", "application/x-www-form-urlencoded")
.WithBody(new FormUrlEncodedMatcher(["name=John Doe", "email=johndoe@example.com"]))
).RespondWith(Response.Create());
_sut.Given(Request.Create()
.WithPath("/regex")
.WithParam("foo", new RegexMatcher(".*"))
.UsingGet()
)
.RespondWith(Response.Create());
}
[Fact]
@@ -197,9 +190,9 @@ public class MappingBuilderTests
_sut.SaveMappingsToFolder(null);
// Verify
_fileSystemHandlerMock.Verify(fs => fs.GetMappingFolder(), Times.Exactly(5));
_fileSystemHandlerMock.Verify(fs => fs.FolderExists(mappingFolder), Times.Exactly(5));
_fileSystemHandlerMock.Verify(fs => fs.WriteMappingFile(It.IsAny<string>(), It.IsAny<string>()), Times.Exactly(5));
_fileSystemHandlerMock.Verify(fs => fs.GetMappingFolder(), Times.Exactly(4));
_fileSystemHandlerMock.Verify(fs => fs.FolderExists(mappingFolder), Times.Exactly(4));
_fileSystemHandlerMock.Verify(fs => fs.WriteMappingFile(It.IsAny<string>(), It.IsAny<string>()), Times.Exactly(4));
_fileSystemHandlerMock.VerifyNoOtherCalls();
}
@@ -215,8 +208,8 @@ public class MappingBuilderTests
// Verify
_fileSystemHandlerMock.Verify(fs => fs.GetMappingFolder(), Times.Never);
_fileSystemHandlerMock.Verify(fs => fs.FolderExists(path), Times.Exactly(5));
_fileSystemHandlerMock.Verify(fs => fs.WriteMappingFile(It.IsAny<string>(), It.IsAny<string>()), Times.Exactly(5));
_fileSystemHandlerMock.Verify(fs => fs.FolderExists(path), Times.Exactly(4));
_fileSystemHandlerMock.Verify(fs => fs.WriteMappingFile(It.IsAny<string>(), It.IsAny<string>()), Times.Exactly(4));
_fileSystemHandlerMock.VerifyNoOtherCalls();
}
}

View File

@@ -29,7 +29,7 @@ public class ExactObjectMatcherTests
object checkValue = new byte[] { 1, 2 };
// Act
var matcher = new ExactObjectMatcher([1, 2]);
var matcher = new ExactObjectMatcher(new byte[] { 1, 2 });
var score = matcher.IsMatch(checkValue).Score;
// Assert

View File

@@ -1,177 +0,0 @@
using FluentAssertions;
using WireMock.Matchers;
using Xunit;
namespace WireMock.Net.Tests.Matchers;
public class MatcherTests
{
[Fact]
public void ContentTypeMatcher_GetCSharpCodeArguments_ShouldReturnCorrectArguments()
{
// Arrange
var matcher = new ContentTypeMatcher("application/json");
// Act
var result = matcher.GetCSharpCodeArguments();
// Assert
result.Should().Be("new ContentTypeMatcher(WireMock.Matchers.MatchBehaviour.AcceptOnMatch, \"application/json\", false)");
}
[Fact]
public void ExactMatcher_GetCSharpCodeArguments_ShouldReturnCorrectArguments()
{
// Arrange
var matcher = new ExactMatcher("test");
// Act
var result = matcher.GetCSharpCodeArguments();
// Assert
result.Should().Be("new ExactMatcher(WireMock.Matchers.MatchBehaviour.AcceptOnMatch, false, WireMock.Matchers.MatchOperator.Or, \"test\")");
}
[Fact]
public void ExactObjectMatcher_GetCSharpCodeArguments_ShouldReturnNotImplemented()
{
// Arrange
var matcher = new ExactObjectMatcher(new { Name = "test" });
// Act
var result = matcher.GetCSharpCodeArguments();
// Assert
result.Should().Be("NotImplemented");
}
[Fact]
public void FormUrlEncodedMatcher_GetCSharpCodeArguments_ShouldReturnCorrectArguments()
{
// Arrange
var matcher = new FormUrlEncodedMatcher("key=value");
// Act
var result = matcher.GetCSharpCodeArguments();
// Assert
result.Should().Be("new FormUrlEncodedMatcher(WireMock.Matchers.MatchBehaviour.AcceptOnMatch, \"key=value\", false, WireMock.Matchers.MatchOperator.Or)");
}
[Fact]
public void JmesPathMatcher_GetCSharpCodeArguments_ShouldReturnCorrectArguments()
{
// Arrange
var matcher = new JmesPathMatcher("expression");
// Act
var result = matcher.GetCSharpCodeArguments();
// Assert
result.Should().Be("new JmesPathMatcher(WireMock.Matchers.MatchBehaviour.AcceptOnMatch, WireMock.Matchers.MatchOperator.Or, \"expression\")");
}
[Fact]
public void JsonMatcher_GetCSharpCodeArguments_ShouldReturnCorrectArguments()
{
// Arrange
var matcher = new JsonMatcher(new { key = "value" });
// Act
var result = matcher.GetCSharpCodeArguments();
// Assert
result.Should().StartWith("new JsonMatcher(WireMock.Matchers.MatchBehaviour.AcceptOnMatch,");
}
[Fact]
public void JsonPartialMatcher_GetCSharpCodeArguments_ShouldReturnCorrectArguments()
{
// Arrange
var matcher = new JsonPartialMatcher(new { key = "value" });
// Act
var result = matcher.GetCSharpCodeArguments();
// Assert
result.Should().StartWith("new JsonPartialMatcher(WireMock.Matchers.MatchBehaviour.AcceptOnMatch,");
}
[Fact]
public void JsonPartialWildcardMatcher_GetCSharpCodeArguments_ShouldReturnCorrectArguments()
{
// Arrange
var matcher = new JsonPartialWildcardMatcher(new { key = "value" });
// Act
var result = matcher.GetCSharpCodeArguments();
// Assert
result.Should().StartWith("new JsonPartialWildcardMatcher(WireMock.Matchers.MatchBehaviour.AcceptOnMatch,");
}
[Fact]
public void LinqMatcher_GetCSharpCodeArguments_ShouldReturnCorrectArguments()
{
// Arrange
var matcher = new LinqMatcher("it.Contains(\"test\"");
// Act
var result = matcher.GetCSharpCodeArguments();
// Assert
result.Should().Be("new LinqMatcher(WireMock.Matchers.MatchBehaviour.AcceptOnMatch, WireMock.Matchers.MatchOperator.Or, \"it.Contains(\\\"test\\\"\")");
}
[Fact]
public void RegexMatcher_GetCSharpCodeArguments_ShouldReturnCorrectArguments()
{
// Arrange
var matcher = new RegexMatcher("pattern");
// Act
var result = matcher.GetCSharpCodeArguments();
// Assert
result.Should().Be("new RegexMatcher(WireMock.Matchers.MatchBehaviour.AcceptOnMatch, \"pattern\", false, true, WireMock.Matchers.MatchOperator.Or)");
}
[Fact]
public void SimMetricsMatcher_GetCSharpCodeArguments_ShouldReturnCorrectArguments()
{
// Arrange
var matcher = new SimMetricsMatcher("test");
// Act
var result = matcher.GetCSharpCodeArguments();
// Assert
result.Should().Be("new SimMetricsMatcher.Levenstein(WireMock.Matchers.MatchBehaviour.AcceptOnMatch, \"test\", SimMetrics.Net.SimMetricType.Levenstein, WireMock.Matchers.MatchOperator.Average)");
}
[Fact]
public void WildcardMatcher_GetCSharpCodeArguments_ShouldReturnCorrectArguments()
{
// Arrange
var matcher = new WildcardMatcher("pattern");
// Act
var result = matcher.GetCSharpCodeArguments();
// Assert
result.Should().Be("new WildcardMatcher(WireMock.Matchers.MatchBehaviour.AcceptOnMatch, \"pattern\", false, WireMock.Matchers.MatchOperator.Or)");
}
[Fact]
public void XPathMatcher_GetCSharpCodeArguments_ShouldReturnCorrectArguments()
{
// Arrange
var matcher = new XPathMatcher("pattern1");
// Act
var result = matcher.GetCSharpCodeArguments();
// Assert
result.Should().Be("new XPathMatcher(WireMock.Matchers.MatchBehaviour.AcceptOnMatch, WireMock.Matchers.MatchOperator.Or, null, \"pattern1\")");
}
}

View File

@@ -25,277 +25,278 @@ using Response = Microsoft.AspNetCore.Http.HttpResponse;
using Microsoft.Extensions.Primitives;
#endif
namespace WireMock.Net.Tests.Owin.Mappers;
public class OwinResponseMapperTests
namespace WireMock.Net.Tests.Owin.Mappers
{
private static readonly Task CompletedTask = Task.FromResult(true);
private readonly OwinResponseMapper _sut;
private readonly Mock<IResponse> _responseMock;
private readonly Mock<Stream> _stream;
private readonly Mock<IHeaderDictionary> _headers;
private readonly Mock<IFileSystemHandler> _fileSystemHandlerMock;
private readonly Mock<IWireMockMiddlewareOptions> _optionsMock;
public OwinResponseMapperTests()
public class OwinResponseMapperTests
{
_stream = new Mock<Stream>();
_stream.SetupAllProperties();
_stream.Setup(s => s.WriteAsync(It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<int>(), It.IsAny<CancellationToken>())).Returns(CompletedTask);
private static readonly Task CompletedTask = Task.FromResult(true);
private readonly OwinResponseMapper _sut;
private readonly Mock<IResponse> _responseMock;
private readonly Mock<Stream> _stream;
private readonly Mock<IHeaderDictionary> _headers;
private readonly Mock<IFileSystemHandler> _fileSystemHandlerMock;
private readonly Mock<IWireMockMiddlewareOptions> _optionsMock;
_fileSystemHandlerMock = new Mock<IFileSystemHandler>();
_fileSystemHandlerMock.SetupAllProperties();
public OwinResponseMapperTests()
{
_stream = new Mock<Stream>();
_stream.SetupAllProperties();
_stream.Setup(s => s.WriteAsync(It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<int>(), It.IsAny<CancellationToken>())).Returns(CompletedTask);
_optionsMock = new Mock<IWireMockMiddlewareOptions>();
_optionsMock.SetupAllProperties();
_optionsMock.SetupGet(o => o.FileSystemHandler).Returns(_fileSystemHandlerMock.Object);
_fileSystemHandlerMock = new Mock<IFileSystemHandler>();
_fileSystemHandlerMock.SetupAllProperties();
_headers = new Mock<IHeaderDictionary>();
_headers.SetupAllProperties();
_optionsMock = new Mock<IWireMockMiddlewareOptions>();
_optionsMock.SetupAllProperties();
_optionsMock.SetupGet(o => o.FileSystemHandler).Returns(_fileSystemHandlerMock.Object);
_headers = new Mock<IHeaderDictionary>();
_headers.SetupAllProperties();
#if NET452
_headers.Setup(h => h.AppendValues(It.IsAny<string>(), It.IsAny<string[]>()));
_headers.Setup(h => h.AppendValues(It.IsAny<string>(), It.IsAny<string[]>()));
#else
_headers.Setup(h => h.Add(It.IsAny<string>(), It.IsAny<StringValues>()));
_headers.Setup(h => h.Add(It.IsAny<string>(), It.IsAny<StringValues>()));
#endif
_responseMock = new Mock<IResponse>();
_responseMock.SetupAllProperties();
_responseMock.SetupGet(r => r.Body).Returns(_stream.Object);
_responseMock.SetupGet(r => r.Headers).Returns(_headers.Object);
_responseMock = new Mock<IResponse>();
_responseMock.SetupAllProperties();
_responseMock.SetupGet(r => r.Body).Returns(_stream.Object);
_responseMock.SetupGet(r => r.Headers).Returns(_headers.Object);
_sut = new OwinResponseMapper(_optionsMock.Object);
}
_sut = new OwinResponseMapper(_optionsMock.Object);
}
[Fact]
public async Task OwinResponseMapper_MapAsync_Null()
{
// Act
await _sut.MapAsync(null, _responseMock.Object).ConfigureAwait(false);
}
[Theory]
[InlineData(300, 300)]
[InlineData(500, 500)]
public async Task OwinResponseMapper_MapAsync_Valid_StatusCode(object code, int expected)
{
// Arrange
var responseMessage = new ResponseMessage
[Fact]
public async Task OwinResponseMapper_MapAsync_Null()
{
StatusCode = code
};
// Act
await _sut.MapAsync(null, _responseMock.Object).ConfigureAwait(false);
}
// Act
await _sut.MapAsync(responseMessage, _responseMock.Object).ConfigureAwait(false);
// Assert
_responseMock.VerifySet(r => r.StatusCode = expected, Times.Once);
}
[Theory]
[InlineData(0, 200)]
[InlineData(-1, 200)]
[InlineData(10000, 200)]
[InlineData(300, 300)]
public async Task OwinResponseMapper_MapAsync_Invalid_StatusCode_When_AllowOnlyDefinedHttpStatusCodeInResponseSet_Is_True(object code, int expected)
{
// Arrange
_optionsMock.SetupGet(o => o.AllowOnlyDefinedHttpStatusCodeInResponse).Returns(true);
var responseMessage = new ResponseMessage
[Theory]
[InlineData(300, 300)]
[InlineData(500, 500)]
public async Task OwinResponseMapper_MapAsync_Valid_StatusCode(object code, int expected)
{
StatusCode = code
};
// Arrange
var responseMessage = new ResponseMessage
{
StatusCode = code
};
// Act
await _sut.MapAsync(responseMessage, _responseMock.Object).ConfigureAwait(false);
// Act
await _sut.MapAsync(responseMessage, _responseMock.Object).ConfigureAwait(false);
// Assert
_responseMock.VerifySet(r => r.StatusCode = expected, Times.Once);
}
// Assert
_responseMock.VerifySet(r => r.StatusCode = expected, Times.Once);
}
[Fact]
public async Task OwinResponseMapper_MapAsync_StatusCode_Is_Null()
{
// Arrange
var responseMessage = new ResponseMessage
[Theory]
[InlineData(0, 200)]
[InlineData(-1, 200)]
[InlineData(10000, 200)]
[InlineData(300, 300)]
public async Task OwinResponseMapper_MapAsync_Invalid_StatusCode_When_AllowOnlyDefinedHttpStatusCodeInResponseSet_Is_True(object code, int expected)
{
StatusCode = null
};
// Arrange
_optionsMock.SetupGet(o => o.AllowOnlyDefinedHttpStatusCodeInResponse).Returns(true);
var responseMessage = new ResponseMessage
{
StatusCode = code
};
// Act
await _sut.MapAsync(responseMessage, _responseMock.Object).ConfigureAwait(false);
// Act
await _sut.MapAsync(responseMessage, _responseMock.Object).ConfigureAwait(false);
// Assert
_responseMock.VerifySet(r => r.StatusCode = It.IsAny<int>(), Times.Never);
}
// Assert
_responseMock.VerifySet(r => r.StatusCode = expected, Times.Once);
}
[Theory]
[InlineData(0, 0)]
[InlineData(-1, -1)]
[InlineData(10000, 10000)]
[InlineData(300, 300)]
public async Task OwinResponseMapper_MapAsync_StatusCode_Is_NotInEnumRange(object code, int expected)
{
// Arrange
var responseMessage = new ResponseMessage
[Fact]
public async Task OwinResponseMapper_MapAsync_StatusCode_Is_Null()
{
StatusCode = code
};
// Arrange
var responseMessage = new ResponseMessage
{
StatusCode = null
};
// Act
await _sut.MapAsync(responseMessage, _responseMock.Object).ConfigureAwait(false);
// Act
await _sut.MapAsync(responseMessage, _responseMock.Object).ConfigureAwait(false);
// Assert
_responseMock.VerifySet(r => r.StatusCode = expected, Times.Once);
}
// Assert
_responseMock.VerifySet(r => r.StatusCode = It.IsAny<int>(), Times.Never);
}
[Fact]
public async Task OwinResponseMapper_MapAsync_NoBody()
{
// Arrange
var responseMessage = new ResponseMessage
[Theory]
[InlineData(0, 0)]
[InlineData(-1, -1)]
[InlineData(10000, 10000)]
[InlineData(300, 300)]
public async Task OwinResponseMapper_MapAsync_StatusCode_Is_NotInEnumRange(object code, int expected)
{
Headers = new Dictionary<string, WireMockList<string>>()
};
// Arrange
var responseMessage = new ResponseMessage
{
StatusCode = code
};
// Act
await _sut.MapAsync(responseMessage, _responseMock.Object).ConfigureAwait(false);
// Act
await _sut.MapAsync(responseMessage, _responseMock.Object).ConfigureAwait(false);
// Assert
_stream.Verify(s => s.WriteAsync(It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<int>(), It.IsAny<CancellationToken>()), Times.Never);
}
// Assert
_responseMock.VerifySet(r => r.StatusCode = expected, Times.Once);
}
[Fact]
public async Task OwinResponseMapper_MapAsync_Body()
{
// Arrange
string body = "abcd";
var responseMessage = new ResponseMessage
[Fact]
public async Task OwinResponseMapper_MapAsync_NoBody()
{
Headers = new Dictionary<string, WireMockList<string>>(),
BodyData = new BodyData { DetectedBodyType = BodyType.String, BodyAsString = body }
};
// Arrange
var responseMessage = new ResponseMessage
{
Headers = new Dictionary<string, WireMockList<string>>()
};
// Act
await _sut.MapAsync(responseMessage, _responseMock.Object).ConfigureAwait(false);
// Act
await _sut.MapAsync(responseMessage, _responseMock.Object).ConfigureAwait(false);
// Assert
_stream.Verify(s => s.WriteAsync(new byte[] { 97, 98, 99, 100 }, 0, 4, It.IsAny<CancellationToken>()), Times.Once);
}
// Assert
_stream.Verify(s => s.WriteAsync(It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<int>(), It.IsAny<CancellationToken>()), Times.Never);
}
[Fact]
public async Task OwinResponseMapper_MapAsync_BodyAsBytes()
{
// Arrange
var bytes = new byte[] { 48, 49 };
var responseMessage = new ResponseMessage
[Fact]
public async Task OwinResponseMapper_MapAsync_Body()
{
Headers = new Dictionary<string, WireMockList<string>>(),
BodyData = new BodyData { DetectedBodyType = BodyType.Bytes, BodyAsBytes = bytes }
};
// Arrange
string body = "abcd";
var responseMessage = new ResponseMessage
{
Headers = new Dictionary<string, WireMockList<string>>(),
BodyData = new BodyData { DetectedBodyType = BodyType.String, BodyAsString = body }
};
// Act
await _sut.MapAsync(responseMessage, _responseMock.Object).ConfigureAwait(false);
// Act
await _sut.MapAsync(responseMessage, _responseMock.Object).ConfigureAwait(false);
// Assert
_stream.Verify(s => s.WriteAsync(bytes, 0, bytes.Length, It.IsAny<CancellationToken>()), Times.Once);
}
// Assert
_stream.Verify(s => s.WriteAsync(new byte[] { 97, 98, 99, 100 }, 0, 4, It.IsAny<CancellationToken>()), Times.Once);
}
[Fact]
public async Task OwinResponseMapper_MapAsync_BodyAsJson()
{
// Arrange
var json = new { t = "x", i = (string?)null };
var responseMessage = new ResponseMessage
[Fact]
public async Task OwinResponseMapper_MapAsync_BodyAsBytes()
{
Headers = new Dictionary<string, WireMockList<string>>(),
BodyData = new BodyData { DetectedBodyType = BodyType.Json, BodyAsJson = json, BodyAsJsonIndented = false }
};
// Arrange
var bytes = new byte[] { 48, 49 };
var responseMessage = new ResponseMessage
{
Headers = new Dictionary<string, WireMockList<string>>(),
BodyData = new BodyData { DetectedBodyType = BodyType.Bytes, BodyAsBytes = bytes }
};
// Act
await _sut.MapAsync(responseMessage, _responseMock.Object).ConfigureAwait(false);
// Act
await _sut.MapAsync(responseMessage, _responseMock.Object).ConfigureAwait(false);
// Assert
_stream.Verify(s => s.WriteAsync(new byte[] { 123, 34, 116, 34, 58, 34, 120, 34, 125 }, 0, 9, It.IsAny<CancellationToken>()), Times.Once);
}
// Assert
_stream.Verify(s => s.WriteAsync(bytes, 0, bytes.Length, It.IsAny<CancellationToken>()), Times.Once);
}
[Fact]
public async Task OwinResponseMapper_MapAsync_SetResponseHeaders()
{
// Arrange
var responseMessage = new ResponseMessage
[Fact]
public async Task OwinResponseMapper_MapAsync_BodyAsJson()
{
Headers = new Dictionary<string, WireMockList<string>> { { "h", new WireMockList<string>("x", "y") } }
};
// Arrange
var json = new { t = "x", i = (string?)null };
var responseMessage = new ResponseMessage
{
Headers = new Dictionary<string, WireMockList<string>>(),
BodyData = new BodyData { DetectedBodyType = BodyType.Json, BodyAsJson = json, BodyAsJsonIndented = false }
};
// Act
await _sut.MapAsync(responseMessage, _responseMock.Object).ConfigureAwait(false);
// Act
await _sut.MapAsync(responseMessage, _responseMock.Object).ConfigureAwait(false);
// Assert
// Assert
_stream.Verify(s => s.WriteAsync(new byte[] { 123, 34, 116, 34, 58, 34, 120, 34, 125 }, 0, 9, It.IsAny<CancellationToken>()), Times.Once);
}
[Fact]
public async Task OwinResponseMapper_MapAsync_SetResponseHeaders()
{
// Arrange
var responseMessage = new ResponseMessage
{
Headers = new Dictionary<string, WireMockList<string>> { { "h", new WireMockList<string>("x", "y") } }
};
// Act
await _sut.MapAsync(responseMessage, _responseMock.Object).ConfigureAwait(false);
// Assert
#if NET452
_headers.Verify(h => h.AppendValues("h", new string[] { "x", "y" }), Times.Once);
_headers.Verify(h => h.AppendValues("h", new string[] { "x", "y" }), Times.Once);
#else
var v = new StringValues();
_headers.Verify(h => h.TryGetValue("h", out v), Times.Once);
var v = new StringValues();
_headers.Verify(h => h.TryGetValue("h", out v), Times.Once);
#endif
}
}
[Fact]
public void OwinResponseMapper_MapAsync_BodyAsFile_ThrowsException()
{
// Arrange
var responseMessage = new ResponseMessage
[Fact]
public void OwinResponseMapper_MapAsync_BodyAsFile_ThrowsException()
{
Headers = new Dictionary<string, WireMockList<string>>(),
BodyData = new BodyData { DetectedBodyType = BodyType.File, BodyAsFile = string.Empty }
};
_fileSystemHandlerMock.Setup(f => f.ReadResponseBodyAsFile(It.IsAny<string>())).Throws<FileNotFoundException>();
// Arrange
var responseMessage = new ResponseMessage
{
Headers = new Dictionary<string, WireMockList<string>>(),
BodyData = new BodyData { DetectedBodyType = BodyType.File, BodyAsFile = string.Empty }
};
_fileSystemHandlerMock.Setup(f => f.ReadResponseBodyAsFile(It.IsAny<string>())).Throws<FileNotFoundException>();
// Act
Func<Task> action = () => _sut.MapAsync(responseMessage, _responseMock.Object);
// Act
Func<Task> action = () => _sut.MapAsync(responseMessage, _responseMock.Object);
// Assert
action.Should().ThrowAsync<FileNotFoundException>();
}
// Assert
action.Should().ThrowAsync<FileNotFoundException>();
}
[Fact]
public async Task OwinResponseMapper_MapAsync_WithFault_EMPTY_RESPONSE()
{
// Arrange
string body = "abc";
var responseMessage = new ResponseMessage
[Fact]
public async Task OwinResponseMapper_MapAsync_WithFault_EMPTY_RESPONSE()
{
Headers = new Dictionary<string, WireMockList<string>>(),
BodyData = new BodyData { DetectedBodyType = BodyType.String, BodyAsString = body },
FaultType = FaultType.EMPTY_RESPONSE
};
// Arrange
string body = "abc";
var responseMessage = new ResponseMessage
{
Headers = new Dictionary<string, WireMockList<string>>(),
BodyData = new BodyData { DetectedBodyType = BodyType.String, BodyAsString = body },
FaultType = FaultType.EMPTY_RESPONSE
};
// Act
await _sut.MapAsync(responseMessage, _responseMock.Object).ConfigureAwait(false);
// Act
await _sut.MapAsync(responseMessage, _responseMock.Object).ConfigureAwait(false);
// Assert
_stream.Verify(s => s.WriteAsync(EmptyArray<byte>.Value, 0, 0, It.IsAny<CancellationToken>()), Times.Once);
}
// Assert
_stream.Verify(s => s.WriteAsync(EmptyArray<byte>.Value, 0, 0, It.IsAny<CancellationToken>()), Times.Once);
}
[Theory]
[InlineData("abcd", BodyType.String)]
[InlineData("", BodyType.String)]
[InlineData(null, BodyType.None)]
public async Task OwinResponseMapper_MapAsync_WithFault_MALFORMED_RESPONSE_CHUNK(string body, BodyType detected)
{
// Arrange
var responseMessage = new ResponseMessage
[Theory]
[InlineData("abcd", BodyType.String)]
[InlineData("", BodyType.String)]
[InlineData(null, BodyType.None)]
public async Task OwinResponseMapper_MapAsync_WithFault_MALFORMED_RESPONSE_CHUNK(string body, BodyType detected)
{
Headers = new Dictionary<string, WireMockList<string>>(),
BodyData = new BodyData { DetectedBodyType = detected, BodyAsString = body },
StatusCode = 100,
FaultType = FaultType.MALFORMED_RESPONSE_CHUNK
};
// Arrange
var responseMessage = new ResponseMessage
{
Headers = new Dictionary<string, WireMockList<string>>(),
BodyData = new BodyData { DetectedBodyType = detected, BodyAsString = body },
StatusCode = 100,
FaultType = FaultType.MALFORMED_RESPONSE_CHUNK
};
// Act
await _sut.MapAsync(responseMessage, _responseMock.Object).ConfigureAwait(false);
// Act
await _sut.MapAsync(responseMessage, _responseMock.Object).ConfigureAwait(false);
// Assert
_responseMock.VerifySet(r => r.StatusCode = 100, Times.Once);
_stream.Verify(s => s.WriteAsync(It.IsAny<byte[]>(), 0, It.Is<int>(count => count >= 0), It.IsAny<CancellationToken>()), Times.Once);
// Assert
_responseMock.VerifySet(r => r.StatusCode = 100, Times.Once);
_stream.Verify(s => s.WriteAsync(It.IsAny<byte[]>(), 0, It.Is<int>(count => count >= 0), It.IsAny<CancellationToken>()), Times.Once);
}
}
}

View File

@@ -92,17 +92,11 @@ public class CustomPathParamMatcher : IStringMatcher
public MatchOperator MatchOperator { get; }
/// <inheritdoc />
public string GetCSharpCodeArguments()
{
return "// TODO: CustomPathParamMatcher";
}
private static string[] GetPathParts(string? path)
{
if (path is null)
{
return [];
return new string[0];
}
var hashMarkIndex = path.IndexOf('#');

View File

@@ -1,8 +1,8 @@
builder
.Given(Request.Create()
.UsingMethod("GET")
.WithPath(new WildcardMatcher(WireMock.Matchers.MatchBehaviour.AcceptOnMatch, "test_path", false, WireMock.Matchers.MatchOperator.Or))
.WithParam("q", new ExactMatcher(WireMock.Matchers.MatchBehaviour.AcceptOnMatch, false, WireMock.Matchers.MatchOperator.And, "42"))
.WithPath("test_path")
.WithParam("q", "42")
.WithClientIP("112.123.100.99")
.WithHeader("h-key", "h-value", true)
.WithCookie("c-key", "c-value", true)

View File

@@ -2,8 +2,8 @@
builder
.Given(Request.Create()
.UsingMethod("GET")
.WithPath(new WildcardMatcher(WireMock.Matchers.MatchBehaviour.AcceptOnMatch, "test_path", false, WireMock.Matchers.MatchOperator.Or))
.WithParam("q", new ExactMatcher(WireMock.Matchers.MatchBehaviour.AcceptOnMatch, false, WireMock.Matchers.MatchOperator.And, "42"))
.WithPath("test_path")
.WithParam("q", "42")
.WithClientIP("112.123.100.99")
.WithHeader("h-key", "h-value", true)
.WithCookie("c-key", "c-value", true)

View File

@@ -1,8 +1,8 @@
server
.Given(Request.Create()
.UsingMethod("GET")
.WithPath(new WildcardMatcher(WireMock.Matchers.MatchBehaviour.AcceptOnMatch, "test_path", false, WireMock.Matchers.MatchOperator.Or))
.WithParam("q", new ExactMatcher(WireMock.Matchers.MatchBehaviour.AcceptOnMatch, false, WireMock.Matchers.MatchOperator.And, "42"))
.WithPath("test_path")
.WithParam("q", "42")
.WithClientIP("112.123.100.99")
.WithHeader("h-key", "h-value", true)
.WithCookie("c-key", "c-value", true)

View File

@@ -2,8 +2,8 @@
server
.Given(Request.Create()
.UsingMethod("GET")
.WithPath(new WildcardMatcher(WireMock.Matchers.MatchBehaviour.AcceptOnMatch, "test_path", false, WireMock.Matchers.MatchOperator.Or))
.WithParam("q", new ExactMatcher(WireMock.Matchers.MatchBehaviour.AcceptOnMatch, false, WireMock.Matchers.MatchOperator.And, "42"))
.WithPath("test_path")
.WithParam("q", "42")
.WithClientIP("112.123.100.99")
.WithHeader("h-key", "h-value", true)
.WithCookie("c-key", "c-value", true)

View File

@@ -8,17 +8,13 @@ using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using FluentAssertions;
using Newtonsoft.Json;
using NFluent;
using WireMock.Admin.Mappings;
using WireMock.Http;
using WireMock.Matchers;
using WireMock.Net.Tests.Facts;
using WireMock.Net.Tests.Serialization;
using WireMock.Net.Xunit;
using WireMock.RequestBuilders;
@@ -199,66 +195,6 @@ public partial class WireMockServerTests
}
#endif
#if NET6_0_OR_GREATER
private static string[] GetIPAddressesByFamily(AddressFamily addressFamily)
{
return NetworkInterface.GetAllNetworkInterfaces()
.Where(ni => ni.OperationalStatus == OperationalStatus.Up)
.SelectMany(ni => ni.GetIPProperties().UnicastAddresses)
.Where(addr => addr.Address.AddressFamily == addressFamily)
.Select(addr => addr.Address.ToString())
.ToArray();
}
[IgnoreOnContinuousIntegrationFact]
public async Task WireMockServer_WithUrl0000_Should_Listen_On_All_IPs_IPv4()
{
// Arrange
var port = PortUtils.FindFreeTcpPort();
var IPv4 = GetIPAddressesByFamily(System.Net.Sockets.AddressFamily.InterNetwork);
var settings = new WireMockServerSettings
{
Urls = ["http://0.0.0.0:" + port],
};
using var server = WireMockServer.Start(settings);
server.Given(Request.Create().WithPath("/*")).RespondWith(Response.Create().WithBody("x"));
foreach (var address in IPv4)
{
// Act
var response = await new HttpClient().GetStringAsync("http://" + address + ":" + server.Ports[0] + "/foo").ConfigureAwait(false);
// Assert
response.Should().Be("x");
}
}
[IgnoreOnContinuousIntegrationFact]
public async Task WireMockServer_WithUrl0000_Should_Listen_On_All_IPs_IPv6()
{
// Arrange
var port = PortUtils.FindFreeTcpPort();
var IPv6 = GetIPAddressesByFamily(System.Net.Sockets.AddressFamily.InterNetworkV6);
var settings = new WireMockServerSettings
{
Urls = ["http://0.0.0.0:" + port],
};
using var server = WireMockServer.Start(settings);
server.Given(Request.Create().WithPath("/*")).RespondWith(Response.Create().WithBody("x"));
foreach (var address in IPv6)
{
// Act
var response = await new HttpClient().GetStringAsync("http://[" + address + "]:" + server.Ports[0] + "/foo").ConfigureAwait(false);
// Assert
response.Should().Be("x");
}
}
#endif
[Fact]
public async Task WireMockServer_Should_respond_a_redirect_without_body()
{
@@ -311,7 +247,7 @@ public partial class WireMockServerTests
// Act
var response = await new HttpClient().GetStringAsync("http://localhost:" + server.Ports[0] + "/foo").ConfigureAwait(false);
// Assert
// Asser.
response.Should().Be("x");
server.Stop();
@@ -337,7 +273,7 @@ public partial class WireMockServerTests
await new HttpClient().GetStringAsync("http://localhost:" + server.Ports[0] + "/foo").ConfigureAwait(false);
watch.Stop();
// Assert
// Asser.
watch.ElapsedMilliseconds.Should().BeGreaterOrEqualTo(0);
server.Stop();
@@ -415,7 +351,7 @@ public partial class WireMockServerTests
//}
[Fact]
public async Task WireMockServer_Should_Exclude_RestrictedResponseHeader()
public async Task WireMockServer_Should_exclude_restrictedResponseHeader()
{
// Assign
string path = $"/foo_{Guid.NewGuid()}";
@@ -435,26 +371,6 @@ public partial class WireMockServerTests
server.Stop();
}
[Fact] // #720
public async Task WireMockServer_Should_AllowResponseHeaderContentLength_For_HEAD()
{
// Assign
const string length = "42";
var path = $"/cl_{Guid.NewGuid()}";
using var server = WireMockServer.Start();
server
.Given(Request.Create().WithPath(path).UsingHead())
.RespondWith(Response.Create().WithHeader(HttpKnownHeaderNames.ContentLength, length));
// Act
var httpRequestMessage = new HttpRequestMessage(HttpMethod.Head, path);
var response = await server.CreateClient().SendAsync(httpRequestMessage).ConfigureAwait(false);
// Assert
response.Content.Headers.GetValues(HttpKnownHeaderNames.ContentLength).Should().Contain(length);
}
#if !NET452 && !NET461
[Theory]
[InlineData("TRACE")]
@@ -725,4 +641,4 @@ public partial class WireMockServerTests
server.Stop();
}
#endif
}
}