mirror of
https://github.com/wiremock/WireMock.Net.git
synced 2026-03-28 20:32:13 +01:00
Fix FluentAssertions (actual body is not displayed in error message) (#1085)
* Fix FluentAssertions (actual body is not displayed in error message) * . * . * raw
This commit is contained in:
@@ -1,7 +1,12 @@
|
|||||||
#pragma warning disable CS1591
|
#pragma warning disable CS1591
|
||||||
using System;
|
using System;
|
||||||
using System.Collections.Generic;
|
using System.Collections.Generic;
|
||||||
|
using AnyOfTypes;
|
||||||
|
using Newtonsoft.Json;
|
||||||
|
using Newtonsoft.Json.Linq;
|
||||||
|
using WireMock.Extensions;
|
||||||
using WireMock.Matchers;
|
using WireMock.Matchers;
|
||||||
|
using WireMock.Models;
|
||||||
|
|
||||||
// ReSharper disable once CheckNamespace
|
// ReSharper disable once CheckNamespace
|
||||||
namespace WireMock.FluentAssertions;
|
namespace WireMock.FluentAssertions;
|
||||||
@@ -9,7 +14,7 @@ namespace WireMock.FluentAssertions;
|
|||||||
public partial class WireMockAssertions
|
public partial class WireMockAssertions
|
||||||
{
|
{
|
||||||
private const string MessageFormatNoCalls = "Expected {context:wiremockserver} to have been called using body {0}{reason}, but no calls were made.";
|
private const string MessageFormatNoCalls = "Expected {context:wiremockserver} to have been called using body {0}{reason}, but no calls were made.";
|
||||||
private const string MessageFormat = "Expected {context:wiremockserver} to have been called using body {0}{reason}, but didn't find it among the body {1}.";
|
private const string MessageFormat = "Expected {context:wiremockserver} to have been called using body {0}{reason}, but didn't find it among the body/bodies {1}.";
|
||||||
|
|
||||||
[CustomAssertion]
|
[CustomAssertion]
|
||||||
public AndConstraint<WireMockAssertions> WithBody(string body, string because = "", params object[] becauseArgs)
|
public AndConstraint<WireMockAssertions> WithBody(string body, string because = "", params object[] becauseArgs)
|
||||||
@@ -56,7 +61,7 @@ public partial class WireMockAssertions
|
|||||||
{
|
{
|
||||||
var (filter, condition) = BuildFilterAndCondition(r => r.BodyAsBytes, matcher);
|
var (filter, condition) = BuildFilterAndCondition(r => r.BodyAsBytes, matcher);
|
||||||
|
|
||||||
return ExecuteAssertionWithBodyAsBytesExactObjectMatcher(matcher, because, becauseArgs, condition, filter, r => r.BodyAsBytes);
|
return ExecuteAssertionWithBodyAsIObjectMatcher(matcher, because, becauseArgs, condition, filter, r => r.BodyAsBytes);
|
||||||
}
|
}
|
||||||
|
|
||||||
private AndConstraint<WireMockAssertions> ExecuteAssertionWithBodyStringMatcher(
|
private AndConstraint<WireMockAssertions> ExecuteAssertionWithBodyStringMatcher(
|
||||||
@@ -74,14 +79,14 @@ public partial class WireMockAssertions
|
|||||||
.ForCondition(requests => CallsCount == 0 || requests.Any())
|
.ForCondition(requests => CallsCount == 0 || requests.Any())
|
||||||
.FailWith(
|
.FailWith(
|
||||||
MessageFormatNoCalls,
|
MessageFormatNoCalls,
|
||||||
matcher.GetPatterns()
|
FormatBody(matcher.GetPatterns())
|
||||||
)
|
)
|
||||||
.Then
|
.Then
|
||||||
.ForCondition(condition)
|
.ForCondition(condition)
|
||||||
.FailWith(
|
.FailWith(
|
||||||
MessageFormat,
|
MessageFormat,
|
||||||
_ => matcher.GetPatterns(),
|
_ => FormatBody(matcher.GetPatterns()),
|
||||||
requests => requests.Select(expression)
|
requests => FormatBodies(requests.Select(expression))
|
||||||
);
|
);
|
||||||
|
|
||||||
FilterRequestMessages(filter);
|
FilterRequestMessages(filter);
|
||||||
@@ -104,14 +109,14 @@ public partial class WireMockAssertions
|
|||||||
.ForCondition(requests => CallsCount == 0 || requests.Any())
|
.ForCondition(requests => CallsCount == 0 || requests.Any())
|
||||||
.FailWith(
|
.FailWith(
|
||||||
MessageFormatNoCalls,
|
MessageFormatNoCalls,
|
||||||
matcher.Value
|
FormatBody(matcher.Value)
|
||||||
)
|
)
|
||||||
.Then
|
.Then
|
||||||
.ForCondition(condition)
|
.ForCondition(condition)
|
||||||
.FailWith(
|
.FailWith(
|
||||||
MessageFormat,
|
MessageFormat,
|
||||||
_ => matcher.Value,
|
_ => FormatBody(matcher.Value),
|
||||||
requests => requests.Select(expression)
|
requests => FormatBodies(requests.Select(expression))
|
||||||
);
|
);
|
||||||
|
|
||||||
FilterRequestMessages(filter);
|
FilterRequestMessages(filter);
|
||||||
@@ -119,33 +124,22 @@ public partial class WireMockAssertions
|
|||||||
return new AndConstraint<WireMockAssertions>(this);
|
return new AndConstraint<WireMockAssertions>(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
private AndConstraint<WireMockAssertions> ExecuteAssertionWithBodyAsBytesExactObjectMatcher(
|
private static string? FormatBody(object? body)
|
||||||
ExactObjectMatcher matcher,
|
|
||||||
string because,
|
|
||||||
object[] becauseArgs,
|
|
||||||
Func<IReadOnlyList<IRequestMessage>, bool> condition,
|
|
||||||
Func<IReadOnlyList<IRequestMessage>, IReadOnlyList<IRequestMessage>> filter,
|
|
||||||
Func<IRequestMessage, object?> expression
|
|
||||||
)
|
|
||||||
{
|
{
|
||||||
Execute.Assertion
|
return body switch
|
||||||
.BecauseOf(because, becauseArgs)
|
{
|
||||||
.Given(() => RequestMessages)
|
null => null,
|
||||||
.ForCondition(requests => CallsCount == 0 || requests.Any())
|
string str => str,
|
||||||
.FailWith(
|
AnyOf<string, StringPattern>[] stringPatterns => FormatBodies(stringPatterns.Select(p => p.GetPattern())),
|
||||||
MessageFormatNoCalls,
|
byte[] bytes => $"byte[{bytes.Length}] {{...}}",
|
||||||
matcher.Value
|
JToken jToken => jToken.ToString(Formatting.None),
|
||||||
)
|
_ => JToken.FromObject(body).ToString(Formatting.None)
|
||||||
.Then
|
};
|
||||||
.ForCondition(condition)
|
}
|
||||||
.FailWith(
|
|
||||||
MessageFormat,
|
|
||||||
_ => matcher.Value,
|
|
||||||
requests => requests.Select(expression)
|
|
||||||
);
|
|
||||||
|
|
||||||
FilterRequestMessages(filter);
|
private static string? FormatBodies(IEnumerable<object?> bodies)
|
||||||
|
{
|
||||||
return new AndConstraint<WireMockAssertions>(this);
|
var valueAsArray = bodies as object[] ?? bodies.ToArray();
|
||||||
|
return valueAsArray.Length == 1 ? FormatBody(valueAsArray.First()) : $"[ {string.Join(", ", valueAsArray.Select(FormatBody))} ]";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -5,18 +5,36 @@ using WireMock.Models;
|
|||||||
|
|
||||||
namespace WireMock.Extensions;
|
namespace WireMock.Extensions;
|
||||||
|
|
||||||
internal static class AnyOfExtensions
|
/// <summary>
|
||||||
|
/// Some extensions for AnyOf.
|
||||||
|
/// </summary>
|
||||||
|
public static class AnyOfExtensions
|
||||||
{
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Gets the pattern.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="value">AnyOf type</param>
|
||||||
|
/// <returns>string value</returns>
|
||||||
public static string GetPattern(this AnyOf<string, StringPattern> value)
|
public static string GetPattern(this AnyOf<string, StringPattern> value)
|
||||||
{
|
{
|
||||||
return value.IsFirst ? value.First : value.Second.Pattern;
|
return value.IsFirst ? value.First : value.Second.Pattern;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Converts a string-patterns to AnyOf patterns.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="patterns">The string patterns</param>
|
||||||
|
/// <returns>The AnyOf patterns</returns>
|
||||||
public static AnyOf<string, StringPattern>[] ToAnyOfPatterns(this IEnumerable<string> patterns)
|
public static AnyOf<string, StringPattern>[] ToAnyOfPatterns(this IEnumerable<string> patterns)
|
||||||
{
|
{
|
||||||
return patterns.Select(p => p.ToAnyOfPattern()).ToArray();
|
return patterns.Select(p => p.ToAnyOfPattern()).ToArray();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Converts a string-pattern to AnyOf pattern.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="pattern">The string pattern</param>
|
||||||
|
/// <returns>The AnyOf pattern</returns>
|
||||||
public static AnyOf<string, StringPattern> ToAnyOfPattern(this string pattern)
|
public static AnyOf<string, StringPattern> ToAnyOfPattern(this string pattern)
|
||||||
{
|
{
|
||||||
return new AnyOf<string, StringPattern>(pattern);
|
return new AnyOf<string, StringPattern>(pattern);
|
||||||
|
|||||||
@@ -702,7 +702,11 @@ public class WireMockAssertionsTests : IDisposable
|
|||||||
// Act
|
// Act
|
||||||
var httpClient = new HttpClient();
|
var httpClient = new HttpClient();
|
||||||
|
|
||||||
await httpClient.PostAsync($"{server.Url}/a", new StringContent(@"{ ""x"": ""y"" }"));
|
var requestBody = new
|
||||||
|
{
|
||||||
|
x = "y"
|
||||||
|
};
|
||||||
|
await httpClient.PostAsJsonAsync($"{server.Url}/a", requestBody);
|
||||||
|
|
||||||
// Assert
|
// Assert
|
||||||
server
|
server
|
||||||
@@ -740,6 +744,103 @@ public class WireMockAssertionsTests : IDisposable
|
|||||||
server.Stop();
|
server.Stop();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task WithBodyAsJson_When_NoMatch_ShouldHaveCorrectErrorMessage()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var server = WireMockServer.Start();
|
||||||
|
|
||||||
|
server
|
||||||
|
.Given(Request.Create().WithPath("/a").UsingPost())
|
||||||
|
.RespondWith(Response.Create().WithBody("A response"));
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var httpClient = new HttpClient();
|
||||||
|
|
||||||
|
var requestBody = new
|
||||||
|
{
|
||||||
|
x = "123"
|
||||||
|
};
|
||||||
|
await httpClient.PostAsJsonAsync($"{server.Url}/a", requestBody);
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
Action act = () => server
|
||||||
|
.Should()
|
||||||
|
.HaveReceived(1)
|
||||||
|
.Calls()
|
||||||
|
.WithBodyAsJson(new { x = "y" })
|
||||||
|
.And
|
||||||
|
.UsingPost();
|
||||||
|
|
||||||
|
act.Should()
|
||||||
|
.Throw<Exception>()
|
||||||
|
.WithMessage("""Expected wiremockserver to have been called using body "{"x":"y"}", but didn't find it among the body/bodies "{"x":"123"}".""");
|
||||||
|
|
||||||
|
server.Stop();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task WithBodyAsString_When_NoMatch_ShouldHaveCorrectErrorMessage()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var server = WireMockServer.Start();
|
||||||
|
|
||||||
|
server
|
||||||
|
.Given(Request.Create().WithPath("/a").UsingPost())
|
||||||
|
.RespondWith(Response.Create().WithBody("A response"));
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var httpClient = new HttpClient();
|
||||||
|
|
||||||
|
await httpClient.PostAsync($"{server.Url}/a", new StringContent("123"));
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
Action act = () => server
|
||||||
|
.Should()
|
||||||
|
.HaveReceived(1)
|
||||||
|
.Calls()
|
||||||
|
.WithBody("abc")
|
||||||
|
.And
|
||||||
|
.UsingPost();
|
||||||
|
|
||||||
|
act.Should()
|
||||||
|
.Throw<Exception>()
|
||||||
|
.WithMessage("""Expected wiremockserver to have been called using body "abc", but didn't find it among the body/bodies "123".""");
|
||||||
|
|
||||||
|
server.Stop();
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task WithBodyAsBytes_When_NoMatch_ShouldHaveCorrectErrorMessage()
|
||||||
|
{
|
||||||
|
// Arrange
|
||||||
|
var server = WireMockServer.Start();
|
||||||
|
|
||||||
|
server
|
||||||
|
.Given(Request.Create().WithPath("/a").UsingPost())
|
||||||
|
.RespondWith(Response.Create().WithBody("A response"));
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var httpClient = new HttpClient();
|
||||||
|
|
||||||
|
await httpClient.PostAsync($"{server.Url}/a", new ByteArrayContent(new byte[] { 5 }));
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
Action act = () => server
|
||||||
|
.Should()
|
||||||
|
.HaveReceived(1)
|
||||||
|
.Calls()
|
||||||
|
.WithBodyAsBytes(new byte[] { 1 })
|
||||||
|
.And
|
||||||
|
.UsingPost();
|
||||||
|
|
||||||
|
act.Should()
|
||||||
|
.Throw<Exception>()
|
||||||
|
.WithMessage("""Expected wiremockserver to have been called using body "byte[1] {...}", but didn't find it among the body/bodies "byte[1] {...}".""");
|
||||||
|
|
||||||
|
server.Stop();
|
||||||
|
}
|
||||||
|
|
||||||
[Fact]
|
[Fact]
|
||||||
public async Task HaveReceived1Call_WithBodyAsBytes()
|
public async Task HaveReceived1Call_WithBodyAsBytes()
|
||||||
{
|
{
|
||||||
|
|||||||
Reference in New Issue
Block a user