mirror of
https://github.com/wiremock/WireMock.Net.git
synced 2026-05-13 11:21:02 +02:00
Merge branch 'stateful-behavior'
This commit is contained in:
@@ -27,7 +27,7 @@ namespace WireMock.Net.ConsoleApplication
|
|||||||
|
|
||||||
server.SetBasicAuthentication("a", "b");
|
server.SetBasicAuthentication("a", "b");
|
||||||
|
|
||||||
server.AllowPartialMapping();
|
// server.AllowPartialMapping();
|
||||||
|
|
||||||
server
|
server
|
||||||
.Given(Request.Create().WithPath("/oauth2/access").UsingPost().WithBody("grant_type=password;username=u;password=p"))
|
.Given(Request.Create().WithPath("/oauth2/access").UsingPost().WithBody("grant_type=password;username=u;password=p"))
|
||||||
@@ -95,19 +95,55 @@ namespace WireMock.Net.ConsoleApplication
|
|||||||
.Given(Request.Create().WithPath("/partial").UsingPost().WithBody(new SimMetricsMatcher(new[] { "cat", "dog" })))
|
.Given(Request.Create().WithPath("/partial").UsingPost().WithBody(new SimMetricsMatcher(new[] { "cat", "dog" })))
|
||||||
.RespondWith(Response.Create().WithStatusCode(200).WithBody("partial = 200"));
|
.RespondWith(Response.Create().WithStatusCode(200).WithBody("partial = 200"));
|
||||||
|
|
||||||
http://localhost:8080/any/any?start=1000&stop=1&stop=2
|
// 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
|
server
|
||||||
.Given(Request.Create().WithPath("/*").UsingGet())
|
.Given(Request.Create()
|
||||||
.WithGuid("90356dba-b36c-469a-a17e-669cd84f1f05")
|
.WithPath("/state1")
|
||||||
.AtPriority(server.Mappings.Count() + 1)
|
.UsingGet())
|
||||||
|
.InScenario("s1")
|
||||||
|
.WillSetStateTo("Test state 1")
|
||||||
.RespondWith(Response.Create()
|
.RespondWith(Response.Create()
|
||||||
.WithStatusCode(200)
|
.WithBody("No state msg 1"));
|
||||||
.WithHeader("Content-Type", "application/json")
|
|
||||||
.WithHeader("Transformed-Postman-Token", "token is {{request.headers.Postman-Token}}")
|
server
|
||||||
.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]}}"" }")
|
.Given(Request.Create()
|
||||||
.WithTransformer()
|
.WithPath("/foostate1")
|
||||||
.WithDelay(TimeSpan.FromMilliseconds(100))
|
.UsingGet())
|
||||||
);
|
.InScenario("s1")
|
||||||
|
.WhenStateIs("Test state 1")
|
||||||
|
.RespondWith(Response.Create()
|
||||||
|
.WithBody("Test state msg 1"));
|
||||||
|
|
||||||
|
server
|
||||||
|
.Given(Request.Create()
|
||||||
|
.WithPath("/state2")
|
||||||
|
.UsingGet())
|
||||||
|
.InScenario("s2")
|
||||||
|
.WillSetStateTo("Test state 2")
|
||||||
|
.RespondWith(Response.Create()
|
||||||
|
.WithBody("No state msg 2"));
|
||||||
|
|
||||||
|
server
|
||||||
|
.Given(Request.Create()
|
||||||
|
.WithPath("/foostate2")
|
||||||
|
.UsingGet())
|
||||||
|
.InScenario("s2")
|
||||||
|
.WhenStateIs("Test state 2")
|
||||||
|
.RespondWith(Response.Create()
|
||||||
|
.WithBody("Test state msg 2"));
|
||||||
|
|
||||||
System.Console.WriteLine("Press any key to stop the server");
|
System.Console.WriteLine("Press any key to stop the server");
|
||||||
System.Console.ReadKey();
|
System.Console.ReadKey();
|
||||||
@@ -121,4 +157,4 @@ namespace WireMock.Net.ConsoleApplication
|
|||||||
System.Console.ReadKey();
|
System.Console.ReadKey();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -31,6 +31,22 @@ namespace WireMock.Admin.Mappings
|
|||||||
/// </value>
|
/// </value>
|
||||||
public int? Priority { get; set; }
|
public int? Priority { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Scenario.
|
||||||
|
/// </summary>
|
||||||
|
public string Scenario { get; set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Execution state condition for the current mapping.
|
||||||
|
/// </summary>
|
||||||
|
public object WhenStateIs { get; set; }
|
||||||
|
|
||||||
|
/// <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 SetStateTo { get; set; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets or sets the request.
|
/// Gets or sets the request.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
|||||||
@@ -1,96 +1,141 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using JetBrains.Annotations;
|
using JetBrains.Annotations;
|
||||||
using WireMock.Matchers.Request;
|
using WireMock.Matchers.Request;
|
||||||
|
|
||||||
namespace WireMock
|
namespace WireMock
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The Mapping.
|
/// The Mapping.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public class Mapping
|
public class Mapping
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets the unique identifier.
|
/// Gets the unique identifier.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <value>
|
/// <value>
|
||||||
/// The unique identifier.
|
/// The unique identifier.
|
||||||
/// </value>
|
/// </value>
|
||||||
public Guid Guid { get; }
|
public Guid Guid { get; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets the unique title.
|
/// Gets the unique title.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <value>
|
/// <value>
|
||||||
/// The unique title.
|
/// The unique title.
|
||||||
/// </value>
|
/// </value>
|
||||||
public string Title { get; }
|
public string Title { get; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets the priority.
|
/// Gets the priority.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <value>
|
/// <value>
|
||||||
/// The priority.
|
/// The priority.
|
||||||
/// </value>
|
/// </value>
|
||||||
public int Priority { get; }
|
public int Priority { get; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The Request matcher.
|
/// Scenario.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public IRequestMatcher RequestMatcher { get; }
|
[CanBeNull]
|
||||||
|
public string Scenario { get; }
|
||||||
/// <summary>
|
|
||||||
/// The Provider.
|
/// <summary>
|
||||||
/// </summary>
|
/// Execution state condition for the current mapping.
|
||||||
public IResponseProvider Provider { get; }
|
/// </summary>
|
||||||
|
[CanBeNull]
|
||||||
/// <summary>
|
public object ExecutionConditionState { get; }
|
||||||
/// Initializes a new instance of the <see cref="Mapping"/> class.
|
|
||||||
/// </summary>
|
/// <summary>
|
||||||
/// <param name="guid">The unique identifier.</param>
|
/// The next state which will be signaled after the current mapping execution.
|
||||||
/// <param name="title">The unique title (can be null_.</param>
|
/// In case the value is null state will not be changed.
|
||||||
/// <param name="requestMatcher">The request matcher.</param>
|
/// </summary>
|
||||||
/// <param name="provider">The provider.</param>
|
[CanBeNull]
|
||||||
/// <param name="priority">The priority for this mapping.</param>
|
public object NextState { get; }
|
||||||
public Mapping(Guid guid, [CanBeNull] string title, IRequestMatcher requestMatcher, IResponseProvider provider, int priority)
|
|
||||||
{
|
/// <summary>
|
||||||
Priority = priority;
|
/// The Request matcher.
|
||||||
Guid = guid;
|
/// </summary>
|
||||||
Title = title;
|
public IRequestMatcher RequestMatcher { get; }
|
||||||
RequestMatcher = requestMatcher;
|
|
||||||
Provider = provider;
|
/// <summary>
|
||||||
}
|
/// The Provider.
|
||||||
|
/// </summary>
|
||||||
/// <summary>
|
public IResponseProvider Provider { get; }
|
||||||
/// The response to.
|
|
||||||
/// </summary>
|
/// <summary>
|
||||||
/// <param name="requestMessage">The request message.</param>
|
/// Is State started ?
|
||||||
/// <returns>The <see cref="ResponseMessage"/>.</returns>
|
/// </summary>
|
||||||
public async Task<ResponseMessage> ResponseToAsync(RequestMessage requestMessage)
|
public bool IsStartState => Scenario == null || Scenario != null && NextState != null && ExecutionConditionState == null;
|
||||||
{
|
|
||||||
return await Provider.ProvideResponseAsync(requestMessage);
|
/// <summary>
|
||||||
}
|
/// Initializes a new instance of the <see cref="Mapping"/> class.
|
||||||
|
/// </summary>
|
||||||
/// <summary>
|
/// <param name="guid">The unique identifier.</param>
|
||||||
/// Determines whether the RequestMessage is handled.
|
/// <param name="title">The unique title (can be null_.</param>
|
||||||
/// </summary>
|
/// <param name="requestMatcher">The request matcher.</param>
|
||||||
/// <param name="requestMessage">The request message.</param>
|
/// <param name="provider">The provider.</param>
|
||||||
/// <returns>The <see cref="RequestMatchResult"/>.</returns>
|
/// <param name="priority">The priority for this mapping.</param>
|
||||||
public RequestMatchResult IsRequestHandled(RequestMessage requestMessage)
|
/// <param name="scenario">The scenario. [Optional]</param>
|
||||||
{
|
/// <param name="executionConditionState">State in which the current mapping can occur. [Optional]</param>
|
||||||
var result = new RequestMatchResult();
|
/// <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)
|
||||||
RequestMatcher.GetMatchingScore(requestMessage, result);
|
{
|
||||||
|
Guid = guid;
|
||||||
return result;
|
Title = title;
|
||||||
}
|
RequestMatcher = requestMatcher;
|
||||||
|
Provider = provider;
|
||||||
/// <summary>
|
Priority = priority;
|
||||||
/// Gets a value indicating whether this mapping is an Admin Interface.
|
Scenario = scenario;
|
||||||
/// </summary>
|
ExecutionConditionState = executionConditionState;
|
||||||
/// <value>
|
NextState = nextState;
|
||||||
/// <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;
|
/// <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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -43,7 +43,7 @@ namespace WireMock.Matchers.Request
|
|||||||
/// <summary>
|
/// <summary>
|
||||||
/// Gets the match details.
|
/// Gets the match details.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public IList<KeyValuePair<Type, double>> MatchDetails { get; private set; }
|
public IList<KeyValuePair<Type, double>> MatchDetails { get; }
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Initializes a new instance of the <see cref="RequestMatchResult"/> class.
|
/// Initializes a new instance of the <see cref="RequestMatchResult"/> class.
|
||||||
@@ -72,7 +72,6 @@ namespace WireMock.Matchers.Request
|
|||||||
/// <returns>
|
/// <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.
|
/// 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>
|
/// </returns>
|
||||||
/// <exception cref="System.NotImplementedException"></exception>
|
|
||||||
public int CompareTo(object obj)
|
public int CompareTo(object obj)
|
||||||
{
|
{
|
||||||
var compareObj = (RequestMatchResult)obj;
|
var compareObj = (RequestMatchResult)obj;
|
||||||
|
|||||||
@@ -0,0 +1,51 @@
|
|||||||
|
using JetBrains.Annotations;
|
||||||
|
|
||||||
|
namespace WireMock.Matchers.Request
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// The scenario and state matcher.
|
||||||
|
/// </summary>
|
||||||
|
internal 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,4 @@
|
|||||||
using System;
|
using System.Collections.Generic;
|
||||||
using System.Collections.Generic;
|
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
namespace WireMock.Owin
|
namespace WireMock.Owin
|
||||||
|
|||||||
@@ -1,9 +1,12 @@
|
|||||||
using System;
|
using System;
|
||||||
using System.Collections;
|
using System.Collections;
|
||||||
|
using System.Collections.Concurrent;
|
||||||
|
using System.Collections.Generic;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
using WireMock.Logging;
|
using WireMock.Logging;
|
||||||
using WireMock.Matchers.Request;
|
using WireMock.Matchers.Request;
|
||||||
using System.Linq;
|
using System.Linq;
|
||||||
|
using WireMock.Matchers;
|
||||||
#if !NETSTANDARD
|
#if !NETSTANDARD
|
||||||
using Microsoft.Owin;
|
using Microsoft.Owin;
|
||||||
#else
|
#else
|
||||||
@@ -24,6 +27,8 @@ namespace WireMock.Owin
|
|||||||
private readonly OwinRequestMapper _requestMapper = new OwinRequestMapper();
|
private readonly OwinRequestMapper _requestMapper = new OwinRequestMapper();
|
||||||
private readonly OwinResponseMapper _responseMapper = new OwinResponseMapper();
|
private readonly OwinResponseMapper _responseMapper = new OwinResponseMapper();
|
||||||
|
|
||||||
|
private readonly IDictionary<string, object> _states = new ConcurrentDictionary<string, object>();
|
||||||
|
|
||||||
#if !NETSTANDARD
|
#if !NETSTANDARD
|
||||||
public WireMockMiddleware(OwinMiddleware next, WireMockMiddlewareOptions options) : base(next)
|
public WireMockMiddleware(OwinMiddleware next, WireMockMiddlewareOptions options) : base(next)
|
||||||
{
|
{
|
||||||
@@ -50,11 +55,20 @@ namespace WireMock.Owin
|
|||||||
RequestMatchResult requestMatchResult = null;
|
RequestMatchResult requestMatchResult = null;
|
||||||
try
|
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
|
var mappings = _options.Mappings
|
||||||
.Select(m => new
|
.Select(m => new
|
||||||
{
|
{
|
||||||
Mapping = m,
|
Mapping = m,
|
||||||
MatchResult = m.IsRequestHandled(request)
|
MatchResult = m.GetRequestMatchResult(request, m.Scenario != null && _states.ContainsKey(m.Scenario) ? _states[m.Scenario] : null)
|
||||||
})
|
})
|
||||||
.ToList();
|
.ToList();
|
||||||
|
|
||||||
@@ -87,14 +101,13 @@ namespace WireMock.Owin
|
|||||||
response = new ResponseMessage { StatusCode = 404, Body = "No matching mapping found" };
|
response = new ResponseMessage { StatusCode = 404, Body = "No matching mapping found" };
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
logRequest = !targetMapping.IsAdminInterface;
|
logRequest = !targetMapping.IsAdminInterface;
|
||||||
|
|
||||||
if (targetMapping.IsAdminInterface && _options.AuthorizationMatcher != null)
|
if (targetMapping.IsAdminInterface && _options.AuthorizationMatcher != null)
|
||||||
{
|
{
|
||||||
string authorization;
|
bool present = request.Headers.TryGetValue("Authorization", out var authorization);
|
||||||
bool present = request.Headers.TryGetValue("Authorization", out authorization);
|
if (!present || _options.AuthorizationMatcher.IsMatch(authorization) < MatchScores.Perfect)
|
||||||
if (!present || _options.AuthorizationMatcher.IsMatch(authorization) < 1.0)
|
|
||||||
{
|
{
|
||||||
response = new ResponseMessage { StatusCode = 401 };
|
response = new ResponseMessage { StatusCode = 401 };
|
||||||
return;
|
return;
|
||||||
@@ -107,6 +120,11 @@ namespace WireMock.Owin
|
|||||||
}
|
}
|
||||||
|
|
||||||
response = await targetMapping.ResponseToAsync(request);
|
response = await targetMapping.ResponseToAsync(request);
|
||||||
|
|
||||||
|
if (targetMapping.Scenario != null)
|
||||||
|
{
|
||||||
|
_states[targetMapping.Scenario] = targetMapping.NextState;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
using System.Runtime.CompilerServices;
|
using System.Runtime.CompilerServices;
|
||||||
|
|
||||||
[assembly: InternalsVisibleTo("WireMock.Net.StandAlone")]
|
[assembly: InternalsVisibleTo("WireMock.Net.StandAlone")]
|
||||||
|
[assembly: InternalsVisibleTo("WireMock.Net.Tests")]
|
||||||
@@ -32,6 +32,9 @@ namespace WireMock.Serialization
|
|||||||
Guid = mapping.Guid,
|
Guid = mapping.Guid,
|
||||||
Title = mapping.Title,
|
Title = mapping.Title,
|
||||||
Priority = mapping.Priority,
|
Priority = mapping.Priority,
|
||||||
|
Scenario = mapping.Scenario,
|
||||||
|
WhenStateIs = mapping.ExecutionConditionState,
|
||||||
|
SetStateTo = mapping.NextState,
|
||||||
Request = new RequestModel
|
Request = new RequestModel
|
||||||
{
|
{
|
||||||
ClientIP = clientIPMatchers != null && clientIPMatchers.Any() ? new ClientIPModel
|
ClientIP = clientIPMatchers != null && clientIPMatchers.Any() ? new ClientIPModel
|
||||||
|
|||||||
@@ -69,9 +69,8 @@ namespace WireMock.Server
|
|||||||
Check.NotNull(filename, nameof(filename));
|
Check.NotNull(filename, nameof(filename));
|
||||||
|
|
||||||
string filenameWithoutExtension = Path.GetFileNameWithoutExtension(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);
|
DeserializeAndAddMapping(File.ReadAllText(filename), guidFromFilename);
|
||||||
}
|
}
|
||||||
@@ -151,7 +150,7 @@ namespace WireMock.Server
|
|||||||
|
|
||||||
var response = (Response)Response.Create(responseMessage);
|
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
|
#endregion
|
||||||
|
|
||||||
@@ -323,6 +322,13 @@ namespace WireMock.Server
|
|||||||
if (mappingModel.Priority != null)
|
if (mappingModel.Priority != null)
|
||||||
respondProvider = respondProvider.AtPriority(mappingModel.Priority.Value);
|
respondProvider = respondProvider.AtPriority(mappingModel.Priority.Value);
|
||||||
|
|
||||||
|
if (mappingModel.Scenario != null)
|
||||||
|
{
|
||||||
|
respondProvider = respondProvider.InScenario(mappingModel.Scenario);
|
||||||
|
respondProvider = respondProvider.WhenStateIs(mappingModel.WhenStateIs);
|
||||||
|
respondProvider = respondProvider.WillSetStateTo(mappingModel.SetStateTo);
|
||||||
|
}
|
||||||
|
|
||||||
respondProvider.RespondWith(responseBuilder);
|
respondProvider.RespondWith(responseBuilder);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,44 +1,65 @@
|
|||||||
using System;
|
using System;
|
||||||
|
|
||||||
namespace WireMock.Server
|
namespace WireMock.Server
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// IRespondWithAProvider
|
/// IRespondWithAProvider
|
||||||
/// </summary>
|
/// </summary>
|
||||||
public interface IRespondWithAProvider
|
public interface IRespondWithAProvider
|
||||||
{
|
{
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Define a unique identifier for this mapping.
|
/// Define a unique identifier for this mapping.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="guid">The unique identifier.</param>
|
/// <param name="guid">The unique identifier.</param>
|
||||||
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
|
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
|
||||||
IRespondWithAProvider WithGuid(Guid guid);
|
IRespondWithAProvider WithGuid(Guid guid);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Define a unique title for this mapping.
|
/// Define a unique title for this mapping.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="title">The unique title.</param>
|
/// <param name="title">The unique title.</param>
|
||||||
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
|
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
|
||||||
IRespondWithAProvider WithTitle(string title);
|
IRespondWithAProvider WithTitle(string title);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Define a unique identifier for this mapping.
|
/// Define a unique identifier for this mapping.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="guid">The unique identifier.</param>
|
/// <param name="guid">The unique identifier.</param>
|
||||||
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
|
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
|
||||||
IRespondWithAProvider WithGuid(string guid);
|
IRespondWithAProvider WithGuid(string guid);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Define the priority for this mapping.
|
/// Define the priority for this mapping.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="priority">The priority.</param>
|
/// <param name="priority">The priority.</param>
|
||||||
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
|
/// <returns>The <see cref="IRespondWithAProvider"/>.</returns>
|
||||||
IRespondWithAProvider AtPriority(int priority);
|
IRespondWithAProvider AtPriority(int priority);
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The respond with.
|
/// The respond with.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="provider">The provider.</param>
|
/// <param name="provider">The provider.</param>
|
||||||
void RespondWith(IResponseProvider provider);
|
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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -11,6 +11,9 @@ namespace WireMock.Server
|
|||||||
private int _priority;
|
private int _priority;
|
||||||
private Guid? _guid;
|
private Guid? _guid;
|
||||||
private string _title;
|
private string _title;
|
||||||
|
private object _executionConditionState;
|
||||||
|
private object _nextState;
|
||||||
|
private string _scenario;
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// The _registration callback.
|
/// The _registration callback.
|
||||||
@@ -42,7 +45,7 @@ namespace WireMock.Server
|
|||||||
public void RespondWith(IResponseProvider provider)
|
public void RespondWith(IResponseProvider provider)
|
||||||
{
|
{
|
||||||
var mappingGuid = _guid ?? Guid.NewGuid();
|
var mappingGuid = _guid ?? Guid.NewGuid();
|
||||||
_registrationCallback(new Mapping(mappingGuid, _title, _requestMatcher, provider, _priority));
|
_registrationCallback(new Mapping(mappingGuid, _title, _requestMatcher, provider, _priority, _scenario, _executionConditionState, _nextState));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
@@ -90,5 +93,41 @@ namespace WireMock.Server
|
|||||||
|
|
||||||
return this;
|
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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -407,7 +407,7 @@ namespace WireMock.Net.Tests
|
|||||||
|
|
||||||
var requestLoggedB = _server.LogEntries.Last();
|
var requestLoggedB = _server.LogEntries.Last();
|
||||||
Check.That(requestLoggedB.RequestMessage.Path).EndsWith("/foo3");
|
Check.That(requestLoggedB.RequestMessage.Path).EndsWith("/foo3");
|
||||||
}
|
}
|
||||||
|
|
||||||
public void Dispose()
|
public void Dispose()
|
||||||
{
|
{
|
||||||
|
|||||||
133
test/WireMock.Net.Tests/StatefulBehaviorTests.cs
Normal file
133
test/WireMock.Net.Tests/StatefulBehaviorTests.cs
Normal file
@@ -0,0 +1,133 @@
|
|||||||
|
using System;
|
||||||
|
using System.Net;
|
||||||
|
using System.Net.Http;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using NFluent;
|
||||||
|
using WireMock.RequestBuilders;
|
||||||
|
using WireMock.ResponseBuilders;
|
||||||
|
using WireMock.Server;
|
||||||
|
using Xunit;
|
||||||
|
|
||||||
|
namespace WireMock.Net.Tests
|
||||||
|
{
|
||||||
|
public class StatefulBehaviorTests : IDisposable
|
||||||
|
{
|
||||||
|
private FluentMockServer _server;
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Should_skip_non_relevant_states()
|
||||||
|
{
|
||||||
|
// given
|
||||||
|
_server = FluentMockServer.Start();
|
||||||
|
|
||||||
|
_server
|
||||||
|
.Given(Request.Create()
|
||||||
|
.WithPath("/foo")
|
||||||
|
.UsingGet())
|
||||||
|
.InScenario("s")
|
||||||
|
.WhenStateIs("Test state")
|
||||||
|
.RespondWith(Response.Create());
|
||||||
|
|
||||||
|
// when
|
||||||
|
var response = await new HttpClient().GetAsync("http://localhost:" + _server.Ports[0] + "/foo");
|
||||||
|
|
||||||
|
// then
|
||||||
|
Check.That(response.StatusCode).IsEqualTo(HttpStatusCode.NotFound);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Should_process_request_if_equals_state_and_single_state_defined()
|
||||||
|
{
|
||||||
|
// given
|
||||||
|
_server = FluentMockServer.Start();
|
||||||
|
|
||||||
|
_server
|
||||||
|
.Given(Request.Create()
|
||||||
|
.WithPath("/foo")
|
||||||
|
.UsingGet())
|
||||||
|
.InScenario("s")
|
||||||
|
.WillSetStateTo("Test state")
|
||||||
|
.RespondWith(Response.Create()
|
||||||
|
.WithBody("No state msg"));
|
||||||
|
|
||||||
|
_server
|
||||||
|
.Given(Request.Create()
|
||||||
|
.WithPath("/foo")
|
||||||
|
.UsingGet())
|
||||||
|
.InScenario("s")
|
||||||
|
.WhenStateIs("Test state")
|
||||||
|
.RespondWith(Response.Create()
|
||||||
|
.WithBody("Test state msg"));
|
||||||
|
|
||||||
|
// when
|
||||||
|
var responseNoState = await new HttpClient().GetStringAsync("http://localhost:" + _server.Ports[0] + "/foo");
|
||||||
|
var responseWithState = await new HttpClient().GetStringAsync("http://localhost:" + _server.Ports[0] + "/foo");
|
||||||
|
|
||||||
|
// then
|
||||||
|
Check.That(responseNoState).Equals("No state msg");
|
||||||
|
Check.That(responseWithState).Equals("Test state msg");
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact]
|
||||||
|
public async Task Should_process_request_if_equals_state_and_multiple_state_defined()
|
||||||
|
{
|
||||||
|
// given
|
||||||
|
_server = FluentMockServer.Start();
|
||||||
|
|
||||||
|
_server
|
||||||
|
.Given(Request.Create()
|
||||||
|
.WithPath("/state1")
|
||||||
|
.UsingGet())
|
||||||
|
.InScenario("s1")
|
||||||
|
.WillSetStateTo("Test state 1")
|
||||||
|
.RespondWith(Response.Create()
|
||||||
|
.WithBody("No state msg 1"));
|
||||||
|
|
||||||
|
_server
|
||||||
|
.Given(Request.Create()
|
||||||
|
.WithPath("/foo")
|
||||||
|
.UsingGet())
|
||||||
|
.InScenario("s1")
|
||||||
|
.WhenStateIs("Test state 1")
|
||||||
|
.RespondWith(Response.Create()
|
||||||
|
.WithBody("Test state msg 1"));
|
||||||
|
|
||||||
|
_server
|
||||||
|
.Given(Request.Create()
|
||||||
|
.WithPath("/state2")
|
||||||
|
.UsingGet())
|
||||||
|
.InScenario("s2")
|
||||||
|
.WillSetStateTo("Test state 2")
|
||||||
|
.RespondWith(Response.Create()
|
||||||
|
.WithBody("No state msg 2"));
|
||||||
|
|
||||||
|
_server
|
||||||
|
.Given(Request.Create()
|
||||||
|
.WithPath("/foo")
|
||||||
|
.UsingGet())
|
||||||
|
.InScenario("s2")
|
||||||
|
.WhenStateIs("Test state 2")
|
||||||
|
.RespondWith(Response.Create()
|
||||||
|
.WithBody("Test state msg 2"));
|
||||||
|
|
||||||
|
// when
|
||||||
|
string url = "http://localhost:" + _server.Ports[0];
|
||||||
|
var responseNoState1 = await new HttpClient().GetStringAsync(url + "/state1");
|
||||||
|
var responseNoState2 = await new HttpClient().GetStringAsync(url + "/state2");
|
||||||
|
|
||||||
|
var responseWithState1 = await new HttpClient().GetStringAsync(url + "/foo");
|
||||||
|
var responseWithState2 = await new HttpClient().GetStringAsync(url + "/foo");
|
||||||
|
|
||||||
|
// then
|
||||||
|
Check.That(responseNoState1).Equals("No state msg 1");
|
||||||
|
Check.That(responseWithState1).Equals("Test state msg 1");
|
||||||
|
Check.That(responseNoState2).Equals("No state msg 2");
|
||||||
|
Check.That(responseWithState2).Equals("Test state msg 2");
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
_server?.Dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
44
test/WireMock.Net.Tests/WireMockMiddlewareTests.cs
Normal file
44
test/WireMock.Net.Tests/WireMockMiddlewareTests.cs
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
//using Microsoft.Owin;
|
||||||
|
//using Moq;
|
||||||
|
//using NFluent;
|
||||||
|
//using WireMock.Owin;
|
||||||
|
//using Xunit;
|
||||||
|
|
||||||
|
//namespace WireMock.Net.Tests
|
||||||
|
//{
|
||||||
|
// public class WireMockMiddlewareTests
|
||||||
|
// {
|
||||||
|
// private readonly ObjectMother _objectMother = new ObjectMother();
|
||||||
|
|
||||||
|
// [Fact]
|
||||||
|
// public void Should_have_default_state_as_null()
|
||||||
|
// {
|
||||||
|
// // given
|
||||||
|
|
||||||
|
// // when
|
||||||
|
// var sut = _objectMother.Create();
|
||||||
|
|
||||||
|
// // then
|
||||||
|
// Check.That(sut.States).IsNull();
|
||||||
|
// }
|
||||||
|
|
||||||
|
// private class ObjectMother
|
||||||
|
// {
|
||||||
|
// private Mock<OwinMiddleware> OwinMiddleware { get; }
|
||||||
|
// private Mock<IOwinContext> OwinContext { get; }
|
||||||
|
// private WireMockMiddlewareOptions WireMockMiddlewareOptions { get; }
|
||||||
|
|
||||||
|
// public ObjectMother()
|
||||||
|
// {
|
||||||
|
// OwinContext = new Mock<IOwinContext>();
|
||||||
|
// OwinMiddleware = new Mock<OwinMiddleware>(null);
|
||||||
|
// WireMockMiddlewareOptions = new WireMockMiddlewareOptions();
|
||||||
|
// }
|
||||||
|
|
||||||
|
// public WireMockMiddleware Create()
|
||||||
|
// {
|
||||||
|
// return new WireMockMiddleware(OwinMiddleware.Object, WireMockMiddlewareOptions);
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
//}
|
||||||
Reference in New Issue
Block a user