WireMock.Net.RestClient.AwesomeAssertions

This commit is contained in:
Stef Heyenrath
2026-02-21 18:39:43 +01:00
parent d8353fcd94
commit ba4eb4b804
20 changed files with 2007 additions and 32 deletions

View File

@@ -156,6 +156,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WireMock.Net.TestWebApplica
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WireMock.Net.TestWebApplication", "test\WireMock.Net.TestWebApplication\WireMock.Net.TestWebApplication.csproj", "{3B05CC76-C3CB-8667-6B65-3129DFB25681}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WireMock.Net.RestClient.AwesomeAssertions", "src\WireMock.Net.RestClient.AwesomeAssertions\WireMock.Net.RestClient.AwesomeAssertions.csproj", "{F4B2B967-98D7-4D93-9A5C-5EF7B84B941A}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -850,6 +852,18 @@ Global
{3B05CC76-C3CB-8667-6B65-3129DFB25681}.Release|x64.Build.0 = Release|Any CPU
{3B05CC76-C3CB-8667-6B65-3129DFB25681}.Release|x86.ActiveCfg = Release|Any CPU
{3B05CC76-C3CB-8667-6B65-3129DFB25681}.Release|x86.Build.0 = Release|Any CPU
{F4B2B967-98D7-4D93-9A5C-5EF7B84B941A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F4B2B967-98D7-4D93-9A5C-5EF7B84B941A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F4B2B967-98D7-4D93-9A5C-5EF7B84B941A}.Debug|x64.ActiveCfg = Debug|Any CPU
{F4B2B967-98D7-4D93-9A5C-5EF7B84B941A}.Debug|x64.Build.0 = Debug|Any CPU
{F4B2B967-98D7-4D93-9A5C-5EF7B84B941A}.Debug|x86.ActiveCfg = Debug|Any CPU
{F4B2B967-98D7-4D93-9A5C-5EF7B84B941A}.Debug|x86.Build.0 = Debug|Any CPU
{F4B2B967-98D7-4D93-9A5C-5EF7B84B941A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F4B2B967-98D7-4D93-9A5C-5EF7B84B941A}.Release|Any CPU.Build.0 = Release|Any CPU
{F4B2B967-98D7-4D93-9A5C-5EF7B84B941A}.Release|x64.ActiveCfg = Release|Any CPU
{F4B2B967-98D7-4D93-9A5C-5EF7B84B941A}.Release|x64.Build.0 = Release|Any CPU
{F4B2B967-98D7-4D93-9A5C-5EF7B84B941A}.Release|x86.ActiveCfg = Release|Any CPU
{F4B2B967-98D7-4D93-9A5C-5EF7B84B941A}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@@ -914,6 +928,7 @@ Global
{2CE8E3A6-59CC-FE9C-9399-AD54E1FA862B} = {985E0ADB-D4B4-473A-AA40-567E279B7946}
{2EA75541-E63A-37B7-DA0A-BEA82ECD7652} = {985E0ADB-D4B4-473A-AA40-567E279B7946}
{3B05CC76-C3CB-8667-6B65-3129DFB25681} = {0BB8B634-407A-4610-A91F-11586990767A}
{F4B2B967-98D7-4D93-9A5C-5EF7B84B941A} = {8F890C6F-9ACC-438D-928A-AD61CDA862F2}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {DC539027-9852-430C-B19F-FD035D018458}

View File

@@ -25,7 +25,7 @@ public partial class WireMockAssertions
public (Func<IReadOnlyList<IRequestMessage>, IReadOnlyList<IRequestMessage>> Filter, Func<IReadOnlyList<IRequestMessage>, bool> Condition) BuildFilterAndCondition(Func<IRequestMessage, bool> predicate)
{
Func<IReadOnlyList<IRequestMessage>, IReadOnlyList<IRequestMessage>> filter = requests => requests.Where(predicate).ToList();
IReadOnlyList<IRequestMessage> filter(IReadOnlyList<IRequestMessage> requests) => requests.Where(predicate).ToList();
return (filter, requests => (CallsCount is null && filter(requests).Any()) || CallsCount == filter(requests).Count);
}

View File

@@ -9,19 +9,13 @@ namespace WireMock.AwesomeAssertions;
/// <summary>
/// Contains a number of methods to assert that the <see cref="IWireMockServer"/> is in the expected state.
/// </summary>
public class WireMockReceivedAssertions : ReferenceTypeAssertions<IWireMockServer, WireMockReceivedAssertions>
/// <remarks>
/// Create a WireMockReceivedAssertions.
/// </remarks>
/// <param name="server">The <see cref="IWireMockServer"/>.</param>
/// <param name="chain">The assertion chain</param>
public class WireMockReceivedAssertions(IWireMockServer server, AssertionChain chain) : ReferenceTypeAssertions<IWireMockServer, WireMockReceivedAssertions>(server, chain)
{
private readonly AssertionChain _chain;
/// <summary>
/// Create a WireMockReceivedAssertions.
/// </summary>
/// <param name="server">The <see cref="IWireMockServer"/>.</param>
/// <param name="chain">The assertion chain</param>
public WireMockReceivedAssertions(IWireMockServer server, AssertionChain chain) : base(server, chain)
{
_chain = chain;
}
/// <summary>
/// Asserts if <see cref="IWireMockServer"/> has received no calls.
@@ -29,7 +23,7 @@ public class WireMockReceivedAssertions : ReferenceTypeAssertions<IWireMockServe
/// <returns><see cref="WireMockAssertions"/></returns>
public WireMockAssertions HaveReceivedNoCalls()
{
return new WireMockAssertions(Subject, 0, _chain);
return new WireMockAssertions(Subject, 0, CurrentAssertionChain);
}
/// <summary>
@@ -38,7 +32,7 @@ public class WireMockReceivedAssertions : ReferenceTypeAssertions<IWireMockServe
/// <returns><see cref="WireMockAssertions"/></returns>
public WireMockAssertions HaveReceivedACall()
{
return new WireMockAssertions(Subject, null, _chain);
return new WireMockAssertions(Subject, null, CurrentAssertionChain);
}
/// <summary>
@@ -48,7 +42,7 @@ public class WireMockReceivedAssertions : ReferenceTypeAssertions<IWireMockServe
/// <returns><see cref="WireMockANumberOfCallsAssertions"/></returns>
public WireMockANumberOfCallsAssertions HaveReceived(int callsCount)
{
return new WireMockANumberOfCallsAssertions(Subject, callsCount, _chain);
return new WireMockANumberOfCallsAssertions(Subject, callsCount, CurrentAssertionChain);
}
/// <inheritdoc />

View File

@@ -7,22 +7,16 @@ using WireMock.Server;
// ReSharper disable once CheckNamespace
namespace WireMock.FluentAssertions;
public partial class WireMockAssertions
public partial class WireMockAssertions(IWireMockServer subject, int? callsCount)
{
public const string Any = "*";
public int? CallsCount { get; }
public IReadOnlyList<IRequestMessage> RequestMessages { get; private set; }
public WireMockAssertions(IWireMockServer subject, int? callsCount)
{
CallsCount = callsCount;
RequestMessages = subject.LogEntries.Select(logEntry => logEntry.RequestMessage).ToList();
}
public int? CallsCount { get; } = callsCount;
public IReadOnlyList<IRequestMessage> RequestMessages { get; private set; } = subject.LogEntries.Select(logEntry => logEntry.RequestMessage).OfType<IRequestMessage>().ToList();
public (Func<IReadOnlyList<IRequestMessage>, IReadOnlyList<IRequestMessage>> Filter, Func<IReadOnlyList<IRequestMessage>, bool> Condition) BuildFilterAndCondition(Func<IRequestMessage, bool> predicate)
{
Func<IReadOnlyList<IRequestMessage>, IReadOnlyList<IRequestMessage>> filter = requests => requests.Where(predicate).ToList();
IReadOnlyList<IRequestMessage> filter(IReadOnlyList<IRequestMessage> requests) => requests.Where(predicate).ToList();
return (filter, requests => (CallsCount is null && filter(requests).Any()) || CallsCount == filter(requests).Count);
}

View File

@@ -0,0 +1,26 @@
// Copyright © WireMock.Net
// ReSharper disable once CheckNamespace
namespace WireMock.Client.AwesomeAssertions;
/// <summary>
/// Provides assertion methods to verify the number of calls made to a WireMock server.
/// This class is used in the context of AwesomeAssertions.
/// </summary>
/// <remarks>
/// Initializes a new instance of the <see cref="WireMockAdminApiANumberOfCallsAssertions"/> class.
/// </remarks>
/// <param name="adminApi">The WireMock Admin API to assert against.</param>
/// <param name="callsCount">The expected number of calls to assert.</param>
/// <param name="chain">The assertion chain</param>
public class WireMockAdminApiANumberOfCallsAssertions(IWireMockAdminApi adminApi, int callsCount, AssertionChain chain)
{
/// <summary>
/// Returns an instance of <see cref="WireMockAdminApiAssertions"/> which can be used to assert the expected number of calls.
/// </summary>
/// <returns>A <see cref="WireMockAdminApiAssertions"/> instance for asserting the number of calls to the server.</returns>
public WireMockAdminApiAssertions Calls()
{
return new WireMockAdminApiAssertions(adminApi, callsCount, chain);
}
}

View File

@@ -0,0 +1,83 @@
// Copyright © WireMock.Net
using WireMock.Extensions;
using WireMock.Matchers;
// ReSharper disable once CheckNamespace
namespace WireMock.Client.AwesomeAssertions;
#pragma warning disable CS1591
public partial class WireMockAdminApiAssertions
{
[CustomAssertion]
public AndWhichConstraint<WireMockAdminApiAssertions, string> AtAbsolutePath(string absolutePath, string because = "", params object[] becauseArgs)
{
_ = AtAbsolutePath(new ExactMatcher(true, absolutePath), because, becauseArgs);
return new AndWhichConstraint<WireMockAdminApiAssertions, string>(this, absolutePath);
}
[CustomAssertion]
public AndWhichConstraint<WireMockAdminApiAssertions, IStringMatcher> AtAbsolutePath(IStringMatcher absolutePathMatcher, string because = "", params object[] becauseArgs)
{
var (filter, condition) = BuildFilterAndCondition(request => absolutePathMatcher.IsPerfectMatch(request.AbsolutePath));
var absolutePath = absolutePathMatcher.GetPatterns().FirstOrDefault().GetPattern();
chain
.BecauseOf(because, becauseArgs)
.Given(() => RequestMessages)
.ForCondition(requests => CallsCount == 0 || requests.Any())
.FailWith(
"Expected {context:wiremockadminapi} to have been called at address matching the absolute path {0}{reason}, but no calls were made.",
absolutePath
)
.Then
.ForCondition(condition)
.FailWith(
"Expected {context:wiremockadminapi} to have been called at address matching the absolute path {0}{reason}, but didn't find it among the calls to {1}.",
_ => absolutePath,
requests => requests.Select(request => request.AbsolutePath)
);
FilterRequestMessages(filter);
return new AndWhichConstraint<WireMockAdminApiAssertions, IStringMatcher>(this, absolutePathMatcher);
}
[CustomAssertion]
public AndWhichConstraint<WireMockAdminApiAssertions, string> AtPath(string path, string because = "", params object[] becauseArgs)
{
_ = AtPath(new ExactMatcher(true, path), because, becauseArgs);
return new AndWhichConstraint<WireMockAdminApiAssertions, string>(this, path);
}
[CustomAssertion]
public AndWhichConstraint<WireMockAdminApiAssertions, IStringMatcher> AtPath(IStringMatcher pathMatcher, string because = "", params object[] becauseArgs)
{
var (filter, condition) = BuildFilterAndCondition(request => pathMatcher.IsPerfectMatch(request.Path));
var path = pathMatcher.GetPatterns().FirstOrDefault().GetPattern();
chain
.BecauseOf(because, becauseArgs)
.Given(() => RequestMessages)
.ForCondition(requests => CallsCount == 0 || requests.Any())
.FailWith(
"Expected {context:wiremockadminapi} to have been called at address matching the path {0}{reason}, but no calls were made.",
path
)
.Then
.ForCondition(condition)
.FailWith(
"Expected {context:wiremockadminapi} to have been called at address matching the path {0}{reason}, but didn't find it among the calls to {1}.",
_ => path,
requests => requests.Select(request => request.Path)
);
FilterRequestMessages(filter);
return new AndWhichConstraint<WireMockAdminApiAssertions, IStringMatcher>(this, pathMatcher);
}
}

View File

@@ -0,0 +1,83 @@
// Copyright © WireMock.Net
using WireMock.Extensions;
using WireMock.Matchers;
// ReSharper disable once CheckNamespace
namespace WireMock.Client.AwesomeAssertions;
#pragma warning disable CS1591
public partial class WireMockAdminApiAssertions
{
[CustomAssertion]
public AndWhichConstraint<WireMockAdminApiAssertions, string> AtAbsoluteUrl(string absoluteUrl, string because = "", params object[] becauseArgs)
{
_ = AtAbsoluteUrl(new ExactMatcher(true, absoluteUrl), because, becauseArgs);
return new AndWhichConstraint<WireMockAdminApiAssertions, string>(this, absoluteUrl);
}
[CustomAssertion]
public AndWhichConstraint<WireMockAdminApiAssertions, IStringMatcher> AtAbsoluteUrl(IStringMatcher absoluteUrlMatcher, string because = "", params object[] becauseArgs)
{
var (filter, condition) = BuildFilterAndCondition(request => absoluteUrlMatcher.IsPerfectMatch(request.AbsoluteUrl));
var absoluteUrl = absoluteUrlMatcher.GetPatterns().FirstOrDefault().GetPattern();
chain
.BecauseOf(because, becauseArgs)
.Given(() => RequestMessages)
.ForCondition(requests => CallsCount == 0 || requests.Any())
.FailWith(
"Expected {context:wiremockadminapi} to have been called at address matching the absolute url {0}{reason}, but no calls were made.",
absoluteUrl
)
.Then
.ForCondition(condition)
.FailWith(
"Expected {context:wiremockadminapi} to have been called at address matching the absolute url {0}{reason}, but didn't find it among the calls to {1}.",
_ => absoluteUrl,
requests => requests.Select(request => request.AbsoluteUrl)
);
FilterRequestMessages(filter);
return new AndWhichConstraint<WireMockAdminApiAssertions, IStringMatcher>(this, absoluteUrlMatcher);
}
[CustomAssertion]
public AndWhichConstraint<WireMockAdminApiAssertions, string> AtUrl(string url, string because = "", params object[] becauseArgs)
{
_ = AtUrl(new ExactMatcher(true, url), because, becauseArgs);
return new AndWhichConstraint<WireMockAdminApiAssertions, string>(this, url);
}
[CustomAssertion]
public AndWhichConstraint<WireMockAdminApiAssertions, IStringMatcher> AtUrl(IStringMatcher urlMatcher, string because = "", params object[] becauseArgs)
{
var (filter, condition) = BuildFilterAndCondition(request => urlMatcher.IsPerfectMatch(request.Url));
var url = urlMatcher.GetPatterns().FirstOrDefault().GetPattern();
chain
.BecauseOf(because, becauseArgs)
.Given(() => RequestMessages)
.ForCondition(requests => CallsCount == 0 || requests.Any())
.FailWith(
"Expected {context:wiremockadminapi} to have been called at address matching the url {0}{reason}, but no calls were made.",
url
)
.Then
.ForCondition(condition)
.FailWith(
"Expected {context:wiremockadminapi} to have been called at address matching the url {0}{reason}, but didn't find it among the calls to {1}.",
_ => url,
requests => requests.Select(request => request.Url)
);
FilterRequestMessages(filter);
return new AndWhichConstraint<WireMockAdminApiAssertions, IStringMatcher>(this, urlMatcher);
}
}

View File

@@ -0,0 +1,33 @@
// Copyright © WireMock.Net
#pragma warning disable CS1591
// ReSharper disable once CheckNamespace
namespace WireMock.Client.AwesomeAssertions;
public partial class WireMockAdminApiAssertions
{
[CustomAssertion]
public AndWhichConstraint<WireMockAdminApiAssertions, string> FromClientIP(string clientIP, string because = "", params object[] becauseArgs)
{
var (filter, condition) = BuildFilterAndCondition(request => string.Equals(request.ClientIP, clientIP, StringComparison.OrdinalIgnoreCase));
chain
.BecauseOf(because, becauseArgs)
.Given(() => RequestMessages)
.ForCondition(requests => CallsCount == 0 || requests.Any())
.FailWith(
"Expected {context:wiremockadminapi} to have been called from client IP {0}{reason}, but no calls were made.",
clientIP
)
.Then
.ForCondition(condition)
.FailWith(
"Expected {context:wiremockadminapi} to have been called from client IP {0}{reason}, but didn't find it among the calls from IP(s) {1}.",
_ => clientIP, requests => requests.Select(request => request.ClientIP)
);
FilterRequestMessages(filter);
return new AndWhichConstraint<WireMockAdminApiAssertions, string>(this, clientIP);
}
}

View File

@@ -0,0 +1,81 @@
// Copyright © WireMock.Net
#pragma warning disable CS1591
using WireMock.Admin.Requests;
using WireMock.Constants;
// ReSharper disable once CheckNamespace
namespace WireMock.Client.AwesomeAssertions;
public partial class WireMockAdminApiAssertions
{
[CustomAssertion]
public AndConstraint<WireMockAdminApiAssertions> UsingConnect(string because = "", params object[] becauseArgs)
=> UsingMethod(HttpRequestMethod.CONNECT, because, becauseArgs);
[CustomAssertion]
public AndConstraint<WireMockAdminApiAssertions> UsingDelete(string because = "", params object[] becauseArgs)
=> UsingMethod(HttpRequestMethod.DELETE, because, becauseArgs);
[CustomAssertion]
public AndConstraint<WireMockAdminApiAssertions> UsingGet(string because = "", params object[] becauseArgs)
=> UsingMethod(HttpRequestMethod.GET, because, becauseArgs);
[CustomAssertion]
public AndConstraint<WireMockAdminApiAssertions> UsingHead(string because = "", params object[] becauseArgs)
=> UsingMethod(HttpRequestMethod.HEAD, because, becauseArgs);
[CustomAssertion]
public AndConstraint<WireMockAdminApiAssertions> UsingOptions(string because = "", params object[] becauseArgs)
=> UsingMethod(HttpRequestMethod.OPTIONS, because, becauseArgs);
[CustomAssertion]
public AndConstraint<WireMockAdminApiAssertions> UsingPost(string because = "", params object[] becauseArgs)
=> UsingMethod(HttpRequestMethod.POST, because, becauseArgs);
[CustomAssertion]
public AndConstraint<WireMockAdminApiAssertions> UsingPatch(string because = "", params object[] becauseArgs)
=> UsingMethod(HttpRequestMethod.PATCH, because, becauseArgs);
[CustomAssertion]
public AndConstraint<WireMockAdminApiAssertions> UsingPut(string because = "", params object[] becauseArgs)
=> UsingMethod(HttpRequestMethod.PUT, because, becauseArgs);
[CustomAssertion]
public AndConstraint<WireMockAdminApiAssertions> UsingTrace(string because = "", params object[] becauseArgs)
=> UsingMethod(HttpRequestMethod.TRACE, because, becauseArgs);
[CustomAssertion]
public AndConstraint<WireMockAdminApiAssertions> UsingAnyMethod(string because = "", params object[] becauseArgs)
=> UsingMethod(Any, because, becauseArgs);
[CustomAssertion]
public AndConstraint<WireMockAdminApiAssertions> UsingMethod(string method, string because = "", params object[] becauseArgs)
{
var any = method == Any;
Func<LogRequestModel, bool> predicate = request => (any && !string.IsNullOrEmpty(request.Method)) ||
string.Equals(request.Method, method, StringComparison.OrdinalIgnoreCase);
var (filter, condition) = BuildFilterAndCondition(predicate);
chain
.BecauseOf(because, becauseArgs)
.Given(() => RequestMessages)
.ForCondition(requests => CallsCount == 0 || requests.Any())
.FailWith(
"Expected {context:wiremockadminapi} to have been called using method {0}{reason}, but no calls were made.",
method
)
.Then
.ForCondition(condition)
.FailWith(
"Expected {context:wiremockadminapi} to have been called using method {0}{reason}, but didn't find it among the methods {1}.",
_ => method,
requests => requests.Select(request => request.Method)
);
FilterRequestMessages(filter);
return new AndConstraint<WireMockAdminApiAssertions>(this);
}
}

View File

@@ -0,0 +1,146 @@
// Copyright © WireMock.Net
#pragma warning disable CS1591
using AnyOfTypes;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using WireMock.Admin.Requests;
using WireMock.Extensions;
using WireMock.Matchers;
using WireMock.Models;
// ReSharper disable once CheckNamespace
namespace WireMock.Client.AwesomeAssertions;
public partial class WireMockAdminApiAssertions
{
private const string MessageFormatNoCalls = "Expected {context:wiremockadminapi} to have been called using body {0}{reason}, but no calls were made.";
private const string MessageFormat = "Expected {context:wiremockadminapi} to have been called using body {0}{reason}, but didn't find it among the body/bodies {1}.";
[CustomAssertion]
public AndConstraint<WireMockAdminApiAssertions> WithBody(string body, string because = "", params object[] becauseArgs)
{
return WithBody(new WildcardMatcher(body), because, becauseArgs);
}
[CustomAssertion]
public AndConstraint<WireMockAdminApiAssertions> WithBody(IStringMatcher matcher, string because = "", params object[] becauseArgs)
{
var (filter, condition) = BuildFilterAndCondition(r => r.Body, matcher);
return ExecuteAssertionWithBodyStringMatcher(matcher, because, becauseArgs, condition, filter, r => r.Body);
}
[CustomAssertion]
public AndConstraint<WireMockAdminApiAssertions> WithBodyAsJson(object body, string because = "", params object[] becauseArgs)
{
return WithBodyAsJson(new JsonMatcher(body), because, becauseArgs);
}
[CustomAssertion]
public AndConstraint<WireMockAdminApiAssertions> WithBodyAsJson(string body, string because = "", params object[] becauseArgs)
{
return WithBodyAsJson(new JsonMatcher(body), because, becauseArgs);
}
[CustomAssertion]
public AndConstraint<WireMockAdminApiAssertions> WithBodyAsJson(IObjectMatcher matcher, string because = "", params object[] becauseArgs)
{
var (filter, condition) = BuildFilterAndCondition(r => r.BodyAsJson, matcher);
return ExecuteAssertionWithBodyAsIObjectMatcher(matcher, because, becauseArgs, condition, filter, r => r.BodyAsJson);
}
[CustomAssertion]
public AndConstraint<WireMockAdminApiAssertions> WithBodyAsBytes(byte[] body, string because = "", params object[] becauseArgs)
{
return WithBodyAsBytes(new ExactObjectMatcher(body), because, becauseArgs);
}
[CustomAssertion]
public AndConstraint<WireMockAdminApiAssertions> WithBodyAsBytes(ExactObjectMatcher matcher, string because = "", params object[] becauseArgs)
{
var (filter, condition) = BuildFilterAndCondition(r => r.BodyAsBytes, matcher);
return ExecuteAssertionWithBodyAsIObjectMatcher(matcher, because, becauseArgs, condition, filter, r => r.BodyAsBytes);
}
private AndConstraint<WireMockAdminApiAssertions> ExecuteAssertionWithBodyStringMatcher(
IStringMatcher matcher,
string because,
object[] becauseArgs,
Func<IReadOnlyList<LogRequestModel>, bool> condition,
Func<IReadOnlyList<LogRequestModel>, IReadOnlyList<LogRequestModel>> filter,
Func<LogRequestModel, object?> expression
)
{
chain
.BecauseOf(because, becauseArgs)
.Given(() => RequestMessages)
.ForCondition(requests => CallsCount == 0 || requests.Any())
.FailWith(
MessageFormatNoCalls,
FormatBody(matcher.GetPatterns())
)
.Then
.ForCondition(condition)
.FailWith(
MessageFormat,
_ => FormatBody(matcher.GetPatterns()),
requests => FormatBodies(requests.Select(expression))
);
FilterRequestMessages(filter);
return new AndConstraint<WireMockAdminApiAssertions>(this);
}
private AndConstraint<WireMockAdminApiAssertions> ExecuteAssertionWithBodyAsIObjectMatcher(
IObjectMatcher matcher,
string because,
object[] becauseArgs,
Func<IReadOnlyList<LogRequestModel>, bool> condition,
Func<IReadOnlyList<LogRequestModel>, IReadOnlyList<LogRequestModel>> filter,
Func<LogRequestModel, object?> expression
)
{
chain
.BecauseOf(because, becauseArgs)
.Given(() => RequestMessages)
.ForCondition(requests => CallsCount == 0 || requests.Any())
.FailWith(
MessageFormatNoCalls,
FormatBody(matcher.Value)
)
.Then
.ForCondition(condition)
.FailWith(
MessageFormat,
_ => FormatBody(matcher.Value),
requests => FormatBodies(requests.Select(expression))
);
FilterRequestMessages(filter);
return new AndConstraint<WireMockAdminApiAssertions>(this);
}
private static string? FormatBody(object? body)
{
return body switch
{
null => null,
string str => str,
AnyOf<string, StringPattern>[] stringPatterns => FormatBodies(stringPatterns.Select(p => p.GetPattern())),
byte[] bytes => $"byte[{bytes.Length}] {{...}}",
JToken jToken => jToken.ToString(Formatting.None),
_ => JToken.FromObject(body).ToString(Formatting.None)
};
}
private static string? FormatBodies(IEnumerable<object?> bodies)
{
var valueAsArray = bodies as object[] ?? bodies.ToArray();
return valueAsArray.Length == 1 ? FormatBody(valueAsArray[0]) : $"[ {string.Join(", ", valueAsArray.Select(FormatBody))} ]";
}
}

View File

@@ -0,0 +1,157 @@
// Copyright © WireMock.Net
#pragma warning disable CS1591
// ReSharper disable once CheckNamespace
namespace WireMock.Client.AwesomeAssertions;
public partial class WireMockAdminApiAssertions
{
[CustomAssertion]
public AndWhichConstraint<WireMockAdminApiAssertions, string> WitHeaderKey(string expectedKey, string because = "", params object[] becauseArgs)
{
var (filter, condition) = BuildFilterAndCondition(request =>
{
return request.Headers?.Any(h => h.Key == expectedKey) == true;
});
chain
.BecauseOf(because, becauseArgs)
.Given(() => RequestMessages)
.ForCondition(requests => CallsCount == 0 || requests.Any())
.FailWith(
"Expected {context:wiremockadminapi} to have been called with Header {0}{reason}.",
expectedKey
)
.Then
.ForCondition(condition)
.FailWith(
"Expected {context:wiremockadminapi} to have been called with Header {0}{reason}, but didn't find it among the calls with Header(s) {1}.",
_ => expectedKey,
requests => requests.Select(request => request.Headers)
);
FilterRequestMessages(filter);
return new AndWhichConstraint<WireMockAdminApiAssertions, string>(this, expectedKey);
}
[CustomAssertion]
public AndConstraint<WireMockAdminApiAssertions> WithHeader(string expectedKey, string value, string because = "", params object[] becauseArgs)
=> WithHeader(expectedKey, new[] { value }, because, becauseArgs);
[CustomAssertion]
public AndConstraint<WireMockAdminApiAssertions> WithHeader(string expectedKey, string[] expectedValues, string because = "", params object[] becauseArgs)
{
var (filter, condition) = BuildFilterAndCondition(request =>
{
var headers = request.Headers?.ToArray() ?? [];
var matchingHeaderValues = headers.Where(h => h.Key == expectedKey).SelectMany(h => h.Value.ToArray()).ToArray();
if (expectedValues.Length == 1 && matchingHeaderValues.Length == 1)
{
return matchingHeaderValues[0] == expectedValues[0];
}
var trimmedHeaderValues = string.Join(",", matchingHeaderValues.Select(x => x)).Split(',').Select(x => x.Trim()).ToArray();
return expectedValues.Any(trimmedHeaderValues.Contains);
});
chain
.BecauseOf(because, becauseArgs)
.Given(() => RequestMessages)
.ForCondition(requests => CallsCount == 0 || requests.Any())
.FailWith(
"Expected {context:wiremockadminapi} to have been called with Header {0} and Values {1}{reason}.",
expectedKey,
expectedValues
)
.Then
.ForCondition(condition)
.FailWith(
"Expected {context:wiremockadminapi} to have been called with Header {0} and Values {1}{reason}, but didn't find it among the calls with Header(s) {2}.",
_ => expectedKey,
_ => expectedValues,
requests => requests.Select(request => request.Headers)
);
FilterRequestMessages(filter);
return new AndConstraint<WireMockAdminApiAssertions>(this);
}
[CustomAssertion]
public AndConstraint<WireMockAdminApiAssertions> WithoutHeaderKey(string unexpectedKey, string because = "", params object[] becauseArgs)
{
var (filter, condition) = BuildFilterAndCondition(request =>
{
return request.Headers?.Any(h => h.Key == unexpectedKey) != true;
});
chain
.BecauseOf(because, becauseArgs)
.Given(() => RequestMessages)
.ForCondition(requests => CallsCount == 0 || requests.Any())
.FailWith(
"Expected {context:wiremockadminapi} not to have been called with Header {0}{reason}.",
unexpectedKey
)
.Then
.ForCondition(condition)
.FailWith(
"Expected {context:wiremockadminapi} not to have been called with Header {0}{reason}, but found it among the calls with Header(s) {1}.",
_ => unexpectedKey,
requests => requests.Select(request => request.Headers)
);
FilterRequestMessages(filter);
return new AndConstraint<WireMockAdminApiAssertions>(this);
}
[CustomAssertion]
public AndConstraint<WireMockAdminApiAssertions> WithoutHeader(string unexpectedKey, string value, string because = "", params object[] becauseArgs)
=> WithoutHeader(unexpectedKey, new[] { value }, because, becauseArgs);
[CustomAssertion]
public AndConstraint<WireMockAdminApiAssertions> WithoutHeader(string unexpectedKey, string[] expectedValues, string because = "", params object[] becauseArgs)
{
var (filter, condition) = BuildFilterAndCondition(request =>
{
var headers = request.Headers?.ToArray() ?? [];
var matchingHeaderValues = headers.Where(h => h.Key == unexpectedKey).SelectMany(h => h.Value.ToArray()).ToArray();
if (expectedValues.Length == 1 && matchingHeaderValues.Length == 1)
{
return matchingHeaderValues[0] != expectedValues[0];
}
var trimmedHeaderValues = string.Join(",", matchingHeaderValues.Select(x => x)).Split(',').Select(x => x.Trim()).ToArray();
return !expectedValues.Any(trimmedHeaderValues.Contains);
});
chain
.BecauseOf(because, becauseArgs)
.Given(() => RequestMessages)
.ForCondition(requests => CallsCount == 0 || requests.Any())
.FailWith(
"Expected {context:wiremockadminapi} not to have been called with Header {0} and Values {1}{reason}.",
unexpectedKey,
expectedValues
)
.Then
.ForCondition(condition)
.FailWith(
"Expected {context:wiremockadminapi} not to have been called with Header {0} and Values {1}{reason}, but found it among the calls with Header(s) {2}.",
_ => unexpectedKey,
_ => expectedValues,
requests => requests.Select(request => request.Headers)
);
FilterRequestMessages(filter);
return new AndConstraint<WireMockAdminApiAssertions>(this);
}
}

View File

@@ -0,0 +1,34 @@
// Copyright © WireMock.Net
#pragma warning disable CS1591
// ReSharper disable once CheckNamespace
namespace WireMock.Client.AwesomeAssertions;
public partial class WireMockAdminApiAssertions
{
[CustomAssertion]
public AndWhichConstraint<WireMockAdminApiAssertions, string> WithProxyUrl(string proxyUrl, string because = "", params object[] becauseArgs)
{
var (filter, condition) = BuildFilterAndCondition(request => string.Equals(request.ProxyUrl, proxyUrl, StringComparison.OrdinalIgnoreCase));
chain
.BecauseOf(because, becauseArgs)
.Given(() => RequestMessages)
.ForCondition(requests => CallsCount == 0 || requests.Any())
.FailWith(
"Expected {context:wiremockadminapi} to have been called with proxy url {0}{reason}, but no calls were made.",
proxyUrl
)
.Then
.ForCondition(condition)
.FailWith(
"Expected {context:wiremockadminapi} to have been called with proxy url {0}{reason}, but didn't find it among the calls with {1}.",
_ => proxyUrl,
requests => requests.Select(request => request.ProxyUrl)
);
FilterRequestMessages(filter);
return new AndWhichConstraint<WireMockAdminApiAssertions, string>(this, proxyUrl);
}
}

View File

@@ -0,0 +1,42 @@
// Copyright © WireMock.Net
#pragma warning disable CS1591
using WireMock.Admin.Requests;
using WireMock.Matchers;
// ReSharper disable once CheckNamespace
namespace WireMock.Client.AwesomeAssertions;
public partial class WireMockAdminApiAssertions(IWireMockAdminApi subject, int? callsCount, AssertionChain chain)
{
public const string Any = "*";
public int? CallsCount { get; } = callsCount;
public IReadOnlyList<LogRequestModel> RequestMessages { get; private set; } = subject.GetRequestsAsync().GetAwaiter().GetResult()
.Select(logEntry => logEntry.Request)
.OfType<LogRequestModel>()
.ToList();
public (Func<IReadOnlyList<LogRequestModel>, IReadOnlyList<LogRequestModel>> Filter, Func<IReadOnlyList<LogRequestModel>, bool> Condition) BuildFilterAndCondition(Func<LogRequestModel, bool> predicate)
{
IReadOnlyList<LogRequestModel> filter(IReadOnlyList<LogRequestModel> requests) => requests.Where(predicate).ToList();
return (filter, requests => (CallsCount is null && filter(requests).Any()) || CallsCount == filter(requests).Count);
}
public (Func<IReadOnlyList<LogRequestModel>, IReadOnlyList<LogRequestModel>> Filter, Func<IReadOnlyList<LogRequestModel>, bool> Condition) BuildFilterAndCondition(Func<LogRequestModel, string?> expression, IStringMatcher matcher)
{
return BuildFilterAndCondition(r => matcher.IsMatch(expression(r)).IsPerfect());
}
public (Func<IReadOnlyList<LogRequestModel>, IReadOnlyList<LogRequestModel>> Filter, Func<IReadOnlyList<LogRequestModel>, bool> Condition) BuildFilterAndCondition(Func<LogRequestModel, object?> expression, IObjectMatcher matcher)
{
return BuildFilterAndCondition(r => matcher.IsMatch(expression(r)).IsPerfect());
}
public void FilterRequestMessages(Func<IReadOnlyList<LogRequestModel>, IReadOnlyList<LogRequestModel>> filter)
{
RequestMessages = filter(RequestMessages).ToList();
}
}

View File

@@ -0,0 +1,50 @@
// Copyright © WireMock.Net
using AwesomeAssertions.Primitives;
// ReSharper disable once CheckNamespace
namespace WireMock.Client.AwesomeAssertions;
/// <summary>
/// Contains a number of methods to assert that the <see cref="IWireMockAdminApi"/> is in the expected state.
/// </summary>
/// <remarks>
/// Create a WireMockReceivedAssertions.
/// </remarks>
/// <param name="adminApi">The <see cref="IWireMockAdminApi"/>.</param>
/// <param name="chain">The assertion chain</param>
public class WireMockAdminApiReceivedAssertions(IWireMockAdminApi adminApi, AssertionChain chain) :
ReferenceTypeAssertions<IWireMockAdminApi, WireMockAdminApiReceivedAssertions>(adminApi, chain)
{
/// <summary>
/// Asserts if <see cref="IWireMockAdminApi"/> has received no calls.
/// </summary>
/// <returns><see cref="WireMockAdminApiAssertions"/></returns>
public WireMockAdminApiAssertions HaveReceivedNoCalls()
{
return new WireMockAdminApiAssertions(Subject, 0, CurrentAssertionChain);
}
/// <summary>
/// Asserts if <see cref="IWireMockAdminApi"/> has received a call.
/// </summary>
/// <returns><see cref="WireMockAdminApiAssertions"/></returns>
public WireMockAdminApiAssertions HaveReceivedACall()
{
return new WireMockAdminApiAssertions(Subject, null, CurrentAssertionChain);
}
/// <summary>
/// Asserts if <see cref="IWireMockAdminApi"/> has received n-calls.
/// </summary>
/// <param name="callsCount"></param>
/// <returns><see cref="WireMockAdminApiANumberOfCallsAssertions"/></returns>
public WireMockAdminApiANumberOfCallsAssertions HaveReceived(int callsCount)
{
return new WireMockAdminApiANumberOfCallsAssertions(Subject, callsCount, CurrentAssertionChain);
}
/// <inheritdoc />
protected override string Identifier => "wiremockadminapi";
}

View File

@@ -0,0 +1,20 @@
// Copyright © WireMock.Net
// ReSharper disable once CheckNamespace
namespace WireMock.Client.AwesomeAssertions;
/// <summary>
/// Contains extension methods for custom assertions in unit tests.
/// </summary>
public static class WireMockAdminApiExtensions
{
/// <summary>
/// Returns a <see cref="WireMockAdminApiReceivedAssertions"/> object that can be used to assert the current <see cref="IWireMockAdminApi"/>.
/// </summary>
/// <param name="instance">The WireMock Admin API client.</param>
/// <returns><see cref="WireMockAdminApiReceivedAssertions"/></returns>
public static WireMockAdminApiReceivedAssertions Should(this IWireMockAdminApi instance)
{
return new WireMockAdminApiReceivedAssertions(instance, AssertionChain.GetOrCreate());
}
}

View File

@@ -0,0 +1,4 @@
// Copyright © WireMock.Net
global using AwesomeAssertions;
global using AwesomeAssertions.Execution;

View File

@@ -0,0 +1,44 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<Version>0.0.1-preview-01</Version>
<Description>AwesomeAssertions extensions for WireMock.Net RestClient</Description>
<AssemblyTitle>WireMock.Net.RestClient.AwesomeAssertions</AssemblyTitle>
<Authors>Stef Heyenrath</Authors>
<TargetFramework>netstandard2.0</TargetFramework>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<AssemblyName>WireMock.Net.RestClient.AwesomeAssertions</AssemblyName>
<PackageId>WireMock.Net.RestClient.AwesomeAssertions</PackageId>
<PackageTags>wiremock;AwesomeAssertions;UnitTest;Assert;Assertions;restclient</PackageTags>
<RootNamespace>WireMock.Client.AwesomeAssertions</RootNamespace>
<ProjectGuid>{F4B2B967-7878-4D93-9A5C-5EF7B84B941A}</ProjectGuid>
<PublishRepositoryUrl>true</PublishRepositoryUrl>
<AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder>
<EmbedUntrackedSources>true</EmbedUntrackedSources>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>
<SignAssembly>true</SignAssembly>
<AssemblyOriginatorKeyFile>../WireMock.Net/WireMock.Net.snk</AssemblyOriginatorKeyFile>
<!--<DelaySign>true</DelaySign>-->
<PublicSign Condition=" '$(OS)' != 'Windows_NT' ">true</PublicSign>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)' == 'Debug - Sonar'">
<CodeAnalysisRuleSet>../WireMock.Net/WireMock.Net.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AwesomeAssertions" Version="9.4.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\WireMock.Net.Minimal\WireMock.Net.Minimal.csproj" />
<ProjectReference Include="..\WireMock.Net.RestClient\WireMock.Net.RestClient.csproj" />
</ItemGroup>
</Project>

File diff suppressed because it is too large Load Diff

View File

@@ -52,7 +52,7 @@ public class WireMockAssertionsTests : IDisposable
}
[Fact]
public async Task HaveReceived1Calls_AtAbsoluteUrl_WhenACallWasMadeToAbsoluteUrl_Should_BeOK()
public async Task HaveReceived1Call_AtAbsoluteUrl_WhenACallWasMadeToAbsoluteUrl_Should_BeOK()
{
await _httpClient.GetAsync("anyurl", _ct);
@@ -62,7 +62,7 @@ public class WireMockAssertionsTests : IDisposable
}
[Fact]
public async Task HaveReceived1Calls_AtAbsoluteUrl2_WhenACallWasMadeToAbsoluteUrl_Should_BeOK()
public async Task HaveReceived1Call_AtAbsoluteUrl2_WhenACallWasMadeToAbsoluteUrl_Should_BeOK()
{
await _httpClient.GetAsync("anyurl", _ct);
@@ -72,7 +72,7 @@ public class WireMockAssertionsTests : IDisposable
}
[Fact]
public async Task HaveReceived1Calls_AtAbsoluteUrlUsingPost_WhenAPostCallWasMadeToAbsoluteUrl_Should_BeOK()
public async Task HaveReceived1Call_AtAbsoluteUrlUsingPost_WhenAPostCallWasMadeToAbsoluteUrl_Should_BeOK()
{
await _httpClient.PostAsync("anyurl", new StringContent(""), _ct);
@@ -162,7 +162,7 @@ public class WireMockAssertionsTests : IDisposable
}
[Fact]
public async Task HaveReceived1Calls_AtAbsolutePath_WhenACallWasMadeToAbsolutePath_Should_BeOK()
public async Task HaveReceived1Call_AtAbsolutePath_WhenACallWasMadeToAbsolutePath_Should_BeOK()
{
await _httpClient.GetAsync("anypath", _ct);
@@ -172,7 +172,7 @@ public class WireMockAssertionsTests : IDisposable
}
[Fact]
public async Task HaveReceived1Calls_AtAbsolutePathUsingPost_WhenAPostCallWasMadeToAbsolutePath_Should_BeOK()
public async Task HaveReceived1Call_AtAbsolutePathUsingPost_WhenAPostCallWasMadeToAbsolutePath_Should_BeOK()
{
await _httpClient.PostAsync("anypath", new StringContent(""), _ct);
@@ -625,7 +625,7 @@ public class WireMockAssertionsTests : IDisposable
}
[Fact]
public async Task HaveReceived1Calls_AtAbsoluteUrlUsingPost_ShouldChain()
public async Task HaveReceived1Call_AtAbsoluteUrlUsingPost_ShouldChain()
{
// Arrange
var server = WireMockServer.Start();

View File

@@ -50,6 +50,7 @@
<ItemGroup>
<ProjectReference Include="..\..\src\WireMock.Net.AwesomeAssertions\WireMock.Net.AwesomeAssertions.csproj" />
<ProjectReference Include="..\..\src\WireMock.Net.Matchers.CSharpCode\WireMock.Net.Matchers.CSharpCode.csproj" />
<ProjectReference Include="..\..\src\WireMock.Net.RestClient.AwesomeAssertions\WireMock.Net.RestClient.AwesomeAssertions.csproj" />
<ProjectReference Include="..\..\src\WireMock.Net.RestClient\WireMock.Net.RestClient.csproj" />
<ProjectReference Include="..\..\src\WireMock.Net.xUnit.v3\WireMock.Net.xUnit.v3.csproj" />
<ProjectReference Include="..\..\src\WireMock.Net\WireMock.Net.csproj" />