Compare commits

..

6 Commits

Author SHA1 Message Date
Stef Heyenrath
ac72973cc4 1.0.3.14 2018-04-01 11:54:20 +02:00
Stef Heyenrath
e87f970057 PathSegments (#114) 2018-03-29 08:51:22 +02:00
Stef Heyenrath
df4a1f628a BodyAsJsonIndented (#113) 2018-03-28 09:51:01 +02:00
Stef Heyenrath
bdb79aec95 Add some more RequestMessageBodyMatcherTests (#112) 2018-03-28 08:18:33 +02:00
Stef Heyenrath
3369501506 1.0.3.13 2018-03-24 19:02:21 +01:00
Stef Heyenrath
8662638622 Fix #100 2018-03-24 18:40:59 +01:00
20 changed files with 423 additions and 71 deletions

View File

@@ -1,3 +1,18 @@
# 1.0.3.14 (01 April 2018)
- [#114](https://github.com/WireMock-Net/WireMock.Net/issues/114) - Feature: Add PathSegments in Transform +feature
- [#113](https://github.com/WireMock-Net/WireMock.Net/issues/113) - Feature: Add BodyAsJsonIndented for response message +feature
Commits: bdb79aec95...e87f970057
# 1.0.3.12 (24 March 2018)
- [#100](https://github.com/WireMock-Net/WireMock.Net/issues/100) - Issue: JsonPathMatcher - not working for rootless jsons?
Commits: ...
# 1.0.3.11 (20 March 2018)
- [#110](https://github.com/WireMock-Net/WireMock.Net/issues/110) - Fix: remove `Func[]` from MappingModel

View File

@@ -1,5 +1,5 @@
https://github.com/GitTools/GitReleaseNotes
GitReleaseNotes.exe . /OutputFile CHANGELOG.md /Version 1.0.3.11
GitReleaseNotes.exe . /OutputFile CHANGELOG.md /Version 1.0.3.14
GitReleaseNotes.exe . /OutputFile CHANGELOG.md /allTags

View File

@@ -160,18 +160,17 @@ namespace WireMock.Net.ConsoleApplication
.RespondWith(Response.Create().WithStatusCode(200).WithBody("partial = 200"));
// http://localhost:8080/any/any?start=1000&stop=1&stop=2
//server
// .Given(Request.Create().WithPath("/*").UsingGet())
// .WithGuid("90356dba-b36c-469a-a17e-669cd84f1f05")
// .AtPriority(server.Mappings.Count() + 1)
// .RespondWith(Response.Create()
// .WithStatusCode(200)
// .WithHeader("Content-Type", "application/json")
// .WithHeader("Transformed-Postman-Token", "token is {{request.headers.Postman-Token}}")
// .WithBody(@"{""msg"": ""Hello world CATCH-ALL on /*, {{request.path}}, bykey={{request.query.start}}, bykey={{request.query.stop}}, byidx0={{request.query.stop.[0]}}, byidx1={{request.query.stop.[1]}}"" }")
// .WithTransformer()
// .WithDelay(TimeSpan.FromMilliseconds(100))
// );
server
.Given(Request.Create().WithPath("/trans").UsingGet())
.WithGuid("90356dba-b36c-469a-a17e-669cd84f1f05")
.RespondWith(Response.Create()
.WithStatusCode(200)
.WithHeader("Content-Type", "application/json")
.WithHeader("Transformed-Postman-Token", "token is {{request.headers.Postman-Token}}")
.WithBody(@"{""msg"": ""Hello world CATCH-ALL on /*, {{request.path}}, bykey={{request.query.start}}, bykey={{request.query.stop}}, byidx0={{request.query.stop.[0]}}, byidx1={{request.query.stop.[1]}}"" }")
.WithTransformer()
.WithDelay(TimeSpan.FromMilliseconds(100))
);
server
.Given(Request.Create()

View File

@@ -3,7 +3,7 @@
<PropertyGroup>
<Description>Lightweight StandAlone Http Mocking Server for .Net.</Description>
<AssemblyTitle>WireMock.Net.StandAlone</AssemblyTitle>
<Version>1.0.3.11</Version>
<Version>1.0.3.14</Version>
<Authors>Stef Heyenrath</Authors>
<TargetFrameworks>net452;net46;netstandard1.3;netstandard2.0</TargetFrameworks>
<GenerateDocumentationFile>true</GenerateDocumentationFile>

View File

@@ -32,6 +32,11 @@ namespace WireMock.Admin.Mappings
/// </summary>
public object BodyAsJson { get; set; }
/// <summary>
/// Gets or sets a value indicating whether child objects to be indented according to the Newtonsoft.Json.JsonTextWriter.Indentation and Newtonsoft.Json.JsonTextWriter.IndentChar settings.
/// </summary>
public bool? BodyAsJsonIndented { get; set; }
/// <summary>
/// Gets or sets the body (as bytearray).
/// </summary>

View File

@@ -7,12 +7,11 @@ using WireMock.Validation;
namespace WireMock.Matchers
{
/// <summary>
/// JSONPathMatcher
/// JsonPathMatcher
/// </summary>
/// <seealso cref="IMatcher" />
public class JsonPathMatcher : IStringMatcher, IObjectMatcher
{
// private readonly object _jsonPattern;
private readonly string[] _patterns;
/// <summary>
@@ -26,13 +25,6 @@ namespace WireMock.Matchers
_patterns = patterns;
}
//public JsonPathMatcher([NotNull] object jsonPattern)
//{
// Check.NotNull(jsonPattern, nameof(jsonPattern));
// _jsonPattern = jsonPattern;
//}
/// <inheritdoc cref="IStringMatcher.IsMatch"/>
public double IsMatch(string input)
{
@@ -43,9 +35,8 @@ namespace WireMock.Matchers
try
{
JObject o = JObject.Parse(input);
return MatchScores.ToScore(_patterns.Select(p => o.SelectToken(p) != null));
var jtoken = JToken.Parse(input);
return IsMatch(jtoken);
}
catch (Exception)
{
@@ -63,9 +54,9 @@ namespace WireMock.Matchers
try
{
var o = input as JObject ?? JObject.FromObject(input);
return MatchScores.ToScore(_patterns.Select(p => o.SelectToken(p) != null));
// Check if JToken or object
JToken jtoken = input is JToken token ? token : JObject.FromObject(input);
return IsMatch(jtoken);
}
catch (Exception)
{
@@ -84,5 +75,13 @@ namespace WireMock.Matchers
{
return "JsonPathMatcher";
}
private double IsMatch(JToken jtoken)
{
// Wrap in array if needed
JToken jarray = jtoken is JArray ? jtoken : new JArray(jtoken);
return MatchScores.ToScore(_patterns.Select(pattern => jarray.SelectToken(pattern) != null));
}
}
}

View File

@@ -87,7 +87,8 @@ namespace WireMock.Owin
if (responseMessage.BodyAsJson != null)
{
string jsonBody = JsonConvert.SerializeObject(responseMessage.BodyAsJson, new JsonSerializerSettings { Formatting = Formatting.None, NullValueHandling = NullValueHandling.Ignore });
Formatting formatting = responseMessage.BodyAsJsonIndented == true ? Formatting.Indented : Formatting.None;
string jsonBody = JsonConvert.SerializeObject(responseMessage.BodyAsJson, new JsonSerializerSettings { Formatting = formatting, NullValueHandling = NullValueHandling.Ignore });
using (var writer = new StreamWriter(response.Body, responseMessage.BodyEncoding ?? _utf8NoBom))
{
await writer.WriteAsync(jsonBody);

View File

@@ -34,6 +34,11 @@ namespace WireMock
/// </summary>
public string Path { get; }
/// <summary>
/// Gets the path segments.
/// </summary>
public string[] PathSegments { get; }
/// <summary>
/// Gets the method.
/// </summary>
@@ -120,6 +125,7 @@ namespace WireMock
Port = url.Port;
Origin = $"{url.Scheme}://{url.Host}:{url.Port}";
Path = WebUtility.UrlDecode(url.AbsolutePath);
PathSegments = Path.Split('/').Skip(1).ToArray();
Method = method.ToLower();
ClientIP = clientIP;
@@ -157,11 +163,14 @@ namespace WireMock
Port = url.Port;
Origin = $"{url.Scheme}://{url.Host}:{url.Port}";
Path = WebUtility.UrlDecode(url.AbsolutePath);
PathSegments = Path.Split('/').Skip(1).ToArray();
Method = method.ToLower();
ClientIP = clientIP;
BodyAsBytes = bodyAsBytes;
Body = body;
BodyEncoding = bodyEncoding;
Headers = headers?.ToDictionary(header => header.Key, header => new WireMockList<string>(header.Value));
Cookies = cookies;
RawQuery = WebUtility.UrlDecode(url.Query);

View File

@@ -18,7 +18,6 @@ namespace WireMock.ResponseBuilders
/// <returns>A <see cref="IResponseBuilder"/>.</returns>
IResponseBuilder WithBody([NotNull] string body, [CanBeNull] string destination = BodyDestinationFormat.SameAsSource, [CanBeNull] Encoding encoding = null);
/// <summary>
/// WithBody : Create a ... response based on a callback function.
/// </summary>
@@ -26,8 +25,7 @@ namespace WireMock.ResponseBuilders
/// <param name="destination">The Body Destination format (SameAsSource, String or Bytes).</param>
/// <param name="encoding">The body encoding.</param>
/// <returns>A <see cref="IResponseBuilder"/>.</returns>
IResponseBuilder WithBody([NotNull] Func<RequestMessage,string> bodyFactory, [CanBeNull] string destination = BodyDestinationFormat.SameAsSource, [CanBeNull] Encoding encoding = null);
IResponseBuilder WithBody([NotNull] Func<RequestMessage, string> bodyFactory, [CanBeNull] string destination = BodyDestinationFormat.SameAsSource, [CanBeNull] Encoding encoding = null);
/// <summary>
/// WithBody : Create a ... response based on a bytearray.
@@ -43,8 +41,17 @@ namespace WireMock.ResponseBuilders
/// </summary>
/// <param name="body">The body.</param>
/// <param name="encoding">The body encoding.</param>
/// <param name="indented">Use JSON indented.</param>
/// <returns>A <see cref="IResponseBuilder"/>.</returns>
IResponseBuilder WithBodyAsJson([NotNull] object body, [CanBeNull] Encoding encoding = null);
IResponseBuilder WithBodyAsJson([NotNull] object body, [CanBeNull] Encoding encoding = null, bool? indented = null);
/// <summary>
/// WithBody : Create a string response based on a object (which will be converted to a JSON string).
/// </summary>
/// <param name="body">The body.</param>
/// <param name="indented">Define whether child objects to be indented according to the Newtonsoft.Json.JsonTextWriter.Indentation and Newtonsoft.Json.JsonTextWriter.IndentChar settings.</param>
/// <returns>A <see cref="IResponseBuilder"/>.</returns>
IResponseBuilder WithBodyAsJson([NotNull] object body, bool indented);
/// <summary>
/// WithBody : Create a string response based on a Base64 string (which will be decoded to a normal string).

View File

@@ -258,18 +258,25 @@ namespace WireMock.ResponseBuilders
return this;
}
/// <inheritdoc cref="IBodyResponseBuilder.WithBodyAsJson"/>
public IResponseBuilder WithBodyAsJson(object body, Encoding encoding = null)
/// <inheritdoc cref="IBodyResponseBuilder.WithBodyAsJson(object, Encoding, bool)"/>
public IResponseBuilder WithBodyAsJson(object body, Encoding encoding = null, bool? indented = null)
{
Check.NotNull(body, nameof(body));
ResponseMessage.BodyDestination = null;
ResponseMessage.BodyAsJson = body;
ResponseMessage.BodyEncoding = encoding;
ResponseMessage.BodyAsJsonIndented = indented;
return this;
}
/// <inheritdoc cref="IBodyResponseBuilder.WithBodyAsJson(object, bool)"/>
public IResponseBuilder WithBodyAsJson(object body, bool indented)
{
return WithBodyAsJson(body, null, indented);
}
/// <inheritdoc cref="IBodyResponseBuilder.WithBodyFromBase64"/>
public IResponseBuilder WithBodyFromBase64(string bodyAsbase64, Encoding encoding = null)
{

View File

@@ -42,6 +42,11 @@ namespace WireMock
/// </summary>
public object BodyAsJson { get; set; }
/// <summary>
/// Gets or sets a value indicating whether child objects to be indented according to the Newtonsoft.Json.JsonTextWriter.Indentation and Newtonsoft.Json.JsonTextWriter.IndentChar settings.
/// </summary>
public bool? BodyAsJsonIndented { get; set; }
/// <summary>
/// Gets or sets the body as bytes.
/// </summary>

View File

@@ -1,7 +1,5 @@
using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using WireMock.Admin.Mappings;
using WireMock.Matchers.Request;
using WireMock.RequestBuilders;
@@ -96,6 +94,7 @@ namespace WireMock.Serialization
mappingModel.Response.Headers = null;
mappingModel.Response.BodyDestination = null;
mappingModel.Response.BodyAsJson = null;
mappingModel.Response.BodyAsJsonIndented = null;
mappingModel.Response.Body = null;
mappingModel.Response.BodyAsBytes = null;
mappingModel.Response.BodyAsFile = null;
@@ -110,6 +109,7 @@ namespace WireMock.Serialization
mappingModel.Response.StatusCode = response.ResponseMessage.StatusCode;
mappingModel.Response.Headers = Map(response.ResponseMessage.Headers);
mappingModel.Response.BodyAsJson = response.ResponseMessage.BodyAsJson;
mappingModel.Response.BodyAsJsonIndented = response.ResponseMessage.BodyAsJsonIndented;
mappingModel.Response.Body = response.ResponseMessage.Body;
mappingModel.Response.BodyAsBytes = response.ResponseMessage.BodyAsBytes;
mappingModel.Response.BodyAsFile = response.ResponseMessage.BodyAsFile;
@@ -147,16 +147,14 @@ namespace WireMock.Serialization
return newDictionary;
}
//private static string[] Map<T>([CanBeNull] IEnumerable<Func<T, bool>> funcs)
//{
// return funcs?.Select(Map).Where(x => x != null).ToArray();
//}
private static string[] Map<T>([CanBeNull] IEnumerable<Func<T, bool>> funcs)
{
return funcs?.Select(Map).Where(x => x != null).ToArray();
}
private static string Map<T>([CanBeNull] Func<T, bool> func)
{
return func?.ToString();
}
//private static string Map<T>([CanBeNull] Func<T, bool> func)
//{
// return func?.ToString();
//}
}
}

View File

@@ -266,17 +266,19 @@ namespace WireMock.Server
private ResponseMessage SettingsUpdate(RequestMessage requestMessage)
{
var settings = requestMessage.Body != null ? JsonConvert.DeserializeObject<SettingsModel>(requestMessage.Body) : ((JObject)requestMessage.BodyAsJson).ToObject<SettingsModel>();
if (settings.AllowPartialMapping != null)
_options.AllowPartialMapping = settings.AllowPartialMapping.Value;
var settings = DeserializeObject<SettingsModel>(requestMessage);
_options.MaxRequestLogCount = settings.MaxRequestLogCount;
_options.RequestLogExpirationDuration = settings.RequestLogExpirationDuration;
if (settings.AllowPartialMapping != null)
{
_options.AllowPartialMapping = settings.AllowPartialMapping.Value;
}
if (settings.GlobalProcessingDelay != null)
{
_options.RequestProcessingDelay = TimeSpan.FromMilliseconds(settings.GlobalProcessingDelay.Value);
}
return new ResponseMessage { Body = "Settings updated" };
}
@@ -303,7 +305,7 @@ namespace WireMock.Server
{
Guid guid = Guid.Parse(requestMessage.Path.TrimStart(AdminMappings.ToCharArray()));
MappingModel mappingModel = requestMessage.Body != null ? JsonConvert.DeserializeObject<MappingModel>(requestMessage.Body) : ((JObject)requestMessage.BodyAsJson).ToObject<MappingModel>();
var mappingModel = DeserializeObject<MappingModel>(requestMessage);
DeserializeAndAddOrUpdateMapping(mappingModel, guid);
return new ResponseMessage { Body = "Mapping added or updated" };
@@ -371,7 +373,7 @@ namespace WireMock.Server
{
try
{
MappingModel mappingModel = requestMessage.Body != null ? JsonConvert.DeserializeObject<MappingModel>(requestMessage.Body) : ((JObject)requestMessage.BodyAsJson).ToObject<MappingModel>();
var mappingModel = DeserializeObject<MappingModel>(requestMessage);
DeserializeAndAddOrUpdateMapping(mappingModel);
}
catch (ArgumentException a)
@@ -552,7 +554,7 @@ namespace WireMock.Server
#region Requests/find
private ResponseMessage RequestsFind(RequestMessage requestMessage)
{
var requestModel = requestMessage.Body != null ? JsonConvert.DeserializeObject<RequestModel>(requestMessage.Body) : ((JObject)requestMessage.BodyAsJson).ToObject<RequestModel>();
var requestModel = DeserializeObject<RequestModel>(requestMessage);
var request = (Request)InitRequestBuilder(requestModel);
@@ -598,8 +600,7 @@ namespace WireMock.Server
if (requestModel.ClientIP != null)
{
string clientIP = requestModel.ClientIP as string;
if (clientIP != null)
if (requestModel.ClientIP is string clientIP)
{
requestBuilder = requestBuilder.WithClientIP(clientIP);
}
@@ -615,8 +616,7 @@ namespace WireMock.Server
if (requestModel.Path != null)
{
string path = requestModel.Path as string;
if (path != null)
if (requestModel.Path is string path)
{
requestBuilder = requestBuilder.WithPath(path);
}
@@ -632,8 +632,7 @@ namespace WireMock.Server
if (requestModel.Url != null)
{
string url = requestModel.Url as string;
if (url != null)
if (requestModel.Url is string url)
{
requestBuilder = requestBuilder.WithUrl(url);
}
@@ -739,7 +738,7 @@ namespace WireMock.Server
}
else if (responseModel.BodyAsJson != null)
{
responseBuilder = responseBuilder.WithBodyAsJson(responseModel.BodyAsJson, ToEncoding(responseModel.BodyEncoding));
responseBuilder = responseBuilder.WithBodyAsJson(responseModel.BodyAsJson, ToEncoding(responseModel.BodyEncoding), responseModel.BodyAsJsonIndented == true);
}
else if (responseModel.BodyFromBase64 != null)
{
@@ -768,5 +767,12 @@ namespace WireMock.Server
{
return encodingModel != null ? Encoding.GetEncoding(encodingModel.CodePage) : null;
}
private T DeserializeObject<T>(RequestMessage requestMessage)
{
return requestMessage.Body != null ?
JsonConvert.DeserializeObject<T>(requestMessage.Body) :
((JObject)requestMessage.BodyAsJson).ToObject<T>();
}
}
}

View File

@@ -21,7 +21,8 @@ namespace WireMock.Transformers
var template = new { request = requestMessage };
// Body
string body = bodyIsJson ? JsonConvert.SerializeObject(original.BodyAsJson) : original.Body;
Formatting formatting = original.BodyAsJsonIndented == true ? Formatting.Indented : Formatting.None;
string body = bodyIsJson ? JsonConvert.SerializeObject(original.BodyAsJson, formatting) : original.Body;
if (body != null)
{
var templateBody = Handlebars.Compile(body);

View File

@@ -3,7 +3,7 @@
<PropertyGroup>
<Description>Lightweight Http Mocking Server for .Net, inspired by WireMock from the Java landscape.</Description>
<AssemblyTitle>WireMock.Net</AssemblyTitle>
<Version>1.0.3.11</Version>
<Version>1.0.3.14</Version>
<Authors>Stef Heyenrath</Authors>
<TargetFrameworks>net452;net46;netstandard1.3;netstandard2.0</TargetFrameworks>
<GenerateDocumentationFile>true</GenerateDocumentationFile>

View File

@@ -232,6 +232,40 @@ namespace WireMock.Net.Tests
Check.That(response).IsEqualTo("Hello world!");
}
[Fact]
public async Task FluentMockServer_Should_respond_to_request_BodyAsJson()
{
// Assign
_server = FluentMockServer.Start();
_server
.Given(Request.Create().UsingAnyVerb())
.RespondWith(Response.Create().WithBodyAsJson(new { message = "Hello" }));
// Act
var response = await new HttpClient().GetStringAsync("http://localhost:" + _server.Ports[0]);
// Assert
Check.That(response).IsEqualTo("{\"message\":\"Hello\"}");
}
[Fact]
public async Task FluentMockServer_Should_respond_to_request_BodyAsJson_Indented()
{
// Assign
_server = FluentMockServer.Start();
_server
.Given(Request.Create().UsingAnyVerb())
.RespondWith(Response.Create().WithBodyAsJson(new { message = "Hello" }, true));
// Act
var response = await new HttpClient().GetStringAsync("http://localhost:" + _server.Ports[0]);
// Assert
Check.That(response).IsEqualTo("{\r\n \"message\": \"Hello\"\r\n}");
}
[Fact]
public async Task FluentMockServer_Should_respond_to_request_bodyAsCallback()
{

View File

@@ -1,4 +1,5 @@
using NFluent;
using Newtonsoft.Json.Linq;
using NFluent;
using WireMock.Matchers;
using Xunit;
@@ -31,5 +32,104 @@ namespace WireMock.Net.Tests.Matchers
// Assert
Check.That(patterns).ContainsExactly("X");
}
[Fact]
public void JsonPathMatcher_IsMatch_NullString()
{
// Assign
string s = null;
var matcher = new JsonPathMatcher("");
// Act
double match = matcher.IsMatch(s);
// Assert
Check.That(match).IsEqualTo(0);
}
[Fact]
public void JsonPathMatcher_IsMatch_NullObject()
{
// Assign
object o = null;
var matcher = new JsonPathMatcher("");
// Act
double match = matcher.IsMatch(o);
// Assert
Check.That(match).IsEqualTo(0);
}
[Fact]
public void JsonPathMatcher_IsMatch_String_Exception_Mismatch()
{
// Assign
var matcher = new JsonPathMatcher("xxx");
// Act
double match = matcher.IsMatch("");
// Assert
Check.That(match).IsEqualTo(0);
}
[Fact]
public void JsonPathMatcher_IsMatch_Object_Exception_Mismatch()
{
// Assign
var matcher = new JsonPathMatcher("xxx");
// Act
double match = matcher.IsMatch("");
// Assert
Check.That(match).IsEqualTo(0);
}
[Fact]
public void JsonPathMatcher_IsMatch_AnonymousObject()
{
// Assign
var matcher = new JsonPathMatcher("$..[?(@.Id == 1)]");
// Act
double match = matcher.IsMatch(new { Id = 1, Name = "Test" });
// Assert
Check.That(match).IsEqualTo(1);
}
[Fact]
public void JsonPathMatcher_IsMatch_JObject()
{
// Assign
string[] patterns = { "$..[?(@.Id == 1)]" };
var matcher = new JsonPathMatcher(patterns);
// Act
var jobject = new JObject
{
{ "Id", new JValue(1) },
{ "Name", new JValue("Test") }
};
double match = matcher.IsMatch(jobject);
// Assert
Check.That(match).IsEqualTo(1);
}
[Fact]
public void JsonPathMatcher_IsMatch_JObject_Parsed()
{
// Assign
var matcher = new JsonPathMatcher("$..[?(@.Id == 1)]");
// Act
double match = matcher.IsMatch(JObject.Parse("{\"Id\":1,\"Name\":\"Test\"}"));
// Assert
Check.That(match).IsEqualTo(1);
}
}
}

View File

@@ -0,0 +1,145 @@
using System;
using Moq;
using NFluent;
using WireMock.Matchers;
using WireMock.Matchers.Request;
using WireMock.Util;
using Xunit;
namespace WireMock.Net.Tests.RequestMatchers
{
public class RequestMessageBodyMatcherTests
{
[Fact]
public void RequestMessageBodyMatcher_GetMatchingScore_BodyAsString_IStringMatcher()
{
// Assign
var body = new BodyData
{
BodyAsString = "b"
};
var stringMatcherMock = new Mock<IStringMatcher>();
stringMatcherMock.Setup(m => m.IsMatch(It.IsAny<string>())).Returns(0.5d);
var requestMessage = new RequestMessage(new Uri("http://localhost"), "GET", "127.0.0.1", body);
var matcher = new RequestMessageBodyMatcher(stringMatcherMock.Object);
// Act
var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result);
// Assert
Check.That(score).IsEqualTo(0.5d);
// Verify
stringMatcherMock.Verify(m => m.GetPatterns(), Times.Never);
stringMatcherMock.Verify(m => m.IsMatch("b"), Times.Once);
}
[Fact]
public void RequestMessageBodyMatcher_GetMatchingScore_BodyAsBytes_IStringMatcher()
{
// Assign
var body = new BodyData
{
BodyAsBytes = new byte[] { 1 }
};
var stringMatcherMock = new Mock<IStringMatcher>();
stringMatcherMock.Setup(m => m.IsMatch(It.IsAny<string>())).Returns(0.5d);
var requestMessage = new RequestMessage(new Uri("http://localhost"), "GET", "127.0.0.1", body);
var matcher = new RequestMessageBodyMatcher(stringMatcherMock.Object);
// Act
var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result);
// Assert
Check.That(score).IsEqualTo(0.0d);
// Verify
stringMatcherMock.Verify(m => m.GetPatterns(), Times.Never);
stringMatcherMock.Verify(m => m.IsMatch(It.IsAny<string>()), Times.Never);
}
[Fact]
public void RequestMessageBodyMatcher_GetMatchingScore_BodyAsJson_IStringMatcher()
{
// Assign
var body = new BodyData
{
BodyAsJson = new { value = 42 }
};
var stringMatcherMock = new Mock<IStringMatcher>();
stringMatcherMock.Setup(m => m.IsMatch(It.IsAny<string>())).Returns(0.5d);
var requestMessage = new RequestMessage(new Uri("http://localhost"), "GET", "127.0.0.1", body);
var matcher = new RequestMessageBodyMatcher(stringMatcherMock.Object);
// Act
var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result);
// Assert
Check.That(score).IsEqualTo(0.0d);
// Verify
stringMatcherMock.Verify(m => m.IsMatch("b"), Times.Never);
}
[Fact]
public void RequestMessageBodyMatcher_GetMatchingScore_BodyAsJson_IObjectMatcher()
{
// Assign
var body = new BodyData
{
BodyAsJson = 42
};
var objectMatcherMock = new Mock<IObjectMatcher>();
objectMatcherMock.Setup(m => m.IsMatch(It.IsAny<object>())).Returns(0.5d);
var requestMessage = new RequestMessage(new Uri("http://localhost"), "GET", "127.0.0.1", body);
var matcher = new RequestMessageBodyMatcher(objectMatcherMock.Object);
// Act
var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result);
// Assert
Check.That(score).IsEqualTo(0.5d);
// Verify
objectMatcherMock.Verify(m => m.IsMatch(42), Times.Once);
}
[Fact]
public void RequestMessageBodyMatcher_GetMatchingScore_BodyAsBytes_IObjectMatcher()
{
// Assign
var body = new BodyData
{
BodyAsBytes = new byte[] { 1 }
};
var objectMatcherMock = new Mock<IObjectMatcher>();
objectMatcherMock.Setup(m => m.IsMatch(It.IsAny<object>())).Returns(0.5d);
var requestMessage = new RequestMessage(new Uri("http://localhost"), "GET", "127.0.0.1", body);
var matcher = new RequestMessageBodyMatcher(objectMatcherMock.Object);
// Act
var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result);
// Assert
Check.That(score).IsEqualTo(0.5d);
// Verify
objectMatcherMock.Verify(m => m.IsMatch(It.IsAny<byte[]>()), Times.Once);
}
}
}

View File

@@ -1,5 +1,6 @@
using System;
using NFluent;
using WireMock.Util;
using Xunit;
namespace WireMock.Net.Tests
@@ -50,5 +51,25 @@ namespace WireMock.Net.Tests
Check.That(request.GetParameter("key")).Contains("2");
Check.That(request.GetParameter("key")).Contains("3");
}
[Fact]
public void RequestMessage_Constructor1_PathSegments()
{
// Assign
var request = new RequestMessage(new Uri("http://localhost/a/b/c"), "POST", ClientIp);
// Assert
Check.That(request.PathSegments).ContainsExactly("a", "b", "c");
}
[Fact]
public void RequestMessage_Constructor2_PathSegments()
{
// Assign
var request = new RequestMessage(new Uri("http://localhost/a/b/c"), "POST", ClientIp, new BodyData());
// Assert
Check.That(request.PathSegments).ContainsExactly("a", "b", "c");
}
}
}

View File

@@ -147,7 +147,7 @@ namespace WireMock.Net.Tests
public void Request_WithBodyJsonPathMatcher_true()
{
// given
var spec = Request.Create().UsingAnyVerb().WithBody(new JsonPathMatcher("$.things[?(@.name == 'RequiredThing')]"));
var spec = Request.Create().UsingAnyVerb().WithBody(new JsonPathMatcher("$..things[?(@.name == 'RequiredThing')]"));
// when
string bodyAsString = "{ \"things\": [ { \"name\": \"RequiredThing\" }, { \"name\": \"Wiremock\" } ] }";
@@ -179,7 +179,7 @@ namespace WireMock.Net.Tests
public void Request_WithBodyAsJson_Object_JsonPathMatcher_true()
{
// given
var spec = Request.Create().UsingAnyVerb().WithBody(new JsonPathMatcher("$.things[?(@.name == 'RequiredThing')]"));
var spec = Request.Create().UsingAnyVerb().WithBody(new JsonPathMatcher("$..things[?(@.name == 'RequiredThing')]"));
// when
string jsonString = "{ \"things\": [ { \"name\": \"RequiredThing\" }, { \"name\": \"Wiremock\" } ] }";
@@ -199,7 +199,7 @@ namespace WireMock.Net.Tests
public void Request_WithBodyAsJson_Array_JsonPathMatcher_1()
{
// given
var spec = Request.Create().UsingAnyVerb().WithBody(new JsonPathMatcher("$.books[?(@.price < 10)]"));
var spec = Request.Create().UsingAnyVerb().WithBody(new JsonPathMatcher("$..books[?(@.price < 10)]"));
// when
string jsonString = "{ \"books\": [ { \"category\": \"test1\", \"price\": 8.95 }, { \"category\": \"test2\", \"price\": 20 } ] }";