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

@@ -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>