Compare commits

...

8 Commits

Author SHA1 Message Date
Stef Heyenrath
9e9eadf693 1.0.4.4 (#156) 2018-07-01 11:10:34 +02:00
Stef Heyenrath
fe9f4902b1 1.0.4.3 2018-06-30 00:06:53 +02:00
Stef Heyenrath
db013a56ad Merge branch 'param' 2018-06-29 23:59:30 +02:00
Stef Heyenrath
7b2deceafd Merge branch 'Fix_IRequestBuilder.WithParam' 2018-06-29 22:32:31 +02:00
Stef Heyenrath
281b970c57 WithParam (#159) 2018-06-28 20:50:09 +02:00
Stef Heyenrath
768cc621ad #156 2018-06-27 20:19:27 +02:00
Stef Heyenrath
3df8bd2fdc #156 2018-06-27 20:02:16 +02:00
Stef Heyenrath
2d1ead25cd #156 2018-06-27 19:56:53 +02:00
23 changed files with 259 additions and 71 deletions

View File

@@ -1,3 +1,18 @@
# 1.0.4.4 (01 July 2018)
- [#156](https://github.com/WireMock-Net/WireMock.Net/issues/156) - Feature: when adding / updating a mapping : return more details
Commits: ...
# 1.0.4.3 (30 June 2018)
- [#159](https://github.com/WireMock-Net/WireMock.Net/issues/159) - Bug: IRequestBuilder.WithParam broken for key-only matching +fix
- [#156](https://github.com/WireMock-Net/WireMock.Net/issues/156) - Feature: when adding / updating a mapping : return more details
Commits: 2d1ead25cd...db013a56ad
# 1.0.4.2 (26 June 2018)
- [#157](https://github.com/WireMock-Net/WireMock.Net/pull/157) - Support for string and object in JsonMatcher. contributed by Stef Heyenrath ([StefH](https://github.com/StefH)) +feature

View File

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

View File

@@ -43,11 +43,11 @@ namespace WireMock.Net.Client
var request = api.GetRequestsAsync().Result;
Console.WriteLine($"request = {JsonConvert.SerializeObject(request)}");
string deleteRequestsAsync = api.DeleteRequestsAsync().Result;
Console.WriteLine($"deleteRequestsAsync = {deleteRequestsAsync}");
var deleteRequestsAsync = api.DeleteRequestsAsync().Result;
Console.WriteLine($"deleteRequestsAsync = {deleteRequestsAsync.Status}");
string resetRequestsAsync = api.ResetRequestsAsync().Result;
Console.WriteLine($"resetRequestsAsync = {resetRequestsAsync}");
var resetRequestsAsync = api.ResetRequestsAsync().Result;
Console.WriteLine($"resetRequestsAsync = {resetRequestsAsync.Status}");
Console.WriteLine("Press any key to quit");
Console.ReadKey();

View File

@@ -81,8 +81,29 @@ namespace WireMock.Net.ConsoleApplication
.WithParam("$filter", "(substringof(Code, 'WA')")
.UsingGet())
.RespondWith(Response.Create()
.WithHeader("Content-Type", "application/json")
.WithBody(@"{ ""result"": ""odata""}"));
server
.Given(Request
.Create()
.WithPath(new WildcardMatcher("/param2", true))
.WithParam("key", "test")
.UsingGet())
.RespondWith(Response.Create()
.WithHeader("Content-Type", "application/json")
.WithBodyAsJson(new { result = "param2" }));
server
.Given(Request
.Create()
.WithPath(new WildcardMatcher("/param3", true))
.WithParam("key", new WildcardMatcher("t*"))
.UsingGet())
.RespondWith(Response.Create()
.WithHeader("Content-Type", "application/json")
.WithBodyAsJson(new { result = "param3" }));
server
.Given(Request.Create().WithPath("/headers", "/headers_test").UsingPost().WithHeader("Content-Type", "application/json*"))
.RespondWith(Response.Create()

View File

@@ -41,6 +41,7 @@ namespace WireMock.Net.StandAlone
Arguments[currentName] = values.ToArray();
}
}
public bool Contains(string name)
{
return Arguments.ContainsKey(name);

View File

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

View File

@@ -1,4 +1,4 @@
using System.Collections.Generic;
// using System.Collections.Generic;
namespace WireMock.Admin.Mappings
{
@@ -12,10 +12,15 @@ namespace WireMock.Admin.Mappings
/// </summary>
public string Name { get; set; }
///// <summary>
///// Gets or sets the values.
///// </summary>
//public IList<string> Values { get; set; }
/// <summary>
/// Gets or sets the values.
/// Gets or sets the matchers.
/// </summary>
public IList<string> Values { get; set; }
public MatcherModel[] Matchers { get; set; }
///// <summary>
///// Gets or sets the functions.

View File

@@ -0,0 +1,20 @@
using System;
namespace WireMock.Admin.Mappings
{
/// <summary>
/// Status
/// </summary>
public class StatusModel
{
/// <summary>
/// The optional guid.
/// </summary>
public Guid? Guid { get; set; }
/// <summary>
/// The status (can also contain the error message).
/// </summary>
public string Status { get; set; }
}
}

View File

@@ -33,7 +33,7 @@ namespace WireMock.Client
/// <param name="settings">SettingsModel</param>
[Put("__admin/settings")]
[Header("Content-Type", "application/json")]
Task<string> PutSettingsAsync([Body] SettingsModel settings);
Task<StatusModel> PutSettingsAsync([Body] SettingsModel settings);
/// <summary>
/// Update the settings
@@ -41,7 +41,7 @@ namespace WireMock.Client
/// <param name="settings">SettingsModel</param>
[Post("__admin/settings")]
[Header("Content-Type", "application/json")]
Task<string> PostSettingsAsync([Body] SettingsModel settings);
Task<StatusModel> PostSettingsAsync([Body] SettingsModel settings);
/// <summary>
/// Get the mappings.
@@ -56,19 +56,19 @@ namespace WireMock.Client
/// <param name="mapping">MappingModel</param>
[Post("__admin/mappings")]
[Header("Content-Type", "application/json")]
Task<string> PostMappingAsync([Body] MappingModel mapping);
Task<StatusModel> PostMappingAsync([Body] MappingModel mapping);
/// <summary>
/// Delete all mappings.
/// </summary>
[Delete("__admin/mappings")]
Task<string> DeleteMappingsAsync();
Task<StatusModel> DeleteMappingsAsync();
/// <summary>
/// Delete (reset) all mappings.
/// </summary>
[Post("__admin/mappings/reset")]
Task<string> ResetMappingsAsync();
Task<StatusModel> ResetMappingsAsync();
/// <summary>
/// Get a mapping based on the guid
@@ -84,20 +84,20 @@ namespace WireMock.Client
/// <param name="guid">The Guid</param>
/// <param name="mapping">MappingModel</param>
[Put("__admin/mappings/{guid}")]
Task<string> PutMappingAsync([Path] Guid guid, [Body] MappingModel mapping);
Task<StatusModel> PutMappingAsync([Path] Guid guid, [Body] MappingModel mapping);
/// <summary>
/// Delete a mapping based on the guid
/// </summary>
/// <param name="guid">The Guid</param>
[Delete("__admin/mappings/{guid}")]
Task<string> DeleteMappingAsync([Path] Guid guid);
Task<StatusModel> DeleteMappingAsync([Path] Guid guid);
/// <summary>
/// Save the mappings
/// </summary>
[Post("__admin/mappings/save")]
Task<string> SaveMappingAsync();
Task<StatusModel> SaveMappingAsync();
/// <summary>
/// Get the requests.
@@ -110,13 +110,13 @@ namespace WireMock.Client
/// Delete all requests.
/// </summary>
[Delete("__admin/requests")]
Task<string> DeleteRequestsAsync();
Task<StatusModel> DeleteRequestsAsync();
/// <summary>
/// Delete (reset) all requests.
/// </summary>
[Post("__admin/requests/reset")]
Task<string> ResetRequestsAsync();
Task<StatusModel> ResetRequestsAsync();
/// <summary>
/// Get a request based on the guid
@@ -131,7 +131,7 @@ namespace WireMock.Client
/// </summary>
/// <param name="guid">The Guid</param>
[Delete("__admin/requests/{guid}")]
Task<string> DeleteRequestAsync([Path] Guid guid);
Task<StatusModel> DeleteRequestAsync([Path] Guid guid);
/// <summary>
/// Find a request based on the criteria
@@ -151,12 +151,12 @@ namespace WireMock.Client
/// Delete (reset) all scenarios
/// </summary>
[Delete("__admin/scenarios")]
Task<string> DeleteScenariosAsync();
Task<StatusModel> DeleteScenariosAsync();
/// <summary>
/// Delete (reset) all scenarios
/// </summary>
[Post("__admin/scenarios")]
Task<string> ResetScenariosAsync();
Task<StatusModel> ResetScenariosAsync();
}
}

View File

@@ -25,16 +25,16 @@ namespace WireMock.Matchers.Request
public string Key { get; }
/// <summary>
/// The values
/// The matchers.
/// </summary>
public IEnumerable<string> Values { get; }
public IReadOnlyList<IStringMatcher> Matchers { get; }
/// <summary>
/// Initializes a new instance of the <see cref="RequestMessageParamMatcher"/> class.
/// </summary>
/// <param name="matchBehaviour">The match behaviour.</param>
/// <param name="key">The key.</param>
public RequestMessageParamMatcher(MatchBehaviour matchBehaviour, [NotNull] string key) : this(matchBehaviour, key, null)
public RequestMessageParamMatcher(MatchBehaviour matchBehaviour, [NotNull] string key) : this(matchBehaviour, key, (IStringMatcher[])null)
{
}
@@ -44,13 +44,23 @@ namespace WireMock.Matchers.Request
/// <param name="matchBehaviour">The match behaviour.</param>
/// <param name="key">The key.</param>
/// <param name="values">The values.</param>
public RequestMessageParamMatcher(MatchBehaviour matchBehaviour, [NotNull] string key, [CanBeNull] IEnumerable<string> values)
public RequestMessageParamMatcher(MatchBehaviour matchBehaviour, [NotNull] string key, [CanBeNull] string[] values) : this(matchBehaviour, key, values?.Select(value => new ExactMatcher(matchBehaviour, value)).Cast<IStringMatcher>().ToArray())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="RequestMessageParamMatcher"/> class.
/// </summary>
/// <param name="matchBehaviour">The match behaviour.</param>
/// <param name="key">The key.</param>
/// <param name="matchers">The matchers.</param>
public RequestMessageParamMatcher(MatchBehaviour matchBehaviour, [NotNull] string key, [CanBeNull] IStringMatcher[] matchers)
{
Check.NotNull(key, nameof(key));
_matchBehaviour = matchBehaviour;
Key = key;
Values = values;
Matchers = matchers;
}
/// <summary>
@@ -78,21 +88,33 @@ namespace WireMock.Matchers.Request
return MatchScores.ToScore(requestMessage.Query != null && Funcs.Any(f => f(requestMessage.Query)));
}
var values = requestMessage.GetParameter(Key);
if (values == null)
WireMockList<string> valuesPresentInRequestMessage = requestMessage.GetParameter(Key);
if (valuesPresentInRequestMessage == null)
{
// Key is not present, just return Mismatch
// Key is not present at all, just return Mismatch
return MatchScores.Mismatch;
}
if (values.Count == 0 && (Values == null || !Values.Any()))
if (Matchers != null && Matchers.Any())
{
// Key is present, but no values or null, just return Perfect
// Matchers are defined, just use the matchers to calculate the match score.
var scores = new List<double>();
foreach (string valuePresentInRequestMessage in valuesPresentInRequestMessage)
{
double score = Matchers.Max(m => m.IsMatch(valuePresentInRequestMessage));
scores.Add(score);
}
return scores.Any() ? scores.Average() : MatchScores.Mismatch;
}
if (Matchers == null || !Matchers.Any())
{
// Matchers are null or not defined, and Key is present, just return Perfect.
return MatchScores.Perfect;
}
var matches = Values.Select(v => values.Contains(v));
return MatchScores.ToScore(matches);
return MatchScores.Mismatch;
}
}
}

View File

@@ -49,7 +49,7 @@ namespace WireMock.Owin
catch (Exception ex)
{
_options.Logger.Error("HttpStatusCode set to 500 {0}", ex);
await _responseMapper.MapAsync(new ResponseMessage { StatusCode = 500, Body = JsonConvert.SerializeObject(ex) }, ctx.Response);
await _responseMapper.MapAsync(ResponseMessageBuilder.Create(JsonConvert.SerializeObject(ex), 500), ctx.Response);
}
}
}

View File

@@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using WireMock.Logging;
using WireMock.Matchers.Request;
@@ -6,6 +7,7 @@ using System.Linq;
using WireMock.Matchers;
using WireMock.Util;
using Newtonsoft.Json;
using WireMock.Admin.Mappings;
using WireMock.Http;
using WireMock.Serialization;
#if !NETSTANDARD
@@ -22,6 +24,8 @@ namespace WireMock.Owin
internal class WireMockMiddleware
#endif
{
private readonly IDictionary<string, WireMockList<string>> _contentTypeJsonHeaders = new Dictionary<string, WireMockList<string>> { { HttpKnownHeaderNames.ContentType, new WireMockList<string> { "application/json" } } };
private static readonly Task CompletedTask = Task.FromResult(false);
private readonly WireMockMiddlewareOptions _options;
@@ -98,7 +102,7 @@ namespace WireMock.Owin
{
logRequest = true;
_options.Logger.Warn("HttpStatusCode set to 404 : No matching mapping found");
response = new ResponseMessage { StatusCode = 404, Body = "No matching mapping found" };
response = ResponseMessageBuilder.Create("No matching mapping found", 404);
return;
}
@@ -110,7 +114,7 @@ namespace WireMock.Owin
if (!present || _options.AuthorizationMatcher.IsMatch(authorization.ToString()) < MatchScores.Perfect)
{
_options.Logger.Error("HttpStatusCode set to 401");
response = new ResponseMessage { StatusCode = 401 };
response = ResponseMessageBuilder.Create(null, 401);
return;
}
}
@@ -130,7 +134,7 @@ namespace WireMock.Owin
catch (Exception ex)
{
_options.Logger.Error("HttpStatusCode set to 500");
response = new ResponseMessage { StatusCode = 500, Body = JsonConvert.SerializeObject(ex) };
response = ResponseMessageBuilder.Create(JsonConvert.SerializeObject(ex), 500);
}
finally
{

View File

@@ -27,6 +27,14 @@ namespace WireMock.RequestBuilders
/// <returns>The <see cref="IRequestBuilder"/>.</returns>
IRequestBuilder WithParam([NotNull] string key, [CanBeNull] params string[] values);
/// <summary>
/// WithParam: matching on key and matchers.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="matchers">The matchers.</param>
/// <returns>The <see cref="IRequestBuilder"/>.</returns>
IRequestBuilder WithParam([NotNull] string key, [CanBeNull] params IStringMatcher[] matchers);
/// <summary>
/// WithParam: matching on key, values and matchBehaviour.
/// </summary>
@@ -36,6 +44,15 @@ namespace WireMock.RequestBuilders
/// <returns>The <see cref="IRequestBuilder"/>.</returns>
IRequestBuilder WithParam([NotNull] string key, MatchBehaviour matchBehaviour, [CanBeNull] params string[] values);
/// <summary>
/// WithParam: matching on key, matchers and matchBehaviour.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="matchers">The matchers.</param>
/// <param name="matchBehaviour">The match behaviour.</param>
/// <returns>The <see cref="IRequestBuilder"/>.</returns>
IRequestBuilder WithParam([NotNull] string key, MatchBehaviour matchBehaviour, [CanBeNull] params IStringMatcher[] matchers);
/// <summary>
/// WithParam: matching on functions.
/// </summary>

View File

@@ -306,6 +306,12 @@ namespace WireMock.RequestBuilders
return WithParam(key, MatchBehaviour.AcceptOnMatch, values);
}
/// <inheritdoc cref="IParamsRequestBuilder.WithParam(string, IStringMatcher[])"/>
public IRequestBuilder WithParam(string key, params IStringMatcher[] matchers)
{
return WithParam(key, MatchBehaviour.AcceptOnMatch, matchers);
}
/// <inheritdoc cref="IParamsRequestBuilder.WithParam(string, MatchBehaviour, string[])"/>
public IRequestBuilder WithParam(string key, MatchBehaviour matchBehaviour, params string[] values)
{
@@ -315,6 +321,15 @@ namespace WireMock.RequestBuilders
return this;
}
/// <inheritdoc cref="IParamsRequestBuilder.WithParam(string, MatchBehaviour, IStringMatcher[])"/>
public IRequestBuilder WithParam(string key, MatchBehaviour matchBehaviour, params IStringMatcher[] matchers)
{
Check.NotNull(key, nameof(key));
_requestMatchers.Add(new RequestMessageParamMatcher(matchBehaviour, key, matchers));
return this;
}
/// <inheritdoc cref="IParamsRequestBuilder.WithParam(Func{IDictionary{string, WireMockList{string}}, bool}[])"/>
public IRequestBuilder WithParam(params Func<IDictionary<string, WireMockList<string>>, bool>[] funcs)
{

View File

@@ -0,0 +1,26 @@
using System;
using System.Collections.Generic;
using WireMock.Admin.Mappings;
using WireMock.Http;
using WireMock.Util;
namespace WireMock
{
internal static class ResponseMessageBuilder
{
private static string ContentTypeJson = "application/json";
private static readonly IDictionary<string, WireMockList<string>> ContentTypeJsonHeaders = new Dictionary<string, WireMockList<string>> { { HttpKnownHeaderNames.ContentType, new WireMockList<string> { ContentTypeJson } } };
internal static ResponseMessage Create(string message, int statusCode = 200, Guid? guid = null)
{
var response = new ResponseMessage
{
StatusCode = statusCode,
Headers = ContentTypeJsonHeaders,
BodyAsJson = message != null ? new StatusModel { Status = message, Guid = guid } : null
};
return response;
}
}
}

View File

@@ -71,7 +71,7 @@ namespace WireMock.Serialization
Params = paramsMatchers != null && paramsMatchers.Any() ? paramsMatchers.Select(pm => new ParamModel
{
Name = pm.Key,
Values = pm.Values?.ToList()
Matchers = MatcherMapper.Map(pm.Matchers)
//Funcs = Map(pm.Funcs)
}).ToList() : null,

View File

@@ -283,7 +283,7 @@ namespace WireMock.Server
_options.RequestProcessingDelay = TimeSpan.FromMilliseconds(settings.GlobalProcessingDelay.Value);
}
return new ResponseMessage { Body = "Settings updated" };
return ResponseMessageBuilder.Create("Settings updated");
}
#endregion Settings
@@ -296,7 +296,7 @@ namespace WireMock.Server
if (mapping == null)
{
_logger.Warn("HttpStatusCode set to 404 : Mapping not found");
return new ResponseMessage { StatusCode = 404, Body = "Mapping not found" };
return ResponseMessageBuilder.Create("Mapping not found", 404);
}
var model = MappingConverter.ToMappingModel(mapping);
@@ -311,7 +311,7 @@ namespace WireMock.Server
var mappingModel = DeserializeObject<MappingModel>(requestMessage);
DeserializeAndAddOrUpdateMapping(mappingModel, guid);
return new ResponseMessage { Body = "Mapping added or updated" };
return ResponseMessageBuilder.Create("Mapping added or updated", 200, guid);
}
private ResponseMessage MappingDelete(RequestMessage requestMessage)
@@ -320,10 +320,10 @@ namespace WireMock.Server
if (DeleteMapping(guid))
{
return new ResponseMessage { Body = "Mapping removed" };
return ResponseMessageBuilder.Create("Mapping removed", 200, guid);
}
return new ResponseMessage { Body = "Mapping not found" };
return ResponseMessageBuilder.Create("Mapping not found", 404);
}
#endregion Mapping/{guid}
@@ -335,7 +335,7 @@ namespace WireMock.Server
SaveMappingToFile(mapping);
}
return new ResponseMessage { Body = "Mappings saved to disk" };
return ResponseMessageBuilder.Create("Mappings saved to disk");
}
private void SaveMappingToFile(Mapping mapping)
@@ -374,26 +374,27 @@ namespace WireMock.Server
private ResponseMessage MappingsPost(RequestMessage requestMessage)
{
Guid? guid;
try
{
var mappingModel = DeserializeObject<MappingModel>(requestMessage);
DeserializeAndAddOrUpdateMapping(mappingModel);
guid = DeserializeAndAddOrUpdateMapping(mappingModel);
}
catch (ArgumentException a)
{
_logger.Error("HttpStatusCode set to 400 {0}", a);
return new ResponseMessage { StatusCode = 400, Body = a.Message };
return ResponseMessageBuilder.Create(a.Message, 400);
}
catch (Exception e)
{
_logger.Error("HttpStatusCode set to 500 {0}", e);
return new ResponseMessage { StatusCode = 500, Body = e.ToString() };
return ResponseMessageBuilder.Create(e.ToString(), 500);
}
return new ResponseMessage { StatusCode = 201, Body = "Mapping added" };
return ResponseMessageBuilder.Create("Mapping added", 201, guid);
}
private void DeserializeAndAddOrUpdateMapping(MappingModel mappingModel, Guid? guid = null, string path = null)
private Guid DeserializeAndAddOrUpdateMapping(MappingModel mappingModel, Guid? guid = null, string path = null)
{
Check.NotNull(mappingModel, nameof(mappingModel));
Check.NotNull(mappingModel.Request, nameof(mappingModel.Request));
@@ -402,7 +403,7 @@ namespace WireMock.Server
var requestBuilder = InitRequestBuilder(mappingModel.Request);
var responseBuilder = InitResponseBuilder(mappingModel.Response);
IRespondWithAProvider respondProvider = Given(requestBuilder);
var respondProvider = Given(requestBuilder);
if (guid != null)
{
@@ -436,6 +437,8 @@ namespace WireMock.Server
}
respondProvider.RespondWith(responseBuilder);
return respondProvider.Guid;
}
private ResponseMessage MappingsDelete(RequestMessage requestMessage)
@@ -444,7 +447,7 @@ namespace WireMock.Server
ResetScenarios();
return new ResponseMessage { Body = "Mappings deleted" };
return ResponseMessageBuilder.Create("Mappings deleted");
}
#endregion Mappings
@@ -457,7 +460,7 @@ namespace WireMock.Server
if (entry == null)
{
_logger.Warn("HttpStatusCode set to 404 : Request not found");
return new ResponseMessage { StatusCode = 404, Body = "Request not found" };
return ResponseMessageBuilder.Create("Request not found", 404);
}
var model = LogEntryMapper.Map(entry);
@@ -470,9 +473,11 @@ namespace WireMock.Server
Guid guid = Guid.Parse(requestMessage.Path.Substring(AdminRequests.Length + 1));
if (DeleteLogEntry(guid))
return new ResponseMessage { Body = "Request removed" };
{
return ResponseMessageBuilder.Create("Request removed");
}
return new ResponseMessage { Body = "Request not found" };
return ResponseMessageBuilder.Create("Request not found", 404);
}
#endregion Request/{guid}
@@ -490,7 +495,7 @@ namespace WireMock.Server
{
ResetLogEntries();
return new ResponseMessage { Body = "Requests deleted" };
return ResponseMessageBuilder.Create("Requests deleted");
}
#endregion Requests
@@ -533,7 +538,7 @@ namespace WireMock.Server
{
ResetScenarios();
return new ResponseMessage { Body = "Scenarios reset" };
return ResponseMessageBuilder.Create("Scenarios reset");
}
#endregion
@@ -612,9 +617,9 @@ namespace WireMock.Server
if (requestModel.Params != null)
{
foreach (var paramModel in requestModel.Params)
foreach (var paramModel in requestModel.Params.Where(c => c.Matchers != null))
{
requestBuilder = paramModel.Values == null ? requestBuilder.WithParam(paramModel.Name) : requestBuilder.WithParam(paramModel.Name, paramModel.Values.ToArray());
requestBuilder = requestBuilder.WithParam(paramModel.Name, paramModel.Matchers.Select(MatcherMapper.Map).Cast<IStringMatcher>().ToArray());
}
}

View File

@@ -264,7 +264,7 @@ namespace WireMock.Server
Given(Request.Create().WithPath("/*").UsingAnyMethod())
.WithGuid(Guid.Parse("90008000-0000-4444-a17e-669cd84f1f05"))
.AtPriority(1000)
.RespondWith(new DynamicResponseProvider(request => new ResponseMessage { StatusCode = 404, Body = "No matching mapping found" }));
.RespondWith(new DynamicResponseProvider(request => ResponseMessageBuilder.Create("No matching mapping found", 404)));
}
/// <summary>

View File

@@ -8,6 +8,11 @@ namespace WireMock.Server
/// </summary>
public interface IRespondWithAProvider
{
/// <summary>
/// Gets the unique identifier for this mapping.
/// </summary>
Guid Guid { get; }
/// <summary>
/// Define a unique identifier for this mapping.
/// </summary>

View File

@@ -10,7 +10,6 @@ namespace WireMock.Server
internal class RespondWithAProvider : IRespondWithAProvider
{
private int _priority;
private Guid? _guid;
private string _title;
private string _path;
private object _executionConditionState;
@@ -19,6 +18,8 @@ namespace WireMock.Server
private readonly RegistrationCallback _registrationCallback;
private readonly IRequestMatcher _requestMatcher;
public Guid Guid { get; private set; } = Guid.NewGuid();
/// <summary>
/// Initializes a new instance of the <see cref="RespondWithAProvider"/> class.
/// </summary>
@@ -36,8 +37,7 @@ namespace WireMock.Server
/// <param name="provider">The provider.</param>
public void RespondWith(IResponseProvider provider)
{
var mappingGuid = _guid ?? Guid.NewGuid();
_registrationCallback(new Mapping(mappingGuid, _title, _path, _requestMatcher, provider, _priority, _scenario, _executionConditionState, _nextState));
_registrationCallback(new Mapping(Guid, _title, _path, _requestMatcher, provider, _priority, _scenario, _executionConditionState, _nextState));
}
/// <see cref="IRespondWithAProvider.WithGuid(string)"/>
@@ -49,7 +49,7 @@ namespace WireMock.Server
/// <see cref="IRespondWithAProvider.WithGuid(Guid)"/>
public IRespondWithAProvider WithGuid(Guid guid)
{
_guid = guid;
Guid = guid;
return this;
}

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.4.2</Version>
<Version>1.0.4.4</Version>
<Authors>Stef Heyenrath</Authors>
<TargetFrameworks>net452;net46;netstandard1.3;netstandard2.0</TargetFrameworks>
<GenerateDocumentationFile>true</GenerateDocumentationFile>

View File

@@ -33,10 +33,12 @@ namespace WireMock.Net.Tests
Priority = 500,
Title = "test"
};
string result = await api.PostMappingAsync(model);
var result = await api.PostMappingAsync(model);
// Assert
Check.That(result).IsNotNull();
Check.That(result.Status).IsNotNull();
Check.That(result.Guid).IsNotNull();
var mapping = server.Mappings.Single(m => m.Priority == 500);
Check.That(mapping).IsNotNull();

View File

@@ -9,7 +9,7 @@ namespace WireMock.Net.Tests.RequestMatchers
public class RequestMessageParamMatcherTests
{
[Fact]
public void RequestMessageParamMatcher_GetMatchingScore_AllMatch()
public void RequestMessageParamMatcher_GetMatchingScore_KeyWithValuesPresentInUrl_MatchExactOnStringValues()
{
// Assign
var requestMessage = new RequestMessage(new Uri("http://localhost?key=test1,test2"), "GET", "127.0.0.1");
@@ -24,7 +24,22 @@ namespace WireMock.Net.Tests.RequestMatchers
}
[Fact]
public void RequestMessageParamMatcher_GetMatchingScore_PartialMatch()
public void RequestMessageParamMatcher_GetMatchingScore_KeyWithValuesPresentInUrl_MatchExactOnExactMatchers()
{
// Assign
var requestMessage = new RequestMessage(new Uri("http://localhost?key=test1,test2"), "GET", "127.0.0.1");
var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "key", new IStringMatcher[] { new ExactMatcher("test1"), new ExactMatcher("test2") });
// Act
var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result);
// Assert
Check.That(score).IsEqualTo(1.0d);
}
[Fact]
public void RequestMessageParamMatcher_GetMatchingScore_KeyWithValuesPresentInUrl_MatchOnKeyWithValues_PartialMatch()
{
// Assign
var requestMessage = new RequestMessage(new Uri("http://localhost?key=test0,test2"), "GET", "127.0.0.1");
@@ -39,7 +54,7 @@ namespace WireMock.Net.Tests.RequestMatchers
}
[Fact]
public void RequestMessageParamMatcher_GetMatchingScore_OnlyKeyPresent()
public void RequestMessageParamMatcher_GetMatchingScore_OnlyKeyPresentInUrl_MatchOnKeyWithValues_Fails()
{
// Assign
var requestMessage = new RequestMessage(new Uri("http://localhost?key"), "GET", "127.0.0.1");
@@ -54,7 +69,7 @@ namespace WireMock.Net.Tests.RequestMatchers
}
[Fact]
public void RequestMessageParamMatcher_GetMatchingScore_OnlyKeyPresent_WithNull()
public void RequestMessageParamMatcher_GetMatchingScore_OnlyKeyPresentInUrl_MatchOnKey()
{
// Assign
var requestMessage = new RequestMessage(new Uri("http://localhost?key"), "GET", "127.0.0.1");
@@ -69,7 +84,7 @@ namespace WireMock.Net.Tests.RequestMatchers
}
[Fact]
public void RequestMessageParamMatcher_GetMatchingScore_OnlyKeyPresent_WithEmptyArray()
public void RequestMessageParamMatcher_GetMatchingScore_OnlyKeyPresentInUrl_MatchOnKeyWithEmptyArray()
{
// Assign
var requestMessage = new RequestMessage(new Uri("http://localhost?key"), "GET", "127.0.0.1");
@@ -82,5 +97,20 @@ namespace WireMock.Net.Tests.RequestMatchers
// Assert
Check.That(score).IsEqualTo(1.0d);
}
[Fact]
public void RequestMessageParamMatcher_GetMatchingScore_KeyWithValuePresentInUrl_MatchOnKey()
{
// Assign
var requestMessage = new RequestMessage(new Uri("http://localhost?key=frank@contoso.com"), "GET", "127.0.0.1");
var matcher = new RequestMessageParamMatcher(MatchBehaviour.AcceptOnMatch, "key");
// Act
var result = new RequestMatchResult();
double score = matcher.GetMatchingScore(requestMessage, result);
// Assert
Check.That(score).IsEqualTo(1.0d);
}
}
}