change tests and add OpenCover

This commit is contained in:
Stef Heyenrath
2017-02-27 12:15:20 +01:00
parent ce39c7bad2
commit 4fa295edb7
15 changed files with 1423 additions and 14 deletions

View File

@@ -0,0 +1,291 @@
using System;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using NFluent;
using NUnit.Framework;
using WireMock.Matchers;
using WireMock.RequestBuilders;
using WireMock.ResponseBuilders;
using WireMock.Server;
namespace WireMock.Net.Tests
{
[TestFixture]
[Timeout(5000)]
public class FluentMockServerTests
{
private FluentMockServer _server;
[Test]
public void FluentMockServer_Admin_Mappings_Get()
{
var guid = Guid.Parse("90356dba-b36c-469a-a17e-669cd84f1f05");
_server = FluentMockServer.Start();
_server.Given(Request.Create().WithPath("/foo1").UsingGet())
.WithGuid(guid)
.RespondWith(Response.Create().WithStatusCode(201).WithBody("1"));
_server.Given(Request.Create().WithPath("/foo2").UsingGet())
.RespondWith(Response.Create().WithStatusCode(202).WithBody("2"));
var mappings = _server.Mappings.ToArray();
Check.That(mappings).HasSize(2);
Check.That(mappings.First().RequestMatcher).IsNotNull();
Check.That(mappings.First().Provider).IsNotNull();
Check.That(mappings.First().Guid).Equals(guid);
Check.That(mappings[1].Guid).Not.Equals(guid);
}
[Test]
public void FluentMockServer_Admin_Mappings_Add_SameGuid()
{
var guid = Guid.Parse("90356dba-b36c-469a-a17e-669cd84f1f05");
_server = FluentMockServer.Start();
_server.Given(Request.Create().WithPath("/1").UsingGet())
.WithGuid(guid)
.RespondWith(Response.Create().WithStatusCode(500));
var mappings = _server.Mappings.ToArray();
Check.That(mappings).HasSize(1);
Check.That(mappings.First().Guid).Equals(guid);
_server.Given(Request.Create().WithPath("/2").UsingGet())
.WithGuid(guid)
.RespondWith(Response.Create().WithStatusCode(500));
Check.That(mappings).HasSize(1);
Check.That(mappings.First().Guid).Equals(guid);
}
[Test]
public async Task FluentMockServer_Admin_Mappings_AtPriority()
{
_server = FluentMockServer.Start();
// given
_server.Given(Request.Create().WithPath("/1").UsingGet())
.AtPriority(2)
.RespondWith(Response.Create().WithStatusCode(200));
_server.Given(Request.Create().WithPath("/1").UsingGet())
.AtPriority(1)
.RespondWith(Response.Create().WithStatusCode(400));
var mappings = _server.Mappings.ToArray();
Check.That(mappings).HasSize(2);
Check.That(mappings[0].Priority).Equals(2);
Check.That(mappings[1].Priority).Equals(1);
// when
var response = await new HttpClient().GetAsync("http://localhost:" + _server.Ports[0] + "/1");
// then
Check.That((int)response.StatusCode).IsEqualTo(400);
}
[Test]
public async Task FluentMockServer_Admin_Requests_Get()
{
// given
_server = FluentMockServer.Start();
// when
await new HttpClient().GetAsync("http://localhost:" + _server.Ports[0] + "/foo");
// then
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]
public async Task Should_respond_to_request()
{
// given
_server = FluentMockServer.Start();
_server
.Given(Request.Create()
.WithPath("/foo")
.UsingGet())
.RespondWith(Response.Create()
.WithStatusCode(200)
.WithBody(@"{ msg: ""Hello world!""}"));
// when
var response = await new HttpClient().GetStringAsync("http://localhost:" + _server.Ports[0] + "/foo");
// then
Check.That(response).IsEqualTo(@"{ msg: ""Hello world!""}");
}
[Test]
public async Task Should_respond_to_request_bodyAsBase64()
{
// given
_server = FluentMockServer.Start();
_server.Given(Request.Create().WithPath("/foo").UsingGet()).RespondWith(Response.Create().WithBodyAsBase64("SGVsbG8gV29ybGQ/"));
// when
var response = await new HttpClient().GetStringAsync("http://localhost:" + _server.Ports[0] + "/foo");
// then
Check.That(response).IsEqualTo("Hello World?");
}
[Test]
public async Task Should_respond_404_for_unexpected_request()
{
// given
_server = FluentMockServer.Start();
// when
var response = await new HttpClient().GetAsync("http://localhost:" + _server.Ports[0] + "/foo");
// then
Check.That(response.StatusCode).IsEqualTo(HttpStatusCode.NotFound);
Check.That((int)response.StatusCode).IsEqualTo(404);
}
[Test]
public async Task Should_find_a_request_satisfying_a_request_spec()
{
// given
_server = FluentMockServer.Start();
// when
await new HttpClient().GetAsync("http://localhost:" + _server.Ports[0] + "/foo");
await new HttpClient().GetAsync("http://localhost:" + _server.Ports[0] + "/bar");
// then
var result = _server.FindLogEntries(Request.Create().WithPath(new RegexMatcher("^/b.*"))).ToList();
Check.That(result).HasSize(1);
var requestLogged = result.First();
Check.That(requestLogged.RequestMessage.Path).IsEqualTo("/bar");
Check.That(requestLogged.RequestMessage.Url).IsEqualTo("http://localhost:" + _server.Ports[0] + "/bar");
}
[Test]
public async Task Should_reset_requestlogs()
{
// given
_server = FluentMockServer.Start();
// when
await new HttpClient().GetAsync("http://localhost:" + _server.Ports[0] + "/foo");
_server.ResetLogEntries();
// then
Check.That(_server.LogEntries).IsEmpty();
}
[Test]
public void Should_reset_mappings()
{
// given
_server = FluentMockServer.Start();
_server
.Given(Request.Create()
.WithPath("/foo")
.UsingGet())
.RespondWith(Response.Create()
.WithBody(@"{ msg: ""Hello world!""}"));
// when
_server.ResetMappings();
// then
Check.That(_server.Mappings).IsEmpty();
Check.ThatAsyncCode(() => new HttpClient().GetStringAsync("http://localhost:" + _server.Ports[0] + "/foo"))
.ThrowsAny();
}
[Test]
public async Task Should_respond_a_redirect_without_body()
{
// given
_server = FluentMockServer.Start();
_server
.Given(Request.Create()
.WithPath("/foo")
.UsingGet())
.RespondWith(Response.Create()
.WithStatusCode(307)
.WithHeader("Location", "/bar"));
_server
.Given(Request.Create()
.WithPath("/bar")
.UsingGet())
.RespondWith(Response.Create()
.WithStatusCode(200)
.WithBody("REDIRECT SUCCESSFUL"));
// when
var response = await new HttpClient().GetStringAsync("http://localhost:" + _server.Ports[0] + "/foo");
// then
Check.That(response).IsEqualTo("REDIRECT SUCCESSFUL");
}
[Test]
public async Task Should_delay_responses_for_a_given_route()
{
// given
_server = FluentMockServer.Start();
_server
.Given(Request.Create()
.WithPath("/*"))
.RespondWith(Response.Create()
.WithBody(@"{ msg: ""Hello world!""}")
.WithDelay(TimeSpan.FromMilliseconds(200)));
// when
var watch = new Stopwatch();
watch.Start();
await new HttpClient().GetStringAsync("http://localhost:" + _server.Ports[0] + "/foo");
watch.Stop();
// then
Check.That(watch.ElapsedMilliseconds).IsGreaterThan(200);
}
[Test]
public async Task Should_delay_responses()
{
// given
_server = FluentMockServer.Start();
_server.AddGlobalProcessingDelay(TimeSpan.FromMilliseconds(200));
_server
.Given(Request.Create().WithPath("/*"))
.RespondWith(Response.Create().WithBody(@"{ msg: ""Hello world!""}"));
// when
var watch = new Stopwatch();
watch.Start();
await new HttpClient().GetStringAsync("http://localhost:" + _server.Ports[0] + "/foo");
watch.Stop();
// then
Check.That(watch.ElapsedMilliseconds).IsGreaterThan(200);
}
[TearDown]
public void ShutdownServer()
{
_server.Stop();
}
}
}

View File

@@ -0,0 +1,39 @@
using System.Diagnostics.CodeAnalysis;
using System.Net.Http;
using NFluent;
using NUnit.Framework;
using WireMock.Http;
[module:
SuppressMessage("StyleCop.CSharp.DocumentationRules",
"SA1600:ElementsMustBeDocumented",
Justification = "Reviewed. Suppression is OK here, as it's a tests class.")]
[module:
SuppressMessage("StyleCop.CSharp.DocumentationRules",
"SA1633:FileMustHaveHeader",
Justification = "Reviewed. Suppression is OK here, as unknown copyright and company.")]
namespace WireMock.Net.Tests.Http
{
[TestFixture]
public class TinyHttpServerTests
{
[Test]
public void Should_call_handler_on_request()
{
// given
var port = PortUtil.FindFreeTcpPort();
bool called = false;
var urlPrefix = "http://localhost:" + port + "/";
var server = new TinyHttpServer(ctx => called = true, urlPrefix);
server.Start();
// when
var httpClient = new HttpClient();
httpClient.GetAsync(urlPrefix).Wait(3000);
// then
Check.That(called).IsTrue();
}
}
}

View File

@@ -0,0 +1,147 @@
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using NFluent;
using NUnit.Framework;
using WireMock.Http;
namespace WireMock.Net.Tests
{
[TestFixture]
public class HttpListenerRequestMapperTests
{
private MapperServer _server;
[SetUp]
public void StartListenerServer()
{
_server = MapperServer.Start();
}
[Test]
public async Task Should_map_uri_from_listener_request()
{
// given
var client = new HttpClient();
// when
await client.GetAsync(MapperServer.UrlPrefix + "toto");
// then
Check.That(MapperServer.LastRequestMessage).IsNotNull();
Check.That(MapperServer.LastRequestMessage.Path).IsEqualTo("/toto");
}
[Test]
public async Task Should_map_verb_from_listener_request()
{
// given
var client = new HttpClient();
// when
await client.PutAsync(MapperServer.UrlPrefix, new StringContent("Hello!"));
// then
Check.That(MapperServer.LastRequestMessage).IsNotNull();
Check.That(MapperServer.LastRequestMessage.Method).IsEqualTo("put");
}
[Test]
public async Task Should_map_body_from_listener_request()
{
// given
var client = new HttpClient();
// when
await client.PutAsync(MapperServer.UrlPrefix, new StringContent("Hello!"));
// then
Check.That(MapperServer.LastRequestMessage).IsNotNull();
Check.That(MapperServer.LastRequestMessage.Body).IsEqualTo("Hello!");
}
[Test]
public async Task Should_map_headers_from_listener_request()
{
// given
var client = new HttpClient();
client.DefaultRequestHeaders.Add("X-Alex", "1706");
// when
await client.GetAsync(MapperServer.UrlPrefix);
// then
Check.That(MapperServer.LastRequestMessage).IsNotNull();
Check.That(MapperServer.LastRequestMessage.Headers).Not.IsNullOrEmpty();
Check.That(MapperServer.LastRequestMessage.Headers.Contains(new KeyValuePair<string, string>("X-Alex", "1706"))).IsTrue();
}
[Test]
public async Task Should_map_params_from_listener_request()
{
// given
var client = new HttpClient();
// when
await client.GetAsync(MapperServer.UrlPrefix + "index.html?id=toto");
// then
Check.That(MapperServer.LastRequestMessage).IsNotNull();
Check.That(MapperServer.LastRequestMessage.Path).EndsWith("/index.html");
Check.That(MapperServer.LastRequestMessage.GetParameter("id")).HasSize(1);
}
[TearDown]
public void StopListenerServer()
{
_server.Stop();
}
private class MapperServer : TinyHttpServer
{
private static volatile RequestMessage _lastRequestMessage;
private MapperServer(Action<HttpListenerContext> httpHandler, string urlPrefix) : base(httpHandler, urlPrefix)
{
}
public static RequestMessage LastRequestMessage
{
get
{
return _lastRequestMessage;
}
private set
{
_lastRequestMessage = value;
}
}
public static string UrlPrefix { get; private set; }
public new static MapperServer Start()
{
int port = PortUtil.FindFreeTcpPort();
UrlPrefix = "http://localhost:" + port + "/";
var server = new MapperServer(
context =>
{
LastRequestMessage = new HttpListenerRequestMapper().Map(context.Request);
context.Response.Close();
}, UrlPrefix);
((TinyHttpServer)server).Start();
return server;
}
public new void Stop()
{
base.Stop();
LastRequestMessage = null;
}
}
}
}

View File

@@ -0,0 +1,133 @@
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using NFluent;
using NUnit.Framework;
using WireMock.Http;
namespace WireMock.Net.Tests
{
[TestFixture]
public class HttpListenerResponseMapperTests
{
private TinyHttpServer _server;
private Task<HttpResponseMessage> _responseMsgTask;
[Test]
public void Should_map_status_code_from_original_response()
{
// given
var response = new ResponseMessage { StatusCode = 404 };
var httpListenerResponse = CreateHttpListenerResponse();
// when
new HttpListenerResponseMapper().Map(response, httpListenerResponse);
// then
Check.That(httpListenerResponse.StatusCode).IsEqualTo(404);
}
[Test]
public void Should_map_headers_from_original_response()
{
// given
var response = new ResponseMessage();
response.AddHeader("cache-control", "no-cache");
var httpListenerResponse = CreateHttpListenerResponse();
// when
new HttpListenerResponseMapper().Map(response, httpListenerResponse);
// then
Check.That(httpListenerResponse.Headers).HasSize(1);
Check.That(httpListenerResponse.Headers.Keys).Contains("cache-control");
Check.That(httpListenerResponse.Headers.Get("cache-control")).Contains("no-cache");
}
[Test]
public void Should_map_body_from_original_response()
{
// given
var response = new ResponseMessage
{
Body = "Hello !!!"
};
var httpListenerResponse = CreateHttpListenerResponse();
// when
new HttpListenerResponseMapper().Map(response, httpListenerResponse);
// then
var responseMessage = ToResponseMessage(httpListenerResponse);
Check.That(responseMessage).IsNotNull();
var contentTask = responseMessage.Content.ReadAsStringAsync();
Check.That(contentTask.Result).IsEqualTo("Hello !!!");
}
[Test]
public void Should_map_encoded_body_from_original_response()
{
// given
var response = new ResponseMessage
{
Body = "Hello !!!",
BodyEncoding = Encoding.ASCII
};
var httpListenerResponse = CreateHttpListenerResponse();
// when
new HttpListenerResponseMapper().Map(response, httpListenerResponse);
// then
Check.That(httpListenerResponse.ContentEncoding).Equals(Encoding.ASCII);
var responseMessage = ToResponseMessage(httpListenerResponse);
Check.That(responseMessage).IsNotNull();
var contentTask = responseMessage.Content.ReadAsStringAsync();
Check.That(contentTask.Result).IsEqualTo("Hello !!!");
}
[TearDown]
public void StopServer()
{
_server?.Stop();
}
/// <summary>
/// Dirty HACK to get HttpListenerResponse instances
/// </summary>
/// <returns>
/// The <see cref="HttpListenerResponse"/>.
/// </returns>
public HttpListenerResponse CreateHttpListenerResponse()
{
var port = PortUtil.FindFreeTcpPort();
var urlPrefix = "http://localhost:" + port + "/";
var responseReady = new AutoResetEvent(false);
HttpListenerResponse response = null;
_server = new TinyHttpServer(
context =>
{
response = context.Response;
responseReady.Set();
}, urlPrefix);
_server.Start();
_responseMsgTask = new HttpClient().GetAsync(urlPrefix);
responseReady.WaitOne();
return response;
}
public HttpResponseMessage ToResponseMessage(HttpListenerResponse listenerResponse)
{
listenerResponse.Close();
_responseMsgTask.Wait();
return _responseMsgTask.Result;
}
}
}

View File

@@ -0,0 +1,35 @@
using System;
using System.Text;
using NFluent;
using NUnit.Framework;
namespace WireMock.Net.Tests
{
[TestFixture]
public class RequestMessageTests
{
[Test]
public void Should_handle_empty_query()
{
// given
var request = new RequestMessage(new Uri("http://localhost/foo"), "POST");
// then
Check.That(request.GetParameter("not_there")).IsNull();
}
[Test]
public void Should_parse_query_params()
{
// given
string bodyAsString = "whatever";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost?foo=bar&multi=1&multi=2"), "POST", body, bodyAsString, Encoding.UTF8);
// then
Check.That(request.GetParameter("foo")).Contains("bar");
Check.That(request.GetParameter("multi")).Contains("1");
Check.That(request.GetParameter("multi")).Contains("2");
}
}
}

View File

@@ -0,0 +1,550 @@
using System;
using System.Collections.Generic;
using System.Text;
using NFluent;
using NUnit.Framework;
using WireMock.RequestBuilders;
using WireMock.Matchers;
using WireMock.Matchers.Request;
namespace WireMock.Net.Tests
{
[TestFixture]
public class RequestTests
{
[Test]
public void Should_specify_requests_matching_given_path()
{
// given
var spec = Request.Create().WithPath("/foo");
// when
var request = new RequestMessage(new Uri("http://localhost/foo"), "blabla");
// then
var requestMatchResult = new RequestMatchResult();
Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0);
}
[Test]
public void Should_specify_requests_matching_given_paths()
{
var requestBuilder = Request.Create().WithPath("/x1", "/x2");
var request1 = new RequestMessage(new Uri("http://localhost/x1"), "blabla");
var request2 = new RequestMessage(new Uri("http://localhost/x2"), "blabla");
var requestMatchResult = new RequestMatchResult();
Check.That(requestBuilder.GetMatchingScore(request1, requestMatchResult)).IsEqualTo(1.0);
Check.That(requestBuilder.GetMatchingScore(request2, requestMatchResult)).IsEqualTo(1.0);
}
[Test]
public void Should_specify_requests_matching_given_pathFuncs()
{
// given
var spec = Request.Create().WithPath(url => url.EndsWith("/foo"));
// when
var request = new RequestMessage(new Uri("http://localhost/foo"), "blabla");
// then
var requestMatchResult = new RequestMatchResult();
Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0);
}
[Test]
public void Should_specify_requests_matching_given_path_prefix()
{
// given
var spec = Request.Create().WithPath(new RegexMatcher("^/foo"));
// when
var request = new RequestMessage(new Uri("http://localhost/foo/bar"), "blabla");
// then
var requestMatchResult = new RequestMatchResult();
Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0);
}
[Test]
public void Should_exclude_requests_not_matching_given_path()
{
// given
var spec = Request.Create().WithPath("/foo");
// when
var request = new RequestMessage(new Uri("http://localhost/bar"), "blabla");
// then
var requestMatchResult = new RequestMatchResult();
Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsNotEqualTo(1.0);
}
[Test]
public void Should_specify_requests_matching_given_url()
{
// given
var spec = Request.Create().WithUrl("*/foo");
// when
var request = new RequestMessage(new Uri("http://localhost/foo"), "blabla");
// then
var requestMatchResult = new RequestMatchResult();
Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0);
}
[Test]
public void Should_specify_requests_matching_given_path_and_method_put()
{
// given
var spec = Request.Create().WithPath("/foo").UsingPut();
// when
var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT");
// then
var requestMatchResult = new RequestMatchResult();
Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0);
}
[Test]
public void Should_specify_requests_matching_given_path_and_method_post()
{
// given
var spec = Request.Create().WithPath("/foo").UsingPost();
// when
var request = new RequestMessage(new Uri("http://localhost/foo"), "POST");
// then
var requestMatchResult = new RequestMatchResult();
Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0);
}
[Test]
public void Should_specify_requests_matching_given_path_and_method_get()
{
// given
var spec = Request.Create().WithPath("/foo").UsingGet();
// when
var request = new RequestMessage(new Uri("http://localhost/foo"), "GET");
// then
var requestMatchResult = new RequestMatchResult();
Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0);
}
[Test]
public void Should_specify_requests_matching_given_path_and_method_delete()
{
// given
var spec = Request.Create().WithPath("/foo").UsingDelete();
// when
string bodyAsString = "whatever";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "Delete", body, bodyAsString, Encoding.UTF8);
// then
var requestMatchResult = new RequestMatchResult();
Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0);
}
[Test]
public void Should_specify_requests_matching_given_path_and_method_head()
{
// given
var spec = Request.Create().WithPath("/foo").UsingHead();
// when
var request = new RequestMessage(new Uri("http://localhost/foo"), "HEAD");
// then
var requestMatchResult = new RequestMatchResult();
Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0);
}
[Test]
public void Should_exclude_requests_matching_given_path_but_not_http_method()
{
// given
var spec = Request.Create().WithPath("/foo").UsingPut();
// when
var request = new RequestMessage(new Uri("http://localhost/foo"), "HEAD");
// then
var requestMatchResult = new RequestMatchResult();
Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsNotEqualTo(1.0);
}
[Test]
public void Should_exclude_requests_matching_given_http_method_but_not_url()
{
// given
var spec = Request.Create().WithPath("/bar").UsingPut();
// when
var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT");
// then
var requestMatchResult = new RequestMatchResult();
Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsNotEqualTo(1.0);
}
[Test]
public void Should_specify_requests_matching_given_path_and_headers()
{
// given
var spec = Request.Create().WithPath("/foo").UsingAnyVerb().WithHeader("X-toto", "tata");
// when
string bodyAsString = "whatever";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", body, bodyAsString, Encoding.UTF8, new Dictionary <string, string> { { "X-toto", "tata" } });
// then
var requestMatchResult = new RequestMatchResult();
Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0);
}
[Test]
public void Should_exclude_requests_not_matching_given_headers()
{
// given
var spec = Request.Create().UsingAnyVerb().WithHeader("X-toto", "tatata");
// when
string bodyAsString = "whatever";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", body, bodyAsString, Encoding.UTF8, new Dictionary <string, string> { { "X-toto", "tata" } });
// then
var requestMatchResult = new RequestMatchResult();
Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsNotEqualTo(1.0);
}
[Test]
public void Should_exclude_requests_not_matching_given_headers_ignorecase()
{
// given
var spec = Request.Create().UsingAnyVerb().WithHeader("X-toto", "abc", false);
// when
string bodyAsString = "whatever";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", body, bodyAsString, Encoding.UTF8, new Dictionary <string, string> { { "X-toto", "ABC" } });
// then
var requestMatchResult = new RequestMatchResult();
Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsNotEqualTo(1.0);
}
[Test]
public void Should_specify_requests_matching_given_header_prefix()
{
// given
var spec = Request.Create().UsingAnyVerb().WithHeader("X-toto", "tata*");
// when
string bodyAsString = "whatever";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", body, bodyAsString, Encoding.UTF8, new Dictionary<string, string> { { "X-toto", "TaTa" } });
// then
var requestMatchResult = new RequestMatchResult();
Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0);
}
[Test]
public void Should_specify_requests_matching_given_cookies()
{
// given
var spec = Request.Create().UsingAnyVerb().WithCookie("session", "a*");
// when
var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", null, null, null, null, new Dictionary<string, string> { { "session", "abc" } });
// then
var requestMatchResult = new RequestMatchResult();
Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0);
}
[Test]
public void Should_specify_requests_matching_given_body()
{
// given
var spec = Request.Create().UsingAnyVerb().WithBody("Hello world!");
// when
string bodyAsString = "Hello world!";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", body, bodyAsString, Encoding.UTF8);
// then
var requestMatchResult = new RequestMatchResult();
Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0);
}
[Test]
public void Should_specify_requests_matching_given_body_using_ExactMatcher_true()
{
// given
var requestBuilder = Request.Create().UsingAnyVerb().WithBody(new ExactMatcher("cat"));
// when
string bodyAsString = "cat";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "POST", body, bodyAsString, Encoding.UTF8);
// then
var requestMatchResult = new RequestMatchResult();
Check.That(requestBuilder.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0);
}
[Test]
public void Should_specify_requests_matching_given_body_using_ExactMatcher_multiplePatterns()
{
// given
var requestBuilder = Request.Create().UsingAnyVerb().WithBody(new ExactMatcher("cat", "dog"));
// when
string bodyAsString = "cat";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "POST", body, bodyAsString, Encoding.UTF8);
// then
var requestMatchResult = new RequestMatchResult();
Check.That(requestBuilder.GetMatchingScore(request, requestMatchResult)).IsEqualTo(0.5);
}
[Test]
public void Should_specify_requests_matching_given_body_using_ExactMatcher_false()
{
// given
var requestBuilder = Request.Create().UsingAnyVerb().WithBody(new ExactMatcher("cat"));
// when
string bodyAsString = "caR";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "POST", body, bodyAsString, Encoding.UTF8);
// then
var requestMatchResult = new RequestMatchResult();
Check.That(requestBuilder.GetMatchingScore(request, requestMatchResult)).IsLessThan(1.0);
}
[Test]
public void Should_specify_requests_matching_given_body_using_SimMetricsMatcher1()
{
// given
var requestBuilder = Request.Create().UsingAnyVerb().WithBody(new SimMetricsMatcher("The cat walks in the street."));
// when
string bodyAsString = "The car drives in the street.";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "POST", body, bodyAsString, Encoding.UTF8);
// then
var requestMatchResult = new RequestMatchResult();
Check.That(requestBuilder.GetMatchingScore(request, requestMatchResult)).IsLessThan(1.0).And.IsGreaterThan(0.5);
}
[Test]
public void Should_specify_requests_matching_given_body_using_SimMetricsMatcher2()
{
// given
var requestBuilder = Request.Create().UsingAnyVerb().WithBody(new SimMetricsMatcher("The cat walks in the street."));
// when
string bodyAsString = "Hello";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "POST", body, bodyAsString, Encoding.UTF8);
// then
var requestMatchResult = new RequestMatchResult();
Check.That(requestBuilder.GetMatchingScore(request, requestMatchResult)).IsLessThan(0.1).And.IsGreaterThan(0.05);
}
[Test]
public void Should_specify_requests_matching_given_body_using_WildcardMatcher()
{
// given
var spec = Request.Create().WithPath("/foo").UsingAnyVerb().WithBody(new WildcardMatcher("H*o*"));
// when
string bodyAsString = "Hello world!";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", body, bodyAsString, Encoding.UTF8, new Dictionary<string, string> { { "X-toto", "tatata" } });
// then
var requestMatchResult = new RequestMatchResult();
Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0);
}
[Test]
public void Should_specify_requests_matching_given_body_using_RegexMatcher()
{
// given
var spec = Request.Create().UsingAnyVerb().WithBody(new RegexMatcher("H.*o"));
// when
string bodyAsString = "Hello world!";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", body, bodyAsString, Encoding.UTF8);
// then
var requestMatchResult = new RequestMatchResult();
Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0);
}
[Test]
public void Should_specify_requests_matching_given_body_using_XPathMatcher_true()
{
// given
var spec = Request.Create().UsingAnyVerb().WithBody(new XPathMatcher("/todo-list[count(todo-item) = 3]"));
// when
string xmlBodyAsString = @"
<todo-list>
<todo-item id='a1'>abc</todo-item>
<todo-item id='a2'>def</todo-item>
<todo-item id='a3'>xyz</todo-item>
</todo-list>";
byte[] body = Encoding.UTF8.GetBytes(xmlBodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", body, xmlBodyAsString, Encoding.UTF8);
// then
var requestMatchResult = new RequestMatchResult();
Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0);
}
[Test]
public void Should_specify_requests_matching_given_body_using_XPathMatcher_false()
{
// given
var spec = Request.Create().UsingAnyVerb().WithBody(new XPathMatcher("/todo-list[count(todo-item) = 99]"));
// when
string xmlBodyAsString = @"
<todo-list>
<todo-item id='a1'>abc</todo-item>
<todo-item id='a2'>def</todo-item>
<todo-item id='a3'>xyz</todo-item>
</todo-list>";
byte[] body = Encoding.UTF8.GetBytes(xmlBodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", body, xmlBodyAsString, Encoding.UTF8);
// then
var requestMatchResult = new RequestMatchResult();
Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsNotEqualTo(1.0);
}
[Test]
public void Should_specify_requests_matching_given_body_using_JsonPathMatcher_true()
{
// given
var spec = Request.Create().UsingAnyVerb().WithBody(new JsonPathMatcher("$.things[?(@.name == 'RequiredThing')]"));
// when
string bodyAsString = "{ \"things\": [ { \"name\": \"RequiredThing\" }, { \"name\": \"Wiremock\" } ] }";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", body, bodyAsString, Encoding.UTF8);
// then
var requestMatchResult = new RequestMatchResult();
Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0);
}
[Test]
public void Should_specify_requests_matching_given_body_using_JsonPathMatcher_false()
{
// given
var spec = Request.Create().UsingAnyVerb().WithBody(new JsonPathMatcher("$.things[?(@.name == 'RequiredThing')]"));
// when
string bodyAsString = "{ \"things\": { \"name\": \"Wiremock\" } }";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", body, bodyAsString, Encoding.UTF8);
// then
var requestMatchResult = new RequestMatchResult();
Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsNotEqualTo(1.0);
}
[Test]
public void Should_exclude_requests_not_matching_given_body()
{
// given
var spec = Request.Create().UsingAnyVerb().WithBody(" Hello world! ");
// when
string bodyAsString = "xxx";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", body, bodyAsString, Encoding.UTF8, new Dictionary<string, string> { { "X-toto", "tatata" } });
// then
var requestMatchResult = new RequestMatchResult();
Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsNotEqualTo(1.0);
}
[Test]
public void Should_specify_requests_matching_given_param()
{
// given
var spec = Request.Create().WithParam("bar", "1", "2");
// when
var request = new RequestMessage(new Uri("http://localhost/foo?bar=1&bar=2"), "PUT");
// then
var requestMatchResult = new RequestMatchResult();
Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0);
}
[Test]
public void Should_specify_requests_matching_given_paramNoValue()
{
// given
var spec = Request.Create().WithParam("bar");
// when
var request = new RequestMessage(new Uri("http://localhost/foo?bar"), "PUT");
// then
var requestMatchResult = new RequestMatchResult();
Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0);
}
[Test]
public void Should_specify_requests_matching_given_param_func()
{
// given
var spec = Request.Create().UsingAnyVerb().WithParam(p => p.ContainsKey("bar"));
// when
var request = new RequestMessage(new Uri("http://localhost/foo?bar=1&bar=2"), "PUT");
// then
var requestMatchResult = new RequestMatchResult();
Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0);
}
[Test]
public void Should_exclude_requests_not_matching_given_params()
{
// given
var spec = Request.Create().WithParam("bar", "1");
// when
var request = new RequestMessage(new Uri("http://localhost/test=7"), "PUT");
// then
var requestMatchResult = new RequestMatchResult();
Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsNotEqualTo(1.0);
}
}
}

View File

@@ -0,0 +1,106 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using NFluent;
using NUnit.Framework;
using WireMock.ResponseBuilders;
namespace WireMock.Net.Tests
{
[TestFixture]
public class ResponseTests
{
[Test]
public async Task Response_ProvideResponse_Handlebars_UrlPathVerb()
{
// given
string bodyAsString = "abc";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "POST", body, bodyAsString, Encoding.UTF8);
var response = Response.Create()
.WithBody("test {{request.url}} {{request.path}} {{request.method}}")
.WithTransformer();
// act
var responseMessage = await response.ProvideResponse(request);
// then
Check.That(responseMessage.Body).Equals("test http://localhost/foo /foo post");
}
[Test]
public async Task Response_ProvideResponse_Handlebars_Query()
{
// given
string bodyAsString = "abc";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo?a=1&a=2&b=5"), "POST", body, bodyAsString, Encoding.UTF8);
var response = Response.Create()
.WithBody("test keya={{request.query.a}} idx={{request.query.a.[0]}} idx={{request.query.a.[1]}} keyb={{request.query.b}}")
.WithTransformer();
// act
var responseMessage = await response.ProvideResponse(request);
// then
Check.That(responseMessage.Body).Equals("test keya=1 idx=1 idx=2 keyb=5");
}
[Test]
public async Task Response_ProvideResponse_Handlebars_Headers()
{
// given
string bodyAsString = "abc";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "POST", body, bodyAsString, Encoding.UTF8, new Dictionary<string, string> { { "Content-Type", "text/plain" } });
var response = Response.Create().WithHeader("x", "{{request.headers.Content-Type}}").WithBody("test").WithTransformer();
// act
var responseMessage = await response.ProvideResponse(request);
// then
Check.That(responseMessage.Body).Equals("test");
Check.That(responseMessage.Headers).Contains(new KeyValuePair<string,string>("x", "text/plain"));
}
[Test]
public async Task Response_ProvideResponse_Encoding_Body()
{
// given
string bodyAsString = "abc";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "POST", body, bodyAsString, Encoding.UTF8);
var response = Response.Create().WithBody("test", Encoding.ASCII);
// act
var responseMessage = await response.ProvideResponse(request);
// then
Check.That(responseMessage.Body).Equals("test");
Check.That(responseMessage.BodyEncoding).Equals(Encoding.ASCII);
}
[Test]
public async Task Response_ProvideResponse_Encoding_JsonBody()
{
// given
string bodyAsString = "abc";
byte[] body = Encoding.UTF8.GetBytes(bodyAsString);
var request = new RequestMessage(new Uri("http://localhost/foo"), "POST", body, bodyAsString, Encoding.UTF8);
var response = Response.Create().WithBodyAsJson(new { value = "test" }, Encoding.ASCII);
// act
var responseMessage = await response.ProvideResponse(request);
// then
Check.That(responseMessage.Body).Equals("{\"value\":\"test\"}");
Check.That(responseMessage.BodyEncoding).Equals(Encoding.ASCII);
}
}
}

View File

@@ -0,0 +1,59 @@
using NUnit.Framework;
using WireMock.Matchers;
namespace WireMock.Net.Tests
{
[TestFixture]
public class WildcardMatcherTest
{
[Test]
public void WildcardMatcher_patterns_positive()
{
var tests = new[]
{
new { p = "*", i = "" },
new { p = "?", i = " " },
new { p = "*", i = "a" },
new { p = "*", i = "ab" },
new { p = "?", i = "a" },
new { p = "*?", i = "abc" },
new { p = "?*", i = "abc" },
new { p = "abc", i = "abc" },
new { p = "abc*", i = "abc" },
new { p = "abc*", i = "abcd" },
new { p = "*abc*", i = "abc" },
new { p = "*a*bc*", i = "abc" },
new { p = "*a*b?", i = "aXXXbc" }
};
foreach (var test in tests)
{
var matcher = new WildcardMatcher(test.p);
Assert.AreEqual(1.0, matcher.IsMatch(test.i), "p = " + test.p + ", i = " + test.i);
}
}
[Test]
public void WildcardMatcher_patterns_negative()
{
var tests = new[]
{
new { p = "*a", i = ""},
new { p = "a*", i = ""},
new { p = "?", i = ""},
new { p = "*b*", i = "a"},
new { p = "b*a", i = "ab"},
new { p = "??", i = "a"},
new { p = "*?", i = ""},
new { p = "??*", i = "a"},
new { p = "*abc", i = "abX"},
new { p = "*abc*", i = "Xbc"},
new { p = "*a*bc*", i = "ac"}
};
foreach (var test in tests)
{
var matcher = new WildcardMatcher(test.p);
Assert.AreEqual(0.0, matcher.IsMatch(test.i), "p = " + test.p + ", i = " + test.i);
}
}
}
}

View File

@@ -0,0 +1,21 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0.25420" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">14.0.25420</VisualStudioVersion>
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
</PropertyGroup>
<Import Project="$(VSToolsPath)\DotNet\Microsoft.DotNet.Props" Condition="'$(VSToolsPath)' != ''" />
<PropertyGroup Label="Globals">
<ProjectGuid>31dc2ef8-c3fe-467d-84be-fb5d956e612e</ProjectGuid>
<RootNamespace>WireMock.Net.Tests</RootNamespace>
<BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)'=='' ">.\obj</BaseIntermediateOutputPath>
<OutputPath Condition="'$(OutputPath)'=='' ">.\bin\</OutputPath>
</PropertyGroup>
<PropertyGroup>
<SchemaVersion>2.0</SchemaVersion>
</PropertyGroup>
<ItemGroup>
<Service Include="{82a7f48d-3b50-4b1e-b82e-3ada8210c358}" />
</ItemGroup>
<Import Project="$(VSToolsPath)\DotNet\Microsoft.DotNet.targets" Condition="'$(VSToolsPath)' != ''" />
</Project>

View File

@@ -0,0 +1,23 @@
{
"version": "1.0.0-*",
"authors": [ "Stef Heyenrath" ],
"frameworks": {
"net452": {
"frameworkAssemblies": {
"System.Net.Http": { "type": "build" }
},
"dependencies": {
"dotnet-test-nunit": "3.4.0-beta-3",
"Moq": "4.7.0",
"NFluent": "1.3.1",
"NUnit": "3.6.0",
"SimMetrics.Net": "1.0.1.0",
"WireMock.Net": { "target": "project" }
}
}
},
"testRunner": "nunit"
}