Support Microsoft.AspNetCore for net 4.6.1 and up (#185)

* net451

* tests : net462

* fixed tests

* fix tests

* readme

* Code review

* LocalFileSystemHandlerTests

* refactor
This commit is contained in:
Stef Heyenrath
2018-08-17 18:52:29 +02:00
committed by GitHub
parent 01d6dce62d
commit b57d118c3d
69 changed files with 842 additions and 2032 deletions

View File

@@ -1,291 +0,0 @@
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

@@ -1,39 +0,0 @@
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

@@ -1,147 +0,0 @@
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

@@ -1,133 +0,0 @@
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

@@ -1,35 +0,0 @@
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("WireMock.Net.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WireMock.Net.Tests")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d8b56d28-33ce-4bef-97d4-7dd546e37f25")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@@ -1,35 +0,0 @@
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

@@ -1,550 +0,0 @@
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

@@ -1,106 +0,0 @@
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

@@ -1,59 +0,0 @@
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

@@ -1,90 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{D8B56D28-33CE-4BEF-97D4-7DD546E37F25}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>WireMock.Net.Tests</RootNamespace>
<AssemblyName>WireMock.Net.Tests</AssemblyName>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Castle.Core, Version=3.3.0.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc, processorArchitecture=MSIL">
<HintPath>..\..\packages\Castle.Core.3.3.3\lib\net45\Castle.Core.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="Moq, Version=4.5.30.0, Culture=neutral, PublicKeyToken=69f491c39445e920, processorArchitecture=MSIL">
<HintPath>..\..\packages\Moq.4.5.30\lib\net45\Moq.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="NFluent, Version=1.3.1.0, Culture=neutral, PublicKeyToken=18828b37b84b1437, processorArchitecture=MSIL">
<HintPath>..\..\packages\NFluent.1.3.1.0\lib\net40\NFluent.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="nunit.framework, Version=3.6.0.0, Culture=neutral, PublicKeyToken=2638cd05610744eb, processorArchitecture=MSIL">
<HintPath>..\..\packages\NUnit.3.6.0\lib\net45\nunit.framework.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="SimMetrics.Net, Version=1.0.1.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\..\packages\SimMetrics.Net.1.0.1.0\lib\net45\SimMetrics.Net.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
<Reference Include="WireMock.Net">
<HintPath>..\..\src\WireMock.Net\bin\$(Configuration)\net45\WireMock.Net.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="FluentMockServerTests.cs" />
<Compile Include="HttpListenerRequestMapperTests.cs" />
<Compile Include="HttpListenerResponseMapperTests.cs" />
<Compile Include="Http\TinyHttpServerTests.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="RequestTests.cs" />
<Compile Include="RequestMessageTests.cs" />
<Compile Include="ResponseTests.cs" />
<Compile Include="WildcardMatcherTest.cs" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View File

@@ -1,8 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Castle.Core" version="3.3.3" targetFramework="net452" />
<package id="Moq" version="4.5.30" targetFramework="net452" />
<package id="NFluent" version="1.3.1.0" targetFramework="net452" />
<package id="NUnit" version="3.6.0" targetFramework="net452" />
<package id="SimMetrics.Net" version="1.0.1.0" targetFramework="net452" />
</packages>

View File

@@ -9,8 +9,21 @@ using Xunit;
namespace WireMock.Net.Tests
{
// TODO : move these to FluentMockServerAdminRestClientTests
public class ClientTests
{
[Fact]
public async Task Client_IFluentMockServerAdmin_SettingsGet()
{
// Assign
var server = FluentMockServer.StartWithAdminInterface();
var api = RestClient.For<IFluentMockServerAdmin>(server.Urls[0]);
// Act
var settings = await api.GetSettingsAsync();
Check.That(settings).IsNotNull();
}
[Fact]
public async Task Client_IFluentMockServerAdmin_PostMappingAsync()
{

View File

@@ -13,21 +13,14 @@ using Xunit;
namespace WireMock.Net.Tests
{
public class FluentMockServerAdminRestClientTests : IDisposable
public class FluentMockServerAdminRestClientTests
{
public void Dispose()
{
_server?.Stop();
}
private FluentMockServer _server;
[Fact]
public async Task IFluentMockServerAdmin_FindRequestsAsync()
{
// given
_server = FluentMockServer.Start(new FluentMockServerSettings { StartAdminInterface = true, Logger = new WireMockNullLogger() });
var serverUrl = "http://localhost:" + _server.Ports[0];
var server = FluentMockServer.Start(new FluentMockServerSettings { StartAdminInterface = true, Logger = new WireMockNullLogger() });
var serverUrl = "http://localhost:" + server.Ports[0];
await new HttpClient().GetAsync(serverUrl + "/foo");
var api = RestClient.For<IFluentMockServerAdmin>(serverUrl);
@@ -46,8 +39,8 @@ namespace WireMock.Net.Tests
public async Task IFluentMockServerAdmin_GetRequestsAsync()
{
// given
_server = FluentMockServer.Start(new FluentMockServerSettings { StartAdminInterface = true, Logger = new WireMockNullLogger() });
var serverUrl = "http://localhost:" + _server.Ports[0];
var server = FluentMockServer.Start(new FluentMockServerSettings { StartAdminInterface = true, Logger = new WireMockNullLogger() });
var serverUrl = "http://localhost:" + server.Ports[0];
await new HttpClient().GetAsync(serverUrl + "/foo");
var api = RestClient.For<IFluentMockServerAdmin>(serverUrl);

View File

@@ -0,0 +1,314 @@
using System;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Moq;
using Newtonsoft.Json;
using NFluent;
using WireMock.Handlers;
using WireMock.RequestBuilders;
using WireMock.ResponseBuilders;
using WireMock.Server;
using WireMock.Settings;
using Xunit;
namespace WireMock.Net.Tests
{
public class FluentMockServerAdminTests
{
// For for AppVeyor + OpenCover
private string GetCurrentFolder()
{
string current = Directory.GetCurrentDirectory();
//if (!current.EndsWith("WireMock.Net.Tests"))
// return Path.Combine(current, "test", "WireMock.Net.Tests");
return current;
}
[Fact]
public void FluentMockServer_Admin_StartStop()
{
var server1 = FluentMockServer.Start("http://localhost:9091");
Check.That(server1.Urls[0]).Equals("http://localhost:9091");
server1.Stop();
var server2 = FluentMockServer.Start("http://localhost:9091/");
Check.That(server2.Urls[0]).Equals("http://localhost:9091/");
server2.Stop();
}
[Fact]
public void FluentMockServer_Admin_SaveStaticMappings()
{
// Assign
string guid = "791a3f31-6946-aaaa-8e6f-0237c7441111";
var staticMappingHandlerMock = new Mock<IFileSystemHandler>();
staticMappingHandlerMock.Setup(m => m.GetMappingFolder()).Returns("folder");
staticMappingHandlerMock.Setup(m => m.FolderExists(It.IsAny<string>())).Returns(true);
staticMappingHandlerMock.Setup(m => m.WriteMappingFile(It.IsAny<string>(), It.IsAny<string>()));
var _server = FluentMockServer.Start(new FluentMockServerSettings
{
FileSystemHandler = staticMappingHandlerMock.Object
});
_server
.Given(Request.Create().WithPath($"/foo_{Guid.NewGuid()}"))
.WithGuid(guid)
.RespondWith(Response.Create().WithBody("save test"));
// Act
_server.SaveStaticMappings();
// Assert and Verify
staticMappingHandlerMock.Verify(m => m.GetMappingFolder(), Times.Once);
staticMappingHandlerMock.Verify(m => m.FolderExists("folder"), Times.Once);
staticMappingHandlerMock.Verify(m => m.WriteMappingFile(Path.Combine("folder", guid + ".json"), It.IsAny<string>()), Times.Once);
}
[Fact]
public void FluentMockServer_Admin_ReadStaticMapping_WithNonGuidFilename()
{
var guid = Guid.Parse("04ee4872-9efd-4770-90d3-88d445265d0d");
string title = "documentdb_root_title";
var _server = FluentMockServer.Start();
string folder = Path.Combine(GetCurrentFolder(), "__admin", "mappings", "documentdb_root.json");
_server.ReadStaticMappingAndAddOrUpdate(folder);
var mappings = _server.Mappings.ToArray();
Check.That(mappings).HasSize(1);
Check.That(mappings.First().RequestMatcher).IsNotNull();
Check.That(mappings.First().Provider).IsNotNull();
Check.That(mappings.First().Guid).Equals(guid);
Check.That(mappings.First().Title).Equals(title);
}
[Fact]
public void FluentMockServer_Admin_ReadStaticMapping_WithGuidFilename()
{
string guid = "00000002-ee28-4f29-ae63-1ac9b0802d86";
var _server = FluentMockServer.Start();
string folder = Path.Combine(GetCurrentFolder(), "__admin", "mappings", guid + ".json");
_server.ReadStaticMappingAndAddOrUpdate(folder);
var mappings = _server.Mappings.ToArray();
Check.That(mappings).HasSize(1);
Check.That(mappings.First().RequestMatcher).IsNotNull();
Check.That(mappings.First().Provider).IsNotNull();
Check.That(mappings.First().Guid).Equals(Guid.Parse(guid));
Check.That(mappings.First().Title).IsNullOrEmpty();
}
[Fact]
public void FluentMockServer_Admin_ReadStaticMapping_WithResponseBodyFromFile()
{
string guid = "00000002-ee28-4f29-ae63-1ac9b0802d87";
string folder = Path.Combine(GetCurrentFolder(), "__admin", "mappings", guid + ".json");
string json = File.ReadAllText(folder);
string responseBodyFilePath = Path.Combine(GetCurrentFolder(), "responsebody.json");
dynamic jsonObj = JsonConvert.DeserializeObject(json);
jsonObj["Response"]["BodyAsFile"] = responseBodyFilePath;
string output = JsonConvert.SerializeObject(jsonObj, Formatting.Indented);
File.WriteAllText(folder, output);
var _server = FluentMockServer.Start();
_server.ReadStaticMappingAndAddOrUpdate(folder);
var mappings = _server.Mappings.ToArray();
Check.That(mappings).HasSize(1);
Check.That(mappings.First().RequestMatcher).IsNotNull();
Check.That(mappings.First().Provider).IsNotNull();
Check.That(mappings.First().Guid).Equals(Guid.Parse(guid));
Check.That(mappings.First().Title).IsNullOrEmpty();
}
[Fact]
public void FluentMockServer_Admin_ReadStaticMappings_FolderExistsIsTrue()
{
// Assign
var staticMappingHandlerMock = new Mock<IFileSystemHandler>();
staticMappingHandlerMock.Setup(m => m.GetMappingFolder()).Returns("folder");
staticMappingHandlerMock.Setup(m => m.FolderExists(It.IsAny<string>())).Returns(true);
staticMappingHandlerMock.Setup(m => m.EnumerateFiles(It.IsAny<string>())).Returns(new string[0]);
var _server = FluentMockServer.Start(new FluentMockServerSettings
{
FileSystemHandler = staticMappingHandlerMock.Object
});
// Act
_server.ReadStaticMappings();
// Assert and Verify
staticMappingHandlerMock.Verify(m => m.GetMappingFolder(), Times.Once);
staticMappingHandlerMock.Verify(m => m.FolderExists("folder"), Times.Once);
staticMappingHandlerMock.Verify(m => m.EnumerateFiles("folder"), Times.Once);
}
[Fact]
public void FluentMockServer_Admin_ReadStaticMappingAndAddOrUpdate()
{
// Assign
string mapping = "{\"Request\": {\"Path\": {\"Matchers\": [{\"Name\": \"WildcardMatcher\",\"Pattern\": \"/static/mapping\"}]},\"Methods\": [\"get\"]},\"Response\": {\"BodyAsJson\": { \"body\": \"static mapping\" }}}";
var _staticMappingHandlerMock = new Mock<IFileSystemHandler>();
_staticMappingHandlerMock.Setup(m => m.ReadMappingFile(It.IsAny<string>())).Returns(mapping);
var _server = FluentMockServer.Start(new FluentMockServerSettings
{
FileSystemHandler = _staticMappingHandlerMock.Object
});
// Act
_server.ReadStaticMappingAndAddOrUpdate(@"c:\test.json");
// Assert and Verify
_staticMappingHandlerMock.Verify(m => m.ReadMappingFile(@"c:\test.json"), Times.Once);
}
[Fact]
public void FluentMockServer_Admin_ReadStaticMappings()
{
var _server = FluentMockServer.Start();
string folder = Path.Combine(GetCurrentFolder(), "__admin", "mappings");
_server.ReadStaticMappings(folder);
var mappings = _server.Mappings.ToArray();
Check.That(mappings).HasSize(3);
}
[Fact]
public void FluentMockServer_Admin_Mappings_WithGuid_Get()
{
Guid guid = Guid.Parse("90356dba-b36c-469a-a17e-669cd84f1f05");
var _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);
}
[Fact]
public void FluentMockServer_Admin_Mappings_WithGuidAsString_Get()
{
string guid = "90356dba-b36c-469a-a17e-669cd84f1f05";
var _server = FluentMockServer.Start();
_server.Given(Request.Create().WithPath("/foo100").UsingGet()).WithGuid(guid)
.RespondWith(Response.Create().WithStatusCode(201).WithBody("1"));
var mappings = _server.Mappings.ToArray();
Check.That(mappings).HasSize(1);
}
[Fact]
public void FluentMockServer_Admin_Mappings_Add_SameGuid()
{
var guid = Guid.Parse("90356dba-b36c-469a-a17e-669cd84f1f05");
var _server = FluentMockServer.Start();
var response1 = Response.Create().WithStatusCode(500);
_server.Given(Request.Create().UsingGet())
.WithGuid(guid)
.RespondWith(response1);
var mappings1 = _server.Mappings.ToArray();
Check.That(mappings1).HasSize(1);
Check.That(mappings1.First().Guid).Equals(guid);
var response2 = Response.Create().WithStatusCode(400);
_server.Given(Request.Create().WithPath("/2").UsingGet())
.WithGuid(guid)
.RespondWith(response2);
var mappings2 = _server.Mappings.ToArray();
Check.That(mappings2).HasSize(1);
Check.That(mappings2.First().Guid).Equals(guid);
Check.That(mappings2.First().Provider).Equals(response2);
}
[Fact]
public async Task FluentMockServer_Admin_Mappings_AtPriority()
{
var _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);
// when
var response = await new HttpClient().GetAsync("http://localhost:" + _server.Ports[0] + "/1");
// then
Check.That((int)response.StatusCode).IsEqualTo(400);
}
[Fact]
public async Task FluentMockServer_Admin_Requests_Get()
{
// given
var _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();
}
[Fact]
public async Task FluentMockServer_Admin_Logging_SetMaxRequestLogCount()
{
// Assign
var client = new HttpClient();
// Act
var _server = FluentMockServer.Start();
_server.SetMaxRequestLogCount(2);
await client.GetAsync("http://localhost:" + _server.Ports[0] + "/foo1");
await client.GetAsync("http://localhost:" + _server.Ports[0] + "/foo2");
await client.GetAsync("http://localhost:" + _server.Ports[0] + "/foo3");
// Assert
Check.That(_server.LogEntries).HasSize(2);
var requestLoggedA = _server.LogEntries.First();
Check.That(requestLoggedA.RequestMessage.Path).EndsWith("/foo2");
var requestLoggedB = _server.LogEntries.Last();
Check.That(requestLoggedB.RequestMessage.Path).EndsWith("/foo3");
}
}
}

View File

@@ -1,10 +1,10 @@
using System;
using NFluent;
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using NFluent;
using WireMock.RequestBuilders;
using WireMock.ResponseBuilders;
using WireMock.Server;
@@ -13,52 +13,60 @@ using Xunit;
namespace WireMock.Net.Tests
{
public partial class FluentMockServerTests
public class FluentMockServerProxyTests
{
private FluentMockServer _serverForProxyForwarding;
#if NET452
[Fact]
public async Task FluentMockServer_Proxy_Should_proxy_responses()
{
// given
_server = FluentMockServer.Start();
_server
.Given(Request.Create().WithPath("/*"))
// Assign
string path = $"/prx_{Guid.NewGuid().ToString()}";
var server = FluentMockServer.Start();
server
.Given(Request.Create().WithPath(path))
.RespondWith(Response.Create().WithProxy("http://www.google.com"));
// when
var result = await new HttpClient().GetStringAsync("http://localhost:" + _server.Ports[0] + "/search?q=test");
// Act
var requestMessage = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri($"{server.Urls[0]}{path}")
};
var httpClientHandler = new HttpClientHandler { AllowAutoRedirect = false };
var response = await new HttpClient(httpClientHandler).SendAsync(requestMessage);
string content = await response.Content.ReadAsStringAsync();
// then
Check.That(_server.Mappings).HasSize(1);
Check.That(result).Contains("google");
// Assert
Check.That(server.Mappings).HasSize(1);
Check.That(content).Contains("google");
}
[Fact]
public async Task FluentMockServer_Proxy_Should_preserve_content_header_in_proxied_request()
{
// given
_serverForProxyForwarding = FluentMockServer.Start();
_serverForProxyForwarding
.Given(Request.Create().WithPath("/*"))
// Assign
string path = $"/prx_{Guid.NewGuid().ToString()}";
var serverForProxyForwarding = FluentMockServer.Start();
serverForProxyForwarding
.Given(Request.Create().WithPath(path))
.RespondWith(Response.Create());
var settings = new FluentMockServerSettings
{
ProxyAndRecordSettings = new ProxyAndRecordSettings
{
Url = _serverForProxyForwarding.Urls[0],
Url = serverForProxyForwarding.Urls[0],
SaveMapping = true,
SaveMappingToFile = false
}
};
_server = FluentMockServer.Start(settings);
var server = FluentMockServer.Start(settings);
// when
var requestMessage = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri(_server.Urls[0]),
RequestUri = new Uri($"{server.Urls[0]}{path}"),
Content = new StringContent("stringContent")
};
requestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
@@ -66,14 +74,14 @@ namespace WireMock.Net.Tests
await new HttpClient().SendAsync(requestMessage);
// then
var receivedRequest = _serverForProxyForwarding.LogEntries.First().RequestMessage;
var receivedRequest = serverForProxyForwarding.LogEntries.First().RequestMessage;
Check.That(receivedRequest.Body).IsEqualTo("stringContent");
Check.That(receivedRequest.Headers).ContainsKey("Content-Type");
Check.That(receivedRequest.Headers["Content-Type"].First()).Contains("text/plain");
Check.That(receivedRequest.Headers).ContainsKey("bbb");
// check that new proxied mapping is added
Check.That(_server.Mappings).HasSize(2);
Check.That(server.Mappings).HasSize(2);
//var newMapping = _server.Mappings.First(m => m.Guid != guid);
//var matcher = ((Request)newMapping.RequestMatcher).GetRequestMessageMatchers<RequestMessageHeaderMatcher>().FirstOrDefault(m => m.Name == "bbb");
@@ -84,31 +92,29 @@ namespace WireMock.Net.Tests
public async Task FluentMockServer_Proxy_Should_exclude_blacklisted_content_header_in_mapping()
{
// given
_serverForProxyForwarding = FluentMockServer.Start();
_serverForProxyForwarding
.Given(Request.Create().WithPath("/*"))
string path = $"/prx_{Guid.NewGuid().ToString()}";
var serverForProxyForwarding = FluentMockServer.Start();
serverForProxyForwarding
.Given(Request.Create().WithPath(path))
.RespondWith(Response.Create());
var settings = new FluentMockServerSettings
{
ProxyAndRecordSettings = new ProxyAndRecordSettings
{
Url = _serverForProxyForwarding.Urls[0],
Url = serverForProxyForwarding.Urls[0],
SaveMapping = true,
SaveMappingToFile = false,
BlackListedHeaders = new[] { "blacklisted" }
}
};
_server = FluentMockServer.Start(settings);
//_server
// .Given(Request.Create().WithPath("/*"))
// .RespondWith(Response.Create());
var server = FluentMockServer.Start(settings);
// when
var requestMessage = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri(_server.Urls[0]),
RequestUri = new Uri($"{server.Urls[0]}{path}"),
Content = new StringContent("stringContent")
};
requestMessage.Headers.Add("blacklisted", "test");
@@ -116,7 +122,7 @@ namespace WireMock.Net.Tests
await new HttpClient().SendAsync(requestMessage);
// then
var receivedRequest = _serverForProxyForwarding.LogEntries.First().RequestMessage;
var receivedRequest = serverForProxyForwarding.LogEntries.First().RequestMessage;
Check.That(receivedRequest.Headers).Not.ContainsKey("bbb");
Check.That(receivedRequest.Headers).ContainsKey("ok");
@@ -128,29 +134,30 @@ namespace WireMock.Net.Tests
[Fact]
public async Task FluentMockServer_Proxy_Should_preserve_content_header_in_proxied_request_with_empty_content()
{
// given
_serverForProxyForwarding = FluentMockServer.Start();
_serverForProxyForwarding
.Given(Request.Create().WithPath("/*"))
// Assign
string path = $"/prx_{Guid.NewGuid().ToString()}";
var serverForProxyForwarding = FluentMockServer.Start();
serverForProxyForwarding
.Given(Request.Create().WithPath(path))
.RespondWith(Response.Create());
_server = FluentMockServer.Start();
_server
var server = FluentMockServer.Start();
server
.Given(Request.Create().WithPath("/*"))
.RespondWith(Response.Create().WithProxy(_serverForProxyForwarding.Urls[0]));
.RespondWith(Response.Create().WithProxy(serverForProxyForwarding.Urls[0]));
// when
// Act
var requestMessage = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri(_server.Urls[0]),
RequestUri = new Uri($"{server.Urls[0]}{path}"),
Content = new StringContent("")
};
requestMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
await new HttpClient().SendAsync(requestMessage);
// then
var receivedRequest = _serverForProxyForwarding.LogEntries.First().RequestMessage;
// Assert
var receivedRequest = serverForProxyForwarding.LogEntries.First().RequestMessage;
Check.That(receivedRequest.Body).IsEqualTo("");
Check.That(receivedRequest.Headers).ContainsKey("Content-Type");
Check.That(receivedRequest.Headers["Content-Type"].First()).Contains("text/plain");
@@ -159,28 +166,29 @@ namespace WireMock.Net.Tests
[Fact]
public async Task FluentMockServer_Proxy_Should_preserve_content_header_in_proxied_response()
{
// given
_serverForProxyForwarding = FluentMockServer.Start();
_serverForProxyForwarding
.Given(Request.Create().WithPath("/*"))
// Assign
string path = $"/prx_{Guid.NewGuid().ToString()}";
var serverForProxyForwarding = FluentMockServer.Start();
serverForProxyForwarding
.Given(Request.Create().WithPath(path))
.RespondWith(Response.Create()
.WithBody("body")
.WithHeader("Content-Type", "text/plain"));
_server = FluentMockServer.Start();
_server
.Given(Request.Create().WithPath("/*"))
.RespondWith(Response.Create().WithProxy(_serverForProxyForwarding.Urls[0]));
var server = FluentMockServer.Start();
server
.Given(Request.Create().WithPath(path))
.RespondWith(Response.Create().WithProxy(serverForProxyForwarding.Urls[0]));
// when
// Act
var requestMessage = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri(_server.Urls[0])
RequestUri = new Uri($"{server.Urls[0]}{path}")
};
var response = await new HttpClient().SendAsync(requestMessage);
// then
// Assert
Check.That(await response.Content.ReadAsStringAsync()).IsEqualTo("body");
Check.That(response.Content.Headers.Contains("Content-Type")).IsTrue();
Check.That(response.Content.Headers.GetValues("Content-Type")).ContainsExactly("text/plain");
@@ -190,49 +198,52 @@ namespace WireMock.Net.Tests
public async Task FluentMockServer_Proxy_Should_change_absolute_location_header_in_proxied_response()
{
// Assign
string path = $"/prx_{Guid.NewGuid().ToString()}";
var settings = new FluentMockServerSettings { AllowPartialMapping = false };
_serverForProxyForwarding = FluentMockServer.Start(settings);
_serverForProxyForwarding
.Given(Request.Create().WithPath("/*"))
var serverForProxyForwarding = FluentMockServer.Start(settings);
serverForProxyForwarding
.Given(Request.Create().WithPath(path))
.RespondWith(Response.Create()
.WithStatusCode(HttpStatusCode.Redirect)
.WithHeader("Location", _serverForProxyForwarding.Urls[0] + "testpath"));
.WithHeader("Location", "/testpath"));
_server = FluentMockServer.Start(settings);
_server
.Given(Request.Create().WithPath("/prx"))
.RespondWith(Response.Create().WithProxy(_serverForProxyForwarding.Urls[0]));
var server = FluentMockServer.Start(settings);
server
.Given(Request.Create().WithPath(path).UsingAnyMethod())
.RespondWith(Response.Create().WithProxy(serverForProxyForwarding.Urls[0]));
// Act
var requestMessage = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri(_server.Urls[0] + "/prx")
RequestUri = new Uri($"{server.Urls[0]}{path}")
};
var httpClientHandler = new HttpClientHandler { AllowAutoRedirect = false };
var response = await new HttpClient(httpClientHandler).SendAsync(requestMessage);
// Assert
Check.That(response.Headers.Contains("Location")).IsTrue();
Check.That(response.Headers.GetValues("Location")).ContainsExactly(_server.Urls[0] + "testpath");
Check.That(response.Headers.GetValues("Location")).ContainsExactly("/testpath");
}
[Fact]
public async Task FluentMockServer_Proxy_Should_preserve_cookie_header_in_proxied_request()
{
// given
_serverForProxyForwarding = FluentMockServer.Start();
_serverForProxyForwarding
.Given(Request.Create().WithPath("/*"))
// Assign
string path = $"/prx_{Guid.NewGuid().ToString()}";
var serverForProxyForwarding = FluentMockServer.Start();
serverForProxyForwarding
.Given(Request.Create().WithPath(path))
.RespondWith(Response.Create());
_server = FluentMockServer.Start();
_server
.Given(Request.Create().WithPath("/*"))
.RespondWith(Response.Create().WithProxy(_serverForProxyForwarding.Urls[0]));
var server = FluentMockServer.Start();
server
.Given(Request.Create().WithPath(path))
.RespondWith(Response.Create().WithProxy(serverForProxyForwarding.Urls[0]));
// when
var requestUri = new Uri(_server.Urls[0]);
// Act
var requestUri = new Uri($"{server.Urls[0]}{path}");
var requestMessage = new HttpRequestMessage
{
Method = HttpMethod.Get,
@@ -243,7 +254,7 @@ namespace WireMock.Net.Tests
await new HttpClient(clientHandler).SendAsync(requestMessage);
// then
var receivedRequest = _serverForProxyForwarding.LogEntries.First().RequestMessage;
var receivedRequest = serverForProxyForwarding.LogEntries.First().RequestMessage;
Check.That(receivedRequest.Cookies).IsNotNull();
Check.That(receivedRequest.Cookies).ContainsPair("name", "value");
}
@@ -252,23 +263,24 @@ namespace WireMock.Net.Tests
public async Task FluentMockServer_Proxy_Should_set_BodyAsJson_in_proxied_response()
{
// Assign
_serverForProxyForwarding = FluentMockServer.Start();
_serverForProxyForwarding
.Given(Request.Create().WithPath("/*"))
string path = $"/prx_{Guid.NewGuid().ToString()}";
var serverForProxyForwarding = FluentMockServer.Start();
serverForProxyForwarding
.Given(Request.Create().WithPath(path))
.RespondWith(Response.Create()
.WithBodyAsJson(new { i = 42 })
.WithHeader("Content-Type", "application/json; charset=utf-8"));
_server = FluentMockServer.Start();
_server
.Given(Request.Create().WithPath("/*"))
.RespondWith(Response.Create().WithProxy(_serverForProxyForwarding.Urls[0]));
var server = FluentMockServer.Start();
server
.Given(Request.Create().WithPath(path))
.RespondWith(Response.Create().WithProxy(serverForProxyForwarding.Urls[0]));
// Act
var requestMessage = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri(_server.Urls[0])
RequestUri = new Uri($"{server.Urls[0]}{path}")
};
var response = await new HttpClient().SendAsync(requestMessage);
@@ -277,5 +289,7 @@ namespace WireMock.Net.Tests
Check.That(content).IsEqualTo("{\"i\":42}");
Check.That(response.Content.Headers.GetValues("Content-Type")).ContainsExactly("application/json; charset=utf-8");
}
#endif
}
}

View File

@@ -1,303 +1,30 @@
using System;
using NFluent;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Moq;
using NFluent;
using WireMock.Matchers;
using WireMock.RequestBuilders;
using WireMock.ResponseBuilders;
using WireMock.Server;
using Xunit;
using Newtonsoft.Json;
using WireMock.Handlers;
using WireMock.Logging;
using WireMock.Settings;
using WireMock.Admin.Mappings;
namespace WireMock.Net.Tests
{
public partial class FluentMockServerTests : IDisposable
public class FluentMockServerTests
{
private FluentMockServer _server;
private static string jsonRequestMessage = @"{ ""message"" : ""Hello server"" }";
// For for AppVeyor + OpenCover
private string GetCurrentFolder()
{
string current = Directory.GetCurrentDirectory();
//if (!current.EndsWith("WireMock.Net.Tests"))
// return Path.Combine(current, "test", "WireMock.Net.Tests");
return current;
}
[Fact]
public void FluentMockServer_StartStop()
{
var server1 = FluentMockServer.Start("http://localhost:9091/");
server1.Stop();
var server2 = FluentMockServer.Start("http://localhost:9091/");
server2.Stop();
}
[Fact]
public void FluentMockServer_SaveStaticMappings()
{
// Assign
string guid = "791a3f31-6946-aaaa-8e6f-0237c7441111";
var _staticMappingHandlerMock = new Mock<IFileSystemHandler>();
_staticMappingHandlerMock.Setup(m => m.GetMappingFolder()).Returns("folder");
_staticMappingHandlerMock.Setup(m => m.FolderExists(It.IsAny<string>())).Returns(true);
_staticMappingHandlerMock.Setup(m => m.WriteMappingFile(It.IsAny<string>(), It.IsAny<string>()));
_server = FluentMockServer.Start(new FluentMockServerSettings
{
FileSystemHandler = _staticMappingHandlerMock.Object
});
_server
.Given(Request.Create().WithPath($"/foo_{Guid.NewGuid()}"))
.WithGuid(guid)
.RespondWith(Response.Create().WithBody("save test"));
// Act
_server.SaveStaticMappings();
// Assert and Verify
_staticMappingHandlerMock.Verify(m => m.GetMappingFolder(), Times.Once);
_staticMappingHandlerMock.Verify(m => m.FolderExists("folder"), Times.Once);
_staticMappingHandlerMock.Verify(m => m.WriteMappingFile(Path.Combine("folder", guid + ".json"), It.IsAny<string>()), Times.Once);
}
[Fact]
public void FluentMockServer_ReadStaticMapping_WithNonGuidFilename()
{
var guid = Guid.Parse("04ee4872-9efd-4770-90d3-88d445265d0d");
string title = "documentdb_root_title";
_server = FluentMockServer.Start();
string folder = Path.Combine(GetCurrentFolder(), "__admin", "mappings", "documentdb_root.json");
_server.ReadStaticMappingAndAddOrUpdate(folder);
var mappings = _server.Mappings.ToArray();
Check.That(mappings).HasSize(1);
Check.That(mappings.First().RequestMatcher).IsNotNull();
Check.That(mappings.First().Provider).IsNotNull();
Check.That(mappings.First().Guid).Equals(guid);
Check.That(mappings.First().Title).Equals(title);
}
[Fact]
public void FluentMockServer_ReadStaticMapping_WithGuidFilename()
{
string guid = "00000002-ee28-4f29-ae63-1ac9b0802d86";
_server = FluentMockServer.Start();
string folder = Path.Combine(GetCurrentFolder(), "__admin", "mappings", guid + ".json");
_server.ReadStaticMappingAndAddOrUpdate(folder);
var mappings = _server.Mappings.ToArray();
Check.That(mappings).HasSize(1);
Check.That(mappings.First().RequestMatcher).IsNotNull();
Check.That(mappings.First().Provider).IsNotNull();
Check.That(mappings.First().Guid).Equals(Guid.Parse(guid));
Check.That(mappings.First().Title).IsNullOrEmpty();
}
[Fact]
public void FluentMockServer_ReadStaticMapping_WithResponseBodyFromFile()
{
string guid = "00000002-ee28-4f29-ae63-1ac9b0802d87";
string folder = Path.Combine(GetCurrentFolder(), "__admin", "mappings", guid + ".json");
string json = File.ReadAllText(folder);
string responseBodyFilePath = Path.Combine(GetCurrentFolder(), "responsebody.json");
dynamic jsonObj = JsonConvert.DeserializeObject(json);
jsonObj["Response"]["BodyAsFile"] = responseBodyFilePath;
string output = JsonConvert.SerializeObject(jsonObj, Formatting.Indented);
File.WriteAllText(folder, output);
_server = FluentMockServer.Start();
_server.ReadStaticMappingAndAddOrUpdate(folder);
var mappings = _server.Mappings.ToArray();
Check.That(mappings).HasSize(1);
Check.That(mappings.First().RequestMatcher).IsNotNull();
Check.That(mappings.First().Provider).IsNotNull();
Check.That(mappings.First().Guid).Equals(Guid.Parse(guid));
Check.That(mappings.First().Title).IsNullOrEmpty();
}
[Fact]
public void FluentMockServer_ReadStaticMappings_FolderExistsIsTrue()
{
// Assign
var _staticMappingHandlerMock = new Mock<IFileSystemHandler>();
_staticMappingHandlerMock.Setup(m => m.GetMappingFolder()).Returns("folder");
_staticMappingHandlerMock.Setup(m => m.FolderExists(It.IsAny<string>())).Returns(true);
_staticMappingHandlerMock.Setup(m => m.EnumerateFiles(It.IsAny<string>())).Returns(new string[0]);
_server = FluentMockServer.Start(new FluentMockServerSettings
{
FileSystemHandler = _staticMappingHandlerMock.Object
});
// Act
_server.ReadStaticMappings();
// Assert and Verify
_staticMappingHandlerMock.Verify(m => m.GetMappingFolder(), Times.Once);
_staticMappingHandlerMock.Verify(m => m.FolderExists("folder"), Times.Once);
_staticMappingHandlerMock.Verify(m => m.EnumerateFiles("folder"), Times.Once);
}
[Fact]
public void FluentMockServer_ReadStaticMappingAndAddOrUpdate()
{
// Assign
string mapping = "{\"Request\": {\"Path\": {\"Matchers\": [{\"Name\": \"WildcardMatcher\",\"Pattern\": \"/static/mapping\"}]},\"Methods\": [\"get\"]},\"Response\": {\"BodyAsJson\": { \"body\": \"static mapping\" }}}";
var _staticMappingHandlerMock = new Mock<IFileSystemHandler>();
_staticMappingHandlerMock.Setup(m => m.ReadMappingFile(It.IsAny<string>())).Returns(mapping);
_server = FluentMockServer.Start(new FluentMockServerSettings
{
FileSystemHandler = _staticMappingHandlerMock.Object
});
// Act
_server.ReadStaticMappingAndAddOrUpdate(@"c:\test.json");
// Assert and Verify
_staticMappingHandlerMock.Verify(m => m.ReadMappingFile(@"c:\test.json"), Times.Once);
}
[Fact]
public void FluentMockServer_ReadStaticMappings()
{
_server = FluentMockServer.Start();
string folder = Path.Combine(GetCurrentFolder(), "__admin", "mappings");
_server.ReadStaticMappings(folder);
var mappings = _server.Mappings.ToArray();
Check.That(mappings).HasSize(3);
}
[Fact]
public void FluentMockServer_Admin_Mappings_WithGuid_Get()
{
Guid 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);
}
[Fact]
public void FluentMockServer_Admin_Mappings_WithGuidAsString_Get()
{
string guid = "90356dba-b36c-469a-a17e-669cd84f1f05";
_server = FluentMockServer.Start();
_server.Given(Request.Create().WithPath("/foo100").UsingGet()).WithGuid(guid)
.RespondWith(Response.Create().WithStatusCode(201).WithBody("1"));
var mappings = _server.Mappings.ToArray();
Check.That(mappings).HasSize(1);
}
[Fact]
public void FluentMockServer_Admin_Mappings_Add_SameGuid()
{
var guid = Guid.Parse("90356dba-b36c-469a-a17e-669cd84f1f05");
_server = FluentMockServer.Start();
var response1 = Response.Create().WithStatusCode(500);
_server.Given(Request.Create().UsingGet())
.WithGuid(guid)
.RespondWith(response1);
var mappings1 = _server.Mappings.ToArray();
Check.That(mappings1).HasSize(1);
Check.That(mappings1.First().Guid).Equals(guid);
var response2 = Response.Create().WithStatusCode(400);
_server.Given(Request.Create().WithPath("/2").UsingGet())
.WithGuid(guid)
.RespondWith(response2);
var mappings2 = _server.Mappings.ToArray();
Check.That(mappings2).HasSize(1);
Check.That(mappings2.First().Guid).Equals(guid);
Check.That(mappings2.First().Provider).Equals(response2);
}
[Fact]
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);
// when
var response = await new HttpClient().GetAsync("http://localhost:" + _server.Ports[0] + "/1");
// then
Check.That((int)response.StatusCode).IsEqualTo(400);
}
[Fact]
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();
}
[Fact]
public async Task FluentMockServer_Should_respond_to_request_methodPatch()
{
// given
string path = $"/foo_{Guid.NewGuid()}";
_server = FluentMockServer.Start();
var _server = FluentMockServer.Start();
_server.Given(Request.Create().WithPath(path).UsingMethod("patch"))
.RespondWith(Response.Create().WithBody("hello patch"));
@@ -325,7 +52,7 @@ namespace WireMock.Net.Tests
public async Task FluentMockServer_Should_respond_to_request_bodyAsString()
{
// given
_server = FluentMockServer.Start();
var _server = FluentMockServer.Start();
_server
.Given(Request.Create()
@@ -346,7 +73,7 @@ namespace WireMock.Net.Tests
public async Task FluentMockServer_Should_respond_to_request_BodyAsJson()
{
// Assign
_server = FluentMockServer.Start();
var _server = FluentMockServer.Start();
_server
.Given(Request.Create().UsingAnyMethod())
@@ -363,7 +90,7 @@ namespace WireMock.Net.Tests
public async Task FluentMockServer_Should_respond_to_request_BodyAsJson_Indented()
{
// Assign
_server = FluentMockServer.Start();
var _server = FluentMockServer.Start();
_server
.Given(Request.Create().UsingAnyMethod())
@@ -380,7 +107,7 @@ namespace WireMock.Net.Tests
public async Task FluentMockServer_Should_respond_to_request_bodyAsCallback()
{
// given
_server = FluentMockServer.Start();
var _server = FluentMockServer.Start();
_server
.Given(Request.Create()
@@ -401,7 +128,7 @@ namespace WireMock.Net.Tests
public async Task FluentMockServer_Should_respond_to_request_bodyAsBase64()
{
// given
_server = FluentMockServer.Start();
var _server = FluentMockServer.Start();
_server.Given(Request.Create().WithPath("/foo").UsingGet()).RespondWith(Response.Create().WithBodyFromBase64("SGVsbG8gV29ybGQ/"));
@@ -417,7 +144,7 @@ namespace WireMock.Net.Tests
{
// given
string path = $"/foo_{Guid.NewGuid()}";
_server = FluentMockServer.Start();
var _server = FluentMockServer.Start();
_server.Given(Request.Create().WithPath(path).UsingGet()).RespondWith(Response.Create().WithBody(new byte[] { 48, 49 }));
@@ -446,7 +173,7 @@ namespace WireMock.Net.Tests
new object[] { new JsonPathMatcher("$..[?(@.message == 'Hello server')]"), "text/plain" }
};
_server = FluentMockServer.Start();
var _server = FluentMockServer.Start();
foreach (var item in validMatchersForHelloServerJsonMessage)
{
@@ -473,7 +200,7 @@ namespace WireMock.Net.Tests
{
// given
string path = $"/foo{Guid.NewGuid()}";
_server = FluentMockServer.Start();
var _server = FluentMockServer.Start();
// when
var response = await new HttpClient().GetAsync("http://localhost:" + _server.Ports[0] + path);
@@ -488,7 +215,7 @@ namespace WireMock.Net.Tests
{
// Assign
string path = $"/bar_{Guid.NewGuid()}";
_server = FluentMockServer.Start();
var _server = FluentMockServer.Start();
// when
await new HttpClient().GetAsync("http://localhost:" + _server.Ports[0] + "/foo");
@@ -507,7 +234,7 @@ namespace WireMock.Net.Tests
public async Task FluentMockServer_Should_reset_requestlogs()
{
// given
_server = FluentMockServer.Start();
var _server = FluentMockServer.Start();
// when
await new HttpClient().GetAsync("http://localhost:" + _server.Ports[0] + "/foo");
@@ -522,7 +249,7 @@ namespace WireMock.Net.Tests
{
// given
string path = $"/foo_{Guid.NewGuid()}";
_server = FluentMockServer.Start();
var _server = FluentMockServer.Start();
_server
.Given(Request.Create()
@@ -547,7 +274,7 @@ namespace WireMock.Net.Tests
string path = $"/foo_{Guid.NewGuid()}";
string pathToRedirect = $"/bar_{Guid.NewGuid()}";
_server = FluentMockServer.Start();
var _server = FluentMockServer.Start();
_server
.Given(Request.Create()
@@ -575,7 +302,7 @@ namespace WireMock.Net.Tests
public async Task FluentMockServer_Should_delay_responses_for_a_given_route()
{
// given
_server = FluentMockServer.Start();
var _server = FluentMockServer.Start();
_server
.Given(Request.Create()
@@ -598,7 +325,7 @@ namespace WireMock.Net.Tests
public async Task FluentMockServer_Should_delay_responses()
{
// given
_server = FluentMockServer.Start();
var _server = FluentMockServer.Start();
_server.AddGlobalProcessingDelay(TimeSpan.FromMilliseconds(200));
_server
.Given(Request.Create().WithPath("/*"))
@@ -619,7 +346,7 @@ namespace WireMock.Net.Tests
//public async Task Should_proxy_responses_with_client_certificate()
//{
// // given
// _server = FluentMockServer.Start();
// var _server = FluentMockServer.Start();
// _server
// .Given(Request.Create().WithPath("/*"))
// .RespondWith(Response.Create().WithProxy("https://server-that-expects-a-client-certificate", @"\\yourclientcertificatecontainingprivatekey.pfx", "yourclientcertificatepassword"));
@@ -631,34 +358,11 @@ namespace WireMock.Net.Tests
// Check.That(result).Contains("google");
//}
[Fact]
public async Task FluentMockServer_Logging_SetMaxRequestLogCount()
{
// Assign
var client = new HttpClient();
// Act
_server = FluentMockServer.Start();
_server.SetMaxRequestLogCount(2);
await client.GetAsync("http://localhost:" + _server.Ports[0] + "/foo1");
await client.GetAsync("http://localhost:" + _server.Ports[0] + "/foo2");
await client.GetAsync("http://localhost:" + _server.Ports[0] + "/foo3");
// Assert
Check.That(_server.LogEntries).HasSize(2);
var requestLoggedA = _server.LogEntries.First();
Check.That(requestLoggedA.RequestMessage.Path).EndsWith("/foo2");
var requestLoggedB = _server.LogEntries.Last();
Check.That(requestLoggedB.RequestMessage.Path).EndsWith("/foo3");
}
[Fact]
public async Task FluentMockServer_Should_respond_to_request_callback()
{
// Assign
_server = FluentMockServer.Start();
var _server = FluentMockServer.Start();
_server
.Given(Request.Create().WithPath("/foo").UsingGet())
@@ -671,27 +375,25 @@ namespace WireMock.Net.Tests
Check.That(response).IsEqualTo("/fooBar");
}
#if !NET452
[Fact]
public async Task FluentMockServer_Should_exclude_restrictedResponseHeader_for_IOwinResponse()
public async Task FluentMockServer_Should_not_exclude_restrictedResponseHeader_for_ASPNETCORE()
{
_server = FluentMockServer.Start();
// Assign
string path = $"/foo_{Guid.NewGuid()}";
var _server = FluentMockServer.Start();
_server
.Given(Request.Create().WithPath("/foo").UsingGet())
.RespondWith(Response.Create().WithHeader("Keep-Alive", "").WithHeader("test", ""));
.Given(Request.Create().WithPath(path).UsingGet())
.RespondWith(Response.Create().WithHeader("Keep-Alive", "k").WithHeader("test", "t"));
// Act
var response = await new HttpClient().GetAsync("http://localhost:" + _server.Ports[0] + "/foo");
var response = await new HttpClient().GetAsync("http://localhost:" + _server.Ports[0] + path);
// Assert
Check.That(response.Headers.Contains("test")).IsTrue();
Check.That(response.Headers.Contains("Keep-Alive")).IsFalse();
}
public void Dispose()
{
_server?.Stop();
_serverForProxyForwarding?.Stop();
Check.That(response.Headers.Contains("Keep-Alive")).IsTrue();
}
#endif
}
}
}

View File

@@ -0,0 +1,37 @@
using System;
using System.IO;
using NFluent;
using WireMock.Handlers;
using Xunit;
namespace WireMock.Net.Tests.Handlers
{
public class LocalFileSystemHandlerTests
{
private LocalFileSystemHandler sut = new LocalFileSystemHandler();
[Fact]
public void LocalFileSystemHandler_GetMappingFolder()
{
// Act
string result = sut.GetMappingFolder();
// Assert
Check.That(result).EndsWith(Path.Combine("__admin", "mappings"));
}
[Fact]
public void LocalFileSystemHandler_CreateFolder_Throws()
{
// Act
Check.ThatCode(() => sut.CreateFolder(null)).Throws<ArgumentNullException>();
}
[Fact]
public void LocalFileSystemHandler_WriteMappingFile_Throws()
{
// Act
Check.ThatCode(() => sut.WriteMappingFile(null, null)).Throws<ArgumentNullException>();
}
}
}

View File

@@ -13,28 +13,27 @@ using Xunit;
namespace WireMock.Net.Tests
{
public class ObservableLogEntriesTest : IDisposable
public class ObservableLogEntriesTest
{
private FluentMockServer _server;
[Fact]
public async void FluentMockServer_LogEntriesChanged()
{
// Assign
_server = FluentMockServer.Start();
string path = $"/log_{Guid.NewGuid()}";
var server = FluentMockServer.Start();
_server
server
.Given(Request.Create()
.WithPath("/foo")
.WithPath(path)
.UsingGet())
.RespondWith(Response.Create()
.WithBody(@"{ msg: ""Hello world!""}"));
int count = 0;
_server.LogEntriesChanged += (sender, args) => count++;
server.LogEntriesChanged += (sender, args) => count++;
// Act
await new HttpClient().GetAsync("http://localhost:" + _server.Ports[0] + "/foo");
await new HttpClient().GetAsync($"http://localhost:{server.Ports[0]}{path}");
// Assert
Check.That(count).Equals(1);
@@ -46,18 +45,18 @@ namespace WireMock.Net.Tests
int expectedCount = 10;
// Assign
_server = FluentMockServer.Start();
string path = $"/log_p_{Guid.NewGuid()}";
var server = FluentMockServer.Start();
_server
server
.Given(Request.Create()
.WithPath("/foo")
.WithPath(path)
.UsingGet())
.RespondWith(Response.Create()
.WithDelay(6)
.WithSuccess());
int count = 0;
_server.LogEntriesChanged += (sender, args) => count++;
server.LogEntriesChanged += (sender, args) => count++;
var http = new HttpClient();
@@ -65,8 +64,8 @@ namespace WireMock.Net.Tests
var listOfTasks = new List<Task<HttpResponseMessage>>();
for (var i = 0; i < expectedCount; i++)
{
Thread.Sleep(100);
listOfTasks.Add(http.GetAsync($"{_server.Urls[0]}/foo"));
Thread.Sleep(10);
listOfTasks.Add(http.GetAsync($"{server.Urls[0]}{path}"));
}
var responses = await Task.WhenAll(listOfTasks);
var countResponsesWithStatusNotOk = responses.Count(r => r.StatusCode != HttpStatusCode.OK);
@@ -75,10 +74,5 @@ namespace WireMock.Net.Tests
Check.That(countResponsesWithStatusNotOk).Equals(0);
Check.That(count).Equals(expectedCount);
}
public void Dispose()
{
_server?.Dispose();
}
}
}

View File

@@ -14,6 +14,36 @@ namespace WireMock.Net.Tests
{
private const string ClientIp = "::1";
// [Fact] : TODO : this test fails???
public void Request_WithPath_EncodedSpaces()
{
// Assign
var spec = Request.Create().WithPath("/path/a%20b").UsingAnyMethod();
// when
var body = new BodyData();
var request = new RequestMessage(new UrlDetails("http://localhost/path/a%20b"), "GET", ClientIp, body);
// then
var requestMatchResult = new RequestMatchResult();
Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0);
}
[Fact]
public void Request_WithPath_Spaces()
{
// Assign
var spec = Request.Create().WithPath("/path/a b").UsingAnyMethod();
// when
var body = new BodyData();
var request = new RequestMessage(new UrlDetails("http://localhost/path/a b"), "GET", ClientIp, body);
// then
var requestMatchResult = new RequestMatchResult();
Check.That(spec.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0);
}
[Fact]
public void Request_WithPath_WithHeader_Match()
{

View File

@@ -2,7 +2,11 @@
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
#if NET452
using Microsoft.Owin;
#else
using Microsoft.AspNetCore.Http;
#endif
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NFluent;
@@ -18,7 +22,7 @@ namespace WireMock.Net.Tests.ResponseBuilderTests
private const string ClientIp = "::1";
[Fact]
public async Task Response_ProvideResponse_Handlebars_WithBodyAsJson()
public async Task Response_ProvideResponse_Handlebars_WithBodyAsJson_ResultAsObject()
{
// Assign
string jsonString = "{ \"things\": [ { \"name\": \"RequiredThing\" }, { \"name\": \"Wiremock\" } ] }";
@@ -27,17 +31,17 @@ namespace WireMock.Net.Tests.ResponseBuilderTests
BodyAsJson = JsonConvert.DeserializeObject(jsonString),
Encoding = Encoding.UTF8
};
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POST", ClientIp, bodyData);
var request = new RequestMessage(new UrlDetails("http://localhost/foo_object"), "POST", ClientIp, bodyData);
var response = Response.Create()
.WithBodyAsJson(new { x = "test {{request.url}}" })
.WithBodyAsJson(new { x = "test {{request.path}}" })
.WithTransformer();
// Act
var responseMessage = await response.ProvideResponseAsync(request);
// Assert
Check.That(JsonConvert.SerializeObject(responseMessage.BodyAsJson)).Equals("{\"x\":\"test http://localhost/foo\"}");
Check.That(JsonConvert.SerializeObject(responseMessage.BodyAsJson)).Equals("{\"x\":\"test /foo_object\"}");
}
[Fact]

View File

@@ -31,8 +31,6 @@ namespace WireMock.Net.Tests
// then
Check.That(response.StatusCode).IsEqualTo(HttpStatusCode.NotFound);
server.Dispose();
}
[Fact]
@@ -61,8 +59,6 @@ namespace WireMock.Net.Tests
// then
Check.That(responseNoState).Equals("No state msg");
Check.That(responseWithState).Equals("Test state msg");
server.Dispose();
}
[Fact]
@@ -117,8 +113,6 @@ namespace WireMock.Net.Tests
Check.That(server.Scenarios["To do list"].NextState).IsNull();
Check.That(server.Scenarios["To do list"].Started).IsTrue();
Check.That(server.Scenarios["To do list"].Finished).IsTrue();
server.Dispose();
}
[Fact]
@@ -164,8 +158,6 @@ namespace WireMock.Net.Tests
var responseWithState2 = await new HttpClient().GetStringAsync(url + "/foo2X");
Check.That(responseWithState2).Equals("Test state msg 2");
server.Dispose();
}
}
}

View File

@@ -1,5 +1,9 @@
using System;
#if NET452
using Microsoft.Owin;
#else
using Microsoft.AspNetCore.Http;
#endif
using NFluent;
using WireMock.Util;
using Xunit;

View File

@@ -2,7 +2,7 @@
<PropertyGroup>
<Authors>Stef Heyenrath</Authors>
<TargetFramework>net452</TargetFramework>
<TargetFrameworks>net452;netcoreapp2.1</TargetFrameworks>
<DebugType>full</DebugType>
<AssemblyName>WireMock.Net.Tests</AssemblyName>
<PackageId>WireMock.Net.Tests</PackageId>
@@ -16,19 +16,23 @@
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.3.0" />
<PackageReference Include="Microsoft.Owin.Host.HttpListener" Version="3.1.0" />
<PackageReference Include="Moq" Version="4.8.3" />
<PackageReference Include="Newtonsoft.Json" Version="10.0.3" />
<PackageReference Include="Newtonsoft.Json" Version="11.0.2" />
<PackageReference Include="NFluent" Version="2.2.0" />
<PackageReference Include="OpenCover" Version="4.6.519" />
<PackageReference Include="ReportGenerator" Version="3.1.2" />
<PackageReference Include="SimMetrics.Net" Version="1.0.4" />
<PackageReference Include="System.Threading" Version="4.3.0" />
<PackageReference Include="xunit" Version="2.3.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.3.1" />
<PackageReference Include="xunit" Version="2.4.0" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.0" />
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'net452' ">
<ItemGroup Condition="'$(TargetFramework)' == 'net452'">
<PackageReference Include="Microsoft.Owin.Host.HttpListener" Version="3.1.0" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net462'">
<PackageReference Include="Microsoft.AspNetCore" Version="2.1.2" />
</ItemGroup>
<ItemGroup>