scenario and state

This commit is contained in:
Stef Heyenrath
2017-10-07 13:19:48 +02:00
parent ab017beaa6
commit 5424b1e2e2
10 changed files with 416 additions and 257 deletions

View File

@@ -1,124 +1,141 @@
using System;
using System.Threading.Tasks;
using JetBrains.Annotations;
using WireMock.Matchers.Request;
namespace WireMock
{
/// <summary>
/// The Mapping.
/// </summary>
public class Mapping
{
/// <summary>
/// Gets the unique identifier.
/// </summary>
/// <value>
/// The unique identifier.
/// </value>
public Guid Guid { get; }
/// <summary>
/// Gets the unique title.
/// </summary>
/// <value>
/// The unique title.
/// </value>
public string Title { get; }
/// <summary>
/// Gets the priority.
/// </summary>
/// <value>
/// The priority.
/// </value>
public int Priority { get; }
using System;
using System.Threading.Tasks;
using JetBrains.Annotations;
using WireMock.Matchers.Request;
namespace WireMock
{
/// <summary>
/// The Mapping.
/// </summary>
public class Mapping
{
/// <summary>
/// Execution state condition for the current mapping.
/// </summary>
public object ExecutionConditionState { get; }
/// Gets the unique identifier.
/// </summary>
/// <value>
/// The unique identifier.
/// </value>
public Guid Guid { get; }
/// <summary>
/// The next state which will be signaled after the current mapping execution.
/// Gets the unique title.
/// </summary>
/// <value>
/// The unique title.
/// </value>
public string Title { get; }
/// <summary>
/// Gets the priority.
/// </summary>
/// <value>
/// The priority.
/// </value>
public int Priority { get; }
/// <summary>
/// Scenario.
/// </summary>
[CanBeNull]
public string Scenario { get; }
/// <summary>
/// Execution state condition for the current mapping.
/// </summary>
[CanBeNull]
public object ExecutionConditionState { get; }
/// <summary>
/// The next state which will be signaled after the current mapping execution.
/// In case the value is null state will not be changed.
/// </summary>
public object NextState { get; }
/// <summary>
/// The Request matcher.
/// </summary>
public IRequestMatcher RequestMatcher { get; }
/// <summary>
/// The Provider.
/// </summary>
public IResponseProvider Provider { get; }
/// <summary>
/// Initializes a new instance of the <see cref="Mapping"/> class.
/// </summary>
/// <param name="guid">The unique identifier.</param>
/// <param name="title">The unique title (can be null_.</param>
/// <param name="requestMatcher">The request matcher.</param>
/// <param name="provider">The provider.</param>
/// <param name="priority">The priority for this mapping.</param>
public Mapping(Guid guid, [CanBeNull] string title, IRequestMatcher requestMatcher, IResponseProvider provider, int priority)
: this(guid, title, requestMatcher, provider, priority, null, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Mapping"/> class.
/// </summary>
/// <param name="guid">The unique identifier.</param>
/// <param name="title">The unique title (can be null_.</param>
/// <param name="requestMatcher">The request matcher.</param>
/// <param name="provider">The provider.</param>
/// </summary>
[CanBeNull]
public object NextState { get; }
/// <summary>
/// The Request matcher.
/// </summary>
public IRequestMatcher RequestMatcher { get; }
/// <summary>
/// The Provider.
/// </summary>
public IResponseProvider Provider { get; }
/// <summary>
/// Is State started ?
/// </summary>
public bool IsStartState => Scenario == null || Scenario != null && NextState != null && ExecutionConditionState == null;
/// <summary>
/// Initializes a new instance of the <see cref="Mapping"/> class.
/// </summary>
/// <param name="guid">The unique identifier.</param>
/// <param name="title">The unique title (can be null_.</param>
/// <param name="requestMatcher">The request matcher.</param>
/// <param name="provider">The provider.</param>
/// <param name="priority">The priority for this mapping.</param>
/// <param name="executionConditionState">State in which the current mapping can occur. Happens if not null</param>
/// <param name="nextState">The next state which will occur after the current mapping execution. Happens if not null</param>
public Mapping(Guid guid, [CanBeNull] string title, IRequestMatcher requestMatcher, IResponseProvider provider, int priority, object executionConditionState, object nextState)
{
Priority = priority;
ExecutionConditionState = executionConditionState;
NextState = nextState;
Guid = guid;
Title = title;
RequestMatcher = requestMatcher;
Provider = provider;
}
/// <summary>
/// The response to.
/// </summary>
/// <param name="requestMessage">The request message.</param>
/// <returns>The <see cref="ResponseMessage"/>.</returns>
public async Task<ResponseMessage> ResponseToAsync(RequestMessage requestMessage)
{
return await Provider.ProvideResponseAsync(requestMessage);
}
/// <summary>
/// Determines whether the RequestMessage is handled.
/// </summary>
/// <param name="requestMessage">The request message.</param>
/// <returns>The <see cref="RequestMatchResult"/>.</returns>
public RequestMatchResult IsRequestHandled(RequestMessage requestMessage)
{
var result = new RequestMatchResult();
RequestMatcher.GetMatchingScore(requestMessage, result);
return result;
}
/// <summary>
/// Gets a value indicating whether this mapping is an Admin Interface.
/// </summary>
/// <value>
/// <c>true</c> if this mapping is an Admin Interface; otherwise, <c>false</c>.
/// </value>
public bool IsAdminInterface => Provider is DynamicResponseProvider || Provider is DynamicAsyncResponseProvider || Provider is ProxyAsyncResponseProvider;
}
/// <param name="scenario">The scenario. [Optional]</param>
/// <param name="executionConditionState">State in which the current mapping can occur. [Optional]</param>
/// <param name="nextState">The next state which will occur after the current mapping execution. [Optional]</param>
public Mapping(Guid guid, [CanBeNull] string title, IRequestMatcher requestMatcher, IResponseProvider provider, int priority, [CanBeNull] string scenario, [CanBeNull] object executionConditionState, [CanBeNull] object nextState)
{
Guid = guid;
Title = title;
RequestMatcher = requestMatcher;
Provider = provider;
Priority = priority;
Scenario = scenario;
ExecutionConditionState = executionConditionState;
NextState = nextState;
}
/// <summary>
/// The response to.
/// </summary>
/// <param name="requestMessage">The request message.</param>
/// <returns>The <see cref="ResponseMessage"/>.</returns>
public async Task<ResponseMessage> ResponseToAsync(RequestMessage requestMessage)
{
return await Provider.ProvideResponseAsync(requestMessage);
}
/// <summary>
/// Gets the RequestMatchResult based on the RequestMessage.
/// </summary>
/// <param name="requestMessage">The request message.</param>
/// <param name="nextState">The Next State.</param>
/// <returns>The <see cref="RequestMatchResult"/>.</returns>
public RequestMatchResult GetRequestMatchResult(RequestMessage requestMessage, [CanBeNull] object nextState)
{
var result = new RequestMatchResult();
RequestMatcher.GetMatchingScore(requestMessage, result);
// Only check state if Scenario is defined
if (Scenario != null)
{
var matcher = new RequestMessageScenarioAndStateMatcher(nextState, ExecutionConditionState);
matcher.GetMatchingScore(requestMessage, result);
//// If ExecutionConditionState is null, this means that request is the start from a scenario. So just return.
//if (ExecutionConditionState != null)
//{
// // ExecutionConditionState is not null, so get score for matching with the nextState.
// var matcher = new RequestMessageScenarioAndStateMatcher(nextState, ExecutionConditionState);
// matcher.GetMatchingScore(requestMessage, result);
//}
}
return result;
}
/// <summary>
/// Gets a value indicating whether this mapping is an Admin Interface.
/// </summary>
/// <value>
/// <c>true</c> if this mapping is an Admin Interface; otherwise, <c>false</c>.
/// </value>
public bool IsAdminInterface => Provider is DynamicResponseProvider || Provider is DynamicAsyncResponseProvider || Provider is ProxyAsyncResponseProvider;
}
}

View File

@@ -43,7 +43,7 @@ namespace WireMock.Matchers.Request
/// <summary>
/// Gets the match details.
/// </summary>
public IList<KeyValuePair<Type, double>> MatchDetails { get; private set; }
public IList<KeyValuePair<Type, double>> MatchDetails { get; }
/// <summary>
/// Initializes a new instance of the <see cref="RequestMatchResult"/> class.
@@ -72,7 +72,6 @@ namespace WireMock.Matchers.Request
/// <returns>
/// A value that indicates the relative order of the objects being compared. The return value has these meanings: Value Meaning Less than zero This instance precedes <paramref name="obj" /> in the sort order. Zero This instance occurs in the same position in the sort order as <paramref name="obj" />. Greater than zero This instance follows <paramref name="obj" /> in the sort order.
/// </returns>
/// <exception cref="System.NotImplementedException"></exception>
public int CompareTo(object obj)
{
var compareObj = (RequestMatchResult)obj;

View File

@@ -0,0 +1,51 @@
using JetBrains.Annotations;
namespace WireMock.Matchers.Request
{
/// <summary>
/// The scenario and state matcher.
/// </summary>
public class RequestMessageScenarioAndStateMatcher : IRequestMatcher
{
///// <summary>
///// Scenario.
///// </summary>
//[CanBeNull] private string _scenario;
/// <summary>
/// Execution state condition for the current mapping.
/// </summary>
[CanBeNull]
private readonly object _executionConditionState;
/// <summary>
/// The next state which will be signaled after the current mapping execution.
/// In case the value is null state will not be changed.
/// </summary>
[CanBeNull]
private readonly object _nextState;
/// <summary>
/// Initializes a new instance of the <see cref="RequestMessageScenarioAndStateMatcher"/> class.
/// </summary>
/// <param name="nextState">The next state.</param>
/// <param name="executionConditionState">Execution state condition for the current mapping.</param>
public RequestMessageScenarioAndStateMatcher([CanBeNull] object nextState, [CanBeNull] object executionConditionState)
{
_nextState = nextState;
_executionConditionState = executionConditionState;
}
/// <inheritdoc />
public double GetMatchingScore(RequestMessage requestMessage, RequestMatchResult requestMatchResult)
{
double score = IsMatch();
return requestMatchResult.AddScore(GetType(), score);
}
private double IsMatch()
{
return Equals(_executionConditionState, _nextState) ? MatchScores.Perfect : MatchScores.Mismatch;
}
}
}

View File

@@ -1,5 +1,4 @@
using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace WireMock.Owin

View File

@@ -1,9 +1,12 @@
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading.Tasks;
using WireMock.Logging;
using WireMock.Matchers.Request;
using System.Linq;
using WireMock.Matchers;
#if !NETSTANDARD
using Microsoft.Owin;
#else
@@ -24,19 +27,17 @@ namespace WireMock.Owin
private readonly OwinRequestMapper _requestMapper = new OwinRequestMapper();
private readonly OwinResponseMapper _responseMapper = new OwinResponseMapper();
public object State { get; private set; }
private readonly IDictionary<string, object> _states = new ConcurrentDictionary<string, object>();
#if !NETSTANDARD
public WireMockMiddleware(OwinMiddleware next, WireMockMiddlewareOptions options) : base(next)
{
_options = options;
State = null;
}
#else
public WireMockMiddleware(RequestDelegate next, WireMockMiddlewareOptions options)
{
_options = options;
State = null;
}
#endif
@@ -54,12 +55,20 @@ namespace WireMock.Owin
RequestMatchResult requestMatchResult = null;
try
{
foreach (var mapping in _options.Mappings.Where(m => m.Scenario != null))
{
// Set start
if (!_states.ContainsKey(mapping.Scenario) && mapping.IsStartState)
{
_states.Add(mapping.Scenario, null);
}
}
var mappings = _options.Mappings
.Where(m => object.Equals(m.ExecutionConditionState, State))
.Select(m => new
{
Mapping = m,
MatchResult = m.IsRequestHandled(request)
MatchResult = m.GetRequestMatchResult(request, m.Scenario != null && _states.ContainsKey(m.Scenario) ? _states[m.Scenario] : null)
})
.ToList();
@@ -92,14 +101,13 @@ namespace WireMock.Owin
response = new ResponseMessage { StatusCode = 404, Body = "No matching mapping found" };
return;
}
logRequest = !targetMapping.IsAdminInterface;
if (targetMapping.IsAdminInterface && _options.AuthorizationMatcher != null)
{
string authorization;
bool present = request.Headers.TryGetValue("Authorization", out authorization);
if (!present || _options.AuthorizationMatcher.IsMatch(authorization) < 1.0)
bool present = request.Headers.TryGetValue("Authorization", out var authorization);
if (!present || _options.AuthorizationMatcher.IsMatch(authorization) < MatchScores.Perfect)
{
response = new ResponseMessage { StatusCode = 401 };
return;
@@ -112,7 +120,11 @@ namespace WireMock.Owin
}
response = await targetMapping.ResponseToAsync(request);
State = targetMapping.NextState;
if (targetMapping.Scenario != null)
{
_states[targetMapping.Scenario] = targetMapping.NextState;
}
}
catch (Exception ex)
{

View File

@@ -69,9 +69,8 @@ namespace WireMock.Server
Check.NotNull(filename, nameof(filename));
string filenameWithoutExtension = Path.GetFileNameWithoutExtension(filename);
Guid guidFromFilename;
if (Guid.TryParse(filenameWithoutExtension, out guidFromFilename))
if (Guid.TryParse(filenameWithoutExtension, out var guidFromFilename))
{
DeserializeAndAddMapping(File.ReadAllText(filename), guidFromFilename);
}
@@ -151,7 +150,7 @@ namespace WireMock.Server
var response = (Response)Response.Create(responseMessage);
return new Mapping(Guid.NewGuid(), string.Empty, request, response, 0);
return new Mapping(Guid.NewGuid(), string.Empty, request, response, 0, null, null, null);
}
#endregion

View File

@@ -1,58 +1,65 @@
using System;
namespace WireMock.Server
{
/// <summary>
/// IRespondWithAProvider
/// </summary>
public interface IRespondWithAProvider
{
/// <summary>
/// Define a unique identifier for this mapping.
/// </summary>
/// <param name="guid">The unique identifier.</param>
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
IRespondWithAProvider WithGuid(Guid guid);
/// <summary>
/// Define a unique title for this mapping.
/// </summary>
/// <param name="title">The unique title.</param>
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
IRespondWithAProvider WithTitle(string title);
/// <summary>
/// Define a unique identifier for this mapping.
/// </summary>
/// <param name="guid">The unique identifier.</param>
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
IRespondWithAProvider WithGuid(string guid);
/// <summary>
/// Define the priority for this mapping.
/// </summary>
/// <param name="priority">The priority.</param>
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
IRespondWithAProvider AtPriority(int priority);
/// <summary>
/// The respond with.
/// </summary>
/// <param name="provider">The provider.</param>
void RespondWith(IResponseProvider provider);
/// <summary>
/// Execute this respond only in case the current state is equal to specified one
/// </summary>
/// <param name="state">Any object which identifies the current state</param>
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
IRespondWithAProvider WhenStateIs(object state);
using System;
namespace WireMock.Server
{
/// <summary>
/// IRespondWithAProvider
/// </summary>
public interface IRespondWithAProvider
{
/// <summary>
/// Once this mapping is executed the state will be changed to specified one
/// Define a unique identifier for this mapping.
/// </summary>
/// <param name="guid">The unique identifier.</param>
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
IRespondWithAProvider WithGuid(Guid guid);
/// <summary>
/// Define a unique title for this mapping.
/// </summary>
/// <param name="title">The unique title.</param>
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
IRespondWithAProvider WithTitle(string title);
/// <summary>
/// Define a unique identifier for this mapping.
/// </summary>
/// <param name="guid">The unique identifier.</param>
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
IRespondWithAProvider WithGuid(string guid);
/// <summary>
/// Define the priority for this mapping.
/// </summary>
/// <param name="priority">The priority.</param>
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
IRespondWithAProvider AtPriority(int priority);
/// <summary>
/// The respond with.
/// </summary>
/// <param name="provider">The provider.</param>
void RespondWith(IResponseProvider provider);
/// <summary>
/// Sets the the scenario.
/// </summary>
/// <param name="scenario">The scenario.</param>
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
IRespondWithAProvider InScenario(string scenario);
/// <summary>
/// Execute this respond only in case the current state is equal to specified one.
/// </summary>
/// <param name="state">Any object which identifies the current state</param>
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
IRespondWithAProvider WhenStateIs(object state);
/// <summary>
/// Once this mapping is executed the state will be changed to specified one.
/// </summary>
/// <param name="state">Any object which identifies the new state</param>
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
IRespondWithAProvider WillSetStateTo(object state);
}
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
IRespondWithAProvider WillSetStateTo(object state);
}
}

View File

@@ -11,9 +11,9 @@ namespace WireMock.Server
private int _priority;
private Guid? _guid;
private string _title;
private object _executionConditionState = null;
private object _nextState = null;
private object _executionConditionState;
private object _nextState;
private string _scenario;
/// <summary>
/// The _registration callback.
@@ -45,19 +45,7 @@ namespace WireMock.Server
public void RespondWith(IResponseProvider provider)
{
var mappingGuid = _guid ?? Guid.NewGuid();
_registrationCallback(new Mapping(mappingGuid, _title, _requestMatcher, provider, _priority, _executionConditionState, _nextState));
}
public IRespondWithAProvider WhenStateIs(object state)
{
_executionConditionState = state;
return this;
}
public IRespondWithAProvider WillSetStateTo(object state)
{
_nextState = state;
return this;
_registrationCallback(new Mapping(mappingGuid, _title, _requestMatcher, provider, _priority, _scenario, _executionConditionState, _nextState));
}
/// <summary>
@@ -105,5 +93,41 @@ namespace WireMock.Server
return this;
}
public IRespondWithAProvider InScenario(string scenario)
{
_scenario = scenario;
return this;
}
public IRespondWithAProvider WhenStateIs(object state)
{
if (string.IsNullOrEmpty(_scenario))
{
throw new NotSupportedException("Unable to set state condition when no scenario is defined.");
}
//if (_nextState != null)
//{
// throw new NotSupportedException("Unable to set state condition when next state is defined.");
//}
_executionConditionState = state;
return this;
}
public IRespondWithAProvider WillSetStateTo(object state)
{
if (string.IsNullOrEmpty(_scenario))
{
throw new NotSupportedException("Unable to set next state when no scenario is defined.");
}
_nextState = state;
return this;
}
}
}