Implement "/__admin/requests"

This commit is contained in:
Stef Heyenrath
2017-01-26 12:00:30 +01:00
parent 1bf543a91e
commit a334974bef
30 changed files with 319 additions and 104 deletions

View File

@@ -315,7 +315,7 @@ The mappings defined in the mock service.
### /__admin/requests
Logged requests and responses received by the mock service.
* `GET /__admin/requests` --> TODO
* `GET /__admin/requests` --> Get received requests
* `GET /__admin/requests/{requestId}` --> TODO
* `POST /__admin/requests/reset` --> TODO
* `POST /__admin/requests/count` --> TODO

View File

@@ -82,7 +82,7 @@ namespace WireMock.Net.ConsoleApplication
Console.ReadKey();
Console.WriteLine("Displaying all requests");
var allRequests = server.RequestLogs;
var allRequests = server.LogEntries;
Console.WriteLine(JsonConvert.SerializeObject(allRequests, Formatting.Indented));
Console.WriteLine("Press any key to quit");

View File

@@ -1,4 +1,4 @@
namespace WireMock.Admin
namespace WireMock.Admin.Mappings
{
/// <summary>
/// Body Model

View File

@@ -1,6 +1,6 @@
using System.Collections.Generic;
namespace WireMock.Admin
namespace WireMock.Admin.Mappings
{
/// <summary>
/// Cookie Model

View File

@@ -1,6 +1,6 @@
using System.Collections.Generic;
namespace WireMock.Admin
namespace WireMock.Admin.Mappings
{
/// <summary>
/// Header Model

View File

@@ -1,6 +1,6 @@
using System;
namespace WireMock.Admin
namespace WireMock.Admin.Mappings
{
/// <summary>
/// MappingModel

View File

@@ -1,4 +1,4 @@
namespace WireMock.Admin
namespace WireMock.Admin.Mappings
{
/// <summary>
/// MatcherModel

View File

@@ -1,6 +1,6 @@
using System.Collections.Generic;
namespace WireMock.Admin
namespace WireMock.Admin.Mappings
{
/// <summary>
/// Param Model

View File

@@ -1,6 +1,6 @@
using System.Collections.Generic;
namespace WireMock.Admin
namespace WireMock.Admin.Mappings
{
/// <summary>
/// RequestModel
@@ -16,9 +16,9 @@ namespace WireMock.Admin
public UrlModel Url { get; set; }
/// <summary>
/// The verbs
/// The methods
/// </summary>
public string[] Verbs { get; set; }
public string[] Methods { get; set; }
/// <summary>
/// Gets or sets the Headers.

View File

@@ -1,6 +1,6 @@
using System.Collections.Generic;
namespace WireMock.Admin
namespace WireMock.Admin.Mappings
{
/// <summary>
/// ResponseModel

View File

@@ -1,6 +1,6 @@
using System.Collections.Generic;
namespace WireMock.Admin
namespace WireMock.Admin.Mappings
{
/// <summary>
/// UrlModel

View File

@@ -0,0 +1,24 @@
namespace WireMock.Admin.Requests
{
/// <summary>
/// Request Log Model
/// </summary>
public class LogEntryModel
{
/// <summary>
/// Gets or sets the request.
/// </summary>
/// <value>
/// The request.
/// </value>
public LogRequestModel Request { get; set; }
/// <summary>
/// Gets or sets the response.
/// </summary>
/// <value>
/// The response.
/// </value>
public LogResponseModel Response { get; set; }
}
}

View File

@@ -0,0 +1,104 @@
using System;
using System.Collections.Generic;
using WireMock.Util;
namespace WireMock.Admin.Requests
{
/// <summary>
/// RequestMessage Model
/// </summary>
public class LogRequestModel
{
/// <summary>
/// Gets or sets the unique identifier.
/// </summary>
/// <value>
/// The unique identifier.
/// </value>
public Guid Guid { get; set; }
/// <summary>
/// Gets the DateTime.
/// </summary>
public DateTime DateTime { get; set; }
/// <summary>
/// Gets or sets the URL.
/// </summary>
/// <value>
/// The URL.
/// </value>
public string Url { get; set; }
/// <summary>
/// Gets or sets the absolete URL.
/// </summary>
/// <value>
/// The absolete URL.
/// </value>
public string AbsoleteUrl { get; set; }
/// <summary>
/// Gets the query.
/// </summary>
public IDictionary<string, WireMockList<string>> Query { get; set; }
/// <summary>
/// Gets or sets the method.
/// </summary>
/// <value>
/// The method.
/// </value>
public string Method { get; set; }
/// <summary>
/// Gets or sets the Headers.
/// </summary>
/// <value>
/// The Headers.
/// </value>
public IDictionary<string, string> Headers { get; set; }
/// <summary>
/// Gets or sets the Cookies.
/// </summary>
/// <value>
/// The Cookies.
/// </value>
public IDictionary<string, string> Cookies { get; set; }
/// <summary>
/// Gets or sets the body.
/// </summary>
/// <value>
/// The body.
/// </value>
public string Body { get; set; }
/*
"id" : "45760a03-eebb-4387-ad0d-bb89b5d3d662",
"request" : {
"url" : "/received-request/9",
"absoluteUrl" : "http://localhost:56715/received-request/9",
"method" : "GET",
"clientIp" : "127.0.0.1",
"headers" : {
"Connection" : "keep-alive",
"Host" : "localhost:56715",
"User-Agent" : "Apache-HttpClient/4.5.1 (Java/1.7.0_51)"
},
"cookies" : { },
"browserProxyRequest" : false,
"loggedDate" : 1471442494809,
"bodyAsBase64" : "",
"body" : "",
"loggedDateString" : "2016-08-17T14:01:34Z"
},
"responseDefinition" : {
"status" : 404,
"transformers" : [ ],
"fromConfiguredStub" : false,
"transformerParameters" : { }
}*/
}
}

View File

@@ -0,0 +1,30 @@
using System.Collections.Generic;
namespace WireMock.Admin.Requests
{
/// <summary>
/// Response MessageModel
/// </summary>
public class LogResponseModel
{
/// <summary>
/// Gets or sets the status code.
/// </summary>
public int StatusCode { get; set; } = 200;
/// <summary>
/// Gets the headers.
/// </summary>
public IDictionary<string, string> Headers { get; set; }
/// <summary>
/// Gets or sets the body.
/// </summary>
public string Body { get; set; }
/// <summary>
/// Gets or sets the original body.
/// </summary>
public string BodyOriginal { get; set; }
}
}

View File

@@ -28,7 +28,9 @@ namespace WireMock
foreach (Cookie cookie in listenerRequest.Cookies)
cookies.Add(cookie.Name, cookie.Value);
return new RequestMessage(url, verb, body, bodyAsString, headers, cookies);
var message = new RequestMessage(url, verb, body, bodyAsString, headers, cookies) { DateTime = DateTime.Now };
return message;
}
/// <summary>

View File

@@ -0,0 +1,24 @@
namespace WireMock.Logging
{
/// <summary>
/// LogEntry
/// </summary>
public class LogEntry
{
/// <summary>
/// Gets or sets the request message.
/// </summary>
/// <value>
/// The request message.
/// </value>
public RequestMessage RequestMessage { get; set; }
/// <summary>
/// Gets or sets the response message.
/// </summary>
/// <value>
/// The response message.
/// </value>
public ResponseMessage ResponseMessage { get; set; }
}
}

View File

@@ -7,23 +7,23 @@ namespace WireMock.Matchers.Request
/// <summary>
/// The request verb matcher.
/// </summary>
internal class RequestMessageVerbMatcher : IRequestMatcher
internal class RequestMessageMethodMatcher : IRequestMatcher
{
/// <summary>
/// The verbs
/// The methods
/// </summary>
public string[] Verbs { get; }
public string[] Methods { get; }
/// <summary>
/// Initializes a new instance of the <see cref="RequestMessageVerbMatcher"/> class.
/// Initializes a new instance of the <see cref="RequestMessageMethodMatcher"/> class.
/// </summary>
/// <param name="verbs">
/// <param name="methods">
/// The verb.
/// </param>
public RequestMessageVerbMatcher([NotNull] params string[] verbs)
public RequestMessageMethodMatcher([NotNull] params string[] methods)
{
Check.NotNull(verbs, nameof(verbs));
Verbs = verbs.Select(v => v.ToLower()).ToArray();
Check.NotNull(methods, nameof(methods));
Methods = methods.Select(v => v.ToLower()).ToArray();
}
/// <summary>
@@ -35,7 +35,7 @@ namespace WireMock.Matchers.Request
/// </returns>
public bool IsMatch(RequestMessage requestMessage)
{
return Verbs.Contains(requestMessage.Verb);
return Methods.Contains(requestMessage.Method);
}
}
}

View File

@@ -3,9 +3,9 @@
namespace WireMock.RequestBuilders
{
/// <summary>
/// The VerbRequestBuilder interface.
/// The MethodRequestBuilder interface.
/// </summary>
public interface IVerbRequestBuilder : IHeadersAndCookiesRequestBuilder
public interface IMethodRequestBuilder : IHeadersAndCookiesRequestBuilder
{
/// <summary>
/// The using get.

View File

@@ -7,7 +7,7 @@ namespace WireMock.RequestBuilders
/// <summary>
/// IUrlAndPathRequestBuilder
/// </summary>
public interface IUrlAndPathRequestBuilder : IVerbRequestBuilder
public interface IUrlAndPathRequestBuilder : IMethodRequestBuilder
{
/// <summary>
/// The with url.

View File

@@ -127,7 +127,7 @@ namespace WireMock.RequestBuilders
/// </returns>
public IHeadersAndCookiesRequestBuilder UsingGet()
{
_requestMatchers.Add(new RequestMessageVerbMatcher("get"));
_requestMatchers.Add(new RequestMessageMethodMatcher("get"));
return this;
}
@@ -139,7 +139,7 @@ namespace WireMock.RequestBuilders
/// </returns>
public IHeadersAndCookiesRequestBuilder UsingPost()
{
_requestMatchers.Add(new RequestMessageVerbMatcher("post"));
_requestMatchers.Add(new RequestMessageMethodMatcher("post"));
return this;
}
@@ -151,7 +151,7 @@ namespace WireMock.RequestBuilders
/// </returns>
public IHeadersAndCookiesRequestBuilder UsingPut()
{
_requestMatchers.Add(new RequestMessageVerbMatcher("put"));
_requestMatchers.Add(new RequestMessageMethodMatcher("put"));
return this;
}
@@ -163,7 +163,7 @@ namespace WireMock.RequestBuilders
/// </returns>
public IHeadersAndCookiesRequestBuilder UsingDelete()
{
_requestMatchers.Add(new RequestMessageVerbMatcher("delete"));
_requestMatchers.Add(new RequestMessageMethodMatcher("delete"));
return this;
}
@@ -175,7 +175,7 @@ namespace WireMock.RequestBuilders
/// </returns>
public IHeadersAndCookiesRequestBuilder UsingHead()
{
_requestMatchers.Add(new RequestMessageVerbMatcher("head"));
_requestMatchers.Add(new RequestMessageMethodMatcher("head"));
return this;
}
@@ -187,7 +187,7 @@ namespace WireMock.RequestBuilders
/// </returns>
public IHeadersAndCookiesRequestBuilder UsingAnyVerb()
{
var matchers = _requestMatchers.Where(m => m is RequestMessageVerbMatcher).ToList();
var matchers = _requestMatchers.Where(m => m is RequestMessageMethodMatcher).ToList();
foreach (var matcher in matchers)
{
_requestMatchers.Remove(matcher);
@@ -203,7 +203,7 @@ namespace WireMock.RequestBuilders
/// <returns>The <see cref="IHeadersAndCookiesRequestBuilder"/>.</returns>
public IHeadersAndCookiesRequestBuilder UsingVerb(params string[] verbs)
{
_requestMatchers.Add(new RequestMessageVerbMatcher(verbs));
_requestMatchers.Add(new RequestMessageMethodMatcher(verbs));
return this;
}

View File

@@ -17,15 +17,20 @@ namespace WireMock
/// </summary>
public string Url { get; private set; }
/// <summary>
/// Gets the DateTime.
/// </summary>
public DateTime DateTime { get; set; }
/// <summary>
/// Gets the path.
/// </summary>
public string Path { get; }
/// <summary>
/// Gets the verb.
/// Gets the method.
/// </summary>
public string Verb { get; }
public string Method { get; }
/// <summary>
/// Gets the headers.
@@ -68,7 +73,7 @@ namespace WireMock
Url = url.ToString();
Path = url.AbsolutePath;
Verb = verb.ToLower();
Method = verb.ToLower();
BodyAsBytes = bodyAsBytes;
Body = body;
Headers = headers;

View File

@@ -185,7 +185,7 @@ namespace WireMock.ResponseBuilders
ResponseMessage responseMessage;
if (_useTransformer)
{
responseMessage = new ResponseMessage { StatusCode = ResponseMessage.StatusCode };
responseMessage = new ResponseMessage { StatusCode = ResponseMessage.StatusCode, BodyOriginal = ResponseMessage.Body };
var template = new { request = requestMessage };

View File

@@ -17,6 +17,11 @@ namespace WireMock
/// </summary>
public int StatusCode { get; set; } = 200;
/// <summary>
/// Gets or sets the body.
/// </summary>
public string BodyOriginal { get; set; }
/// <summary>
/// Gets or sets the body.
/// </summary>

View File

@@ -3,7 +3,8 @@ using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using Newtonsoft.Json;
using WireMock.Admin;
using WireMock.Admin.Mappings;
using WireMock.Admin.Requests;
using WireMock.Matchers;
using WireMock.Matchers.Request;
using WireMock.RequestBuilders;
@@ -19,6 +20,42 @@ namespace WireMock.Server
private void InitAdmin()
{
Given(Request.Create().WithUrl("/__admin/mappings").UsingGet()).RespondWith(new DynamicResponseProvider(MappingsGet));
Given(Request.Create().WithUrl("/__admin/requests").UsingGet()).RespondWith(new DynamicResponseProvider(RequestsGet));
}
private ResponseMessage RequestsGet()
{
var result = new List<LogEntryModel>();
foreach (var logEntry in LogEntries.Where(r => !r.RequestMessage.Path.StartsWith("/__admin/")))
{
var model = new LogEntryModel
{
Request = new LogRequestModel
{
Guid = Guid.NewGuid(),
DateTime = logEntry.RequestMessage.DateTime,
Url = logEntry.RequestMessage.Path,
AbsoleteUrl = logEntry.RequestMessage.Url,
Query = logEntry.RequestMessage.Query,
Method = logEntry.RequestMessage.Method,
Body = logEntry.RequestMessage.Body,
Headers = logEntry.RequestMessage.Headers,
Cookies = logEntry.RequestMessage.Cookies
},
Response = new LogResponseModel
{
StatusCode = logEntry.ResponseMessage.StatusCode,
Body = logEntry.ResponseMessage.Body,
BodyOriginal = logEntry.ResponseMessage.BodyOriginal,
Headers = logEntry.ResponseMessage.Headers
}
};
result.Add(model);
}
return ToJson(result);
}
private ResponseMessage MappingsGet()
@@ -32,7 +69,7 @@ namespace WireMock.Server
var cookieMatchers = request.GetRequestMessageMatchers<RequestMessageCookieMatcher>();
var paramsMatchers = request.GetRequestMessageMatchers<RequestMessageParamMatcher>();
var bodyMatcher = request.GetRequestMessageMatcher<RequestMessageBodyMatcher>();
var verbMatcher = request.GetRequestMessageMatcher<RequestMessageVerbMatcher>();
var methodMatcher = request.GetRequestMessageMatcher<RequestMessageMethodMatcher>();
var response = (Response) mapping.Provider;
@@ -45,7 +82,7 @@ namespace WireMock.Server
{
Matchers = urlMatchers != null ? Map(urlMatchers.Where(m => m.Matchers != null).SelectMany(m => m.Matchers)) : null
},
Verbs = verbMatcher != null ? verbMatcher.Verbs : new [] { "any" },
Methods = methodMatcher != null ? methodMatcher.Methods : new [] { "any" },
Headers = headerMatchers?.Select(hm => new HeaderModel
{
Name = hm.Name,

View File

@@ -4,10 +4,10 @@ using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using JetBrains.Annotations;
using WireMock.Http;
using WireMock.Logging;
using WireMock.Matchers.Request;
using WireMock.Validation;
@@ -18,39 +18,18 @@ namespace WireMock.Server
/// </summary>
public partial class FluentMockServer
{
/// <summary>
/// The _http server.
/// </summary>
private readonly TinyHttpServer _httpServer;
/// <summary>
/// The _mappings.
/// </summary>
private readonly IList<Mapping> _mappings = new List<Mapping>();
/// <summary>
/// The _request logs.
/// </summary>
private readonly IList<RequestMessage> _requestLogs = new List<RequestMessage>();
private readonly IList<LogEntry> _logEntries = new List<LogEntry>();
/// <summary>
/// The _request mapper.
/// </summary>
private readonly HttpListenerRequestMapper _requestMapper = new HttpListenerRequestMapper();
/// <summary>
/// The _response mapper.
/// </summary>
private readonly HttpListenerResponseMapper _responseMapper = new HttpListenerResponseMapper();
/// <summary>
/// The _sync root.
/// </summary>
private readonly object _syncRoot = new object();
/// <summary>
/// The _request processing delay.
/// </summary>
private TimeSpan _requestProcessingDelay = TimeSpan.Zero;
/// <summary>
@@ -61,19 +40,19 @@ namespace WireMock.Server
/// <summary>
/// Gets the request logs.
/// </summary>
public IEnumerable<RequestMessage> RequestLogs
public IEnumerable<LogEntry> LogEntries
{
get
{
lock (((ICollection)_requestLogs).SyncRoot)
lock (((ICollection)_logEntries).SyncRoot)
{
return new ReadOnlyCollection<RequestMessage>(_requestLogs);
return new ReadOnlyCollection<LogEntry>(_logEntries);
}
}
}
/// <summary>
/// Gets the routes.
/// Gets the mappings.
/// </summary>
public IEnumerable<Mapping> Mappings
{
@@ -146,9 +125,9 @@ namespace WireMock.Server
/// </summary>
public void Reset()
{
lock (((ICollection)_requestLogs).SyncRoot)
lock (((ICollection)_logEntries).SyncRoot)
{
_requestLogs.Clear();
_logEntries.Clear();
}
lock (((ICollection)_mappings).SyncRoot)
@@ -160,17 +139,13 @@ namespace WireMock.Server
/// <summary>
/// The search logs for.
/// </summary>
/// <param name="spec">
/// The matcher.
/// </param>
/// <returns>
/// The <see cref="IEnumerable"/>.
/// </returns>
public IEnumerable<RequestMessage> SearchLogsFor(IRequestMatcher spec)
/// <param name="matcher">The matcher.</param>
/// <returns>The <see cref="IEnumerable"/>.</returns>
public IEnumerable<LogEntry> SearchLogsFor(IRequestMatcher matcher)
{
lock (((ICollection)_requestLogs).SyncRoot)
lock (((ICollection)_logEntries).SyncRoot)
{
return _requestLogs.Where(spec.IsMatch);
return _logEntries.Where(log => matcher.IsMatch(log.RequestMessage));
}
}
@@ -215,14 +190,12 @@ namespace WireMock.Server
/// <summary>
/// The log request.
/// </summary>
/// <param name="requestMessage">
/// The request.
/// </param>
private void LogRequest(RequestMessage requestMessage)
/// <param name="entry">The request.</param>
private void LogRequest(LogEntry entry)
{
lock (((ICollection)_requestLogs).SyncRoot)
lock (((ICollection)_logEntries).SyncRoot)
{
_requestLogs.Add(requestMessage);
_logEntries.Add(entry);
}
}
@@ -238,33 +211,44 @@ namespace WireMock.Server
}
var request = _requestMapper.Map(ctx.Request);
LogRequest(request);
ResponseMessage response = null;
try
{
var targetRoute = _mappings.FirstOrDefault(route => route.IsRequestHandled(request));
if (targetRoute == null)
{
ctx.Response.StatusCode = 404;
byte[] content = Encoding.UTF8.GetBytes("No mapping found");
ctx.Response.OutputStream.Write(content, 0, content.Length);
response = new ResponseMessage
{
StatusCode = 404,
Body = "No mapping found"
};
}
else
{
var response = await targetRoute.ResponseTo(request);
_responseMapper.Map(response, ctx.Response);
response = await targetRoute.ResponseTo(request);
}
}
catch (Exception ex)
{
ctx.Response.StatusCode = 500;
byte[] content = Encoding.UTF8.GetBytes(ex.ToString());
ctx.Response.OutputStream.Write(content, 0, content.Length);
response = new ResponseMessage
{
StatusCode = 500,
Body = ex.ToString()
};
}
finally
{
var log = new LogEntry
{
RequestMessage = request,
ResponseMessage = response
};
LogRequest(log);
_responseMapper.Map(response, ctx.Response);
ctx.Response.Close();
}
}

View File

@@ -97,10 +97,10 @@ namespace WireMock.Net.Tests
await new HttpClient().GetAsync("http://localhost:" + _server.Port + "/foo");
// then
Check.That(_server.RequestLogs).HasSize(1);
var requestLogged = _server.RequestLogs.First();
Check.That(requestLogged.Verb).IsEqualTo("get");
Check.That(requestLogged.BodyAsBytes).IsNull();
Check.That(_server.LogEntries).HasSize(1);
var requestLogged = _server.LogEntries.First();
Check.That(requestLogged.RequestMessage.Method).IsEqualTo("get");
Check.That(requestLogged.RequestMessage.BodyAsBytes).IsNull();
}
[Test]
@@ -118,8 +118,8 @@ namespace WireMock.Net.Tests
Check.That(result).HasSize(1);
var requestLogged = result.First();
Check.That(requestLogged.Path).IsEqualTo("/bar");
Check.That(requestLogged.Url).IsEqualTo("http://localhost:" + _server.Port + "/bar");
Check.That(requestLogged.RequestMessage.Path).IsEqualTo("/bar");
Check.That(requestLogged.RequestMessage.Url).IsEqualTo("http://localhost:" + _server.Port + "/bar");
}
[Test]
@@ -133,7 +133,7 @@ namespace WireMock.Net.Tests
_server.Reset();
// then
Check.That(_server.RequestLogs).IsEmpty();
Check.That(_server.LogEntries).IsEmpty();
}
[Test]

View File

@@ -46,7 +46,7 @@ namespace WireMock.Net.Tests
// then
Check.That(MapperServer.LastRequestMessage).IsNotNull();
Check.That(MapperServer.LastRequestMessage.Verb).IsEqualTo("put");
Check.That(MapperServer.LastRequestMessage.Method).IsEqualTo("put");
}
[Test]

View File

@@ -20,7 +20,7 @@ namespace WireMock.Net.Tests
var request = new RequestMessage(new Uri("http://localhost/foo"), "POST", body, bodyAsString);
var response = Response.Create()
.WithBody("test {{request.url}} {{request.path}} {{request.verb}}")
.WithBody("test {{request.url}} {{request.path}} {{request.method}}")
.WithTransformer();
// act