From 6c16d45256215fd2c9161f758bd55f971dd170ac Mon Sep 17 00:00:00 2001 From: Stef Heyenrath Date: Fri, 20 Jan 2017 17:52:49 +0100 Subject: [PATCH] Add unit test for Response Handlebars --- .runsettings | 27 ++++++++++ README.md | 50 +++++++++---------- WireMock.Net Solution.sln | 1 + src/WireMock/HttpListenerRequestMapper.cs | 27 ++-------- .../Request/RequestMessageBodyMatcher.cs | 8 +-- .../RequestBuilders/IAndPathRequestBuilder.cs | 5 +- src/WireMock/RequestBuilders/Request.cs | 3 +- src/WireMock/RequestMessage.cs | 42 ++++++---------- src/WireMock/Validation/Check.cs | 2 + src/WireMock/Validation/CoreStrings.cs | 2 + .../FluentMockServerTests.cs | 2 +- .../HttpListenerRequestMapperTests.cs | 19 +------ .../HttpListenerResponseMapperTests.cs | 21 +------- test/WireMock.Net.Tests/RequestTests.cs | 2 +- test/WireMock.Net.Tests/ResponseTests.cs | 50 +++++++++++++++++++ .../WireMock.Net.Tests.csproj | 1 + 16 files changed, 141 insertions(+), 121 deletions(-) create mode 100644 .runsettings create mode 100644 test/WireMock.Net.Tests/ResponseTests.cs diff --git a/.runsettings b/.runsettings new file mode 100644 index 00000000..93a47338 --- /dev/null +++ b/.runsettings @@ -0,0 +1,27 @@ + + + + + + + + + + .*\.dll$ + + + .*\.tests.dll + + + True + True + True + False + + + + + + \ No newline at end of file diff --git a/README.md b/README.md index af106c41..3f1b98b7 100644 --- a/README.md +++ b/README.md @@ -25,10 +25,10 @@ The following code will configure a response with a status of 200 to be returned var server = FluentMockServer.Start(); server .Given( - Request.WithUrl("/some/thing").UsingGet() + Request.Create().WithUrl("/some/thing").UsingGet() ) .RespondWith( - Response + Response.Create() .WithStatusCode(200) .WithHeader("Content-Type", "text/plain") .WithBody("Hello world!") @@ -42,10 +42,10 @@ A response body in binary format can be specified as a `byte[]` via an overloade var server = FluentMockServer.Start(); server .Given( - Request.WithUrl("/some/thing").UsingGet() + Request.Create().WithUrl("/some/thing").UsingGet() ) .RespondWith( - Response + Response.Create() .WithBody(new byte[] { 48, 65, 6c, 6c, 6f }) ); ``` @@ -68,10 +68,10 @@ A JSON body will be considered to match a path expression if the expression retu var server = FluentMockServer.Start(); server .Given( - Request.WithUrl("/some/thing").UsingGet() + Request.Create().WithUrl("/some/thing").UsingGet() .WithBody(new JsonPathMatcher("$.things[?(@.name == 'RequiredThing')]")); ) - .RespondWith(Response.WithBody("Hello")); + .RespondWith(Response.Create().WithBody("Hello")); ``` ``` @@ -92,7 +92,7 @@ WireMock delegates to [XPath2.Net](https://github.com/StefH/XPath2.Net), therefo var server = FluentMockServer.Start(); server .Given( - Request.WithUrl("/some/thing").UsingGet() + Request.Create().WithUrl("/some/thing").UsingGet() .WithBody(new XPathMatcher("/todo-list[count(todo-item) = 3]")); ) .RespondWith(Response.WithBody("Hello")); @@ -116,10 +116,10 @@ Example: var server = FluentMockServer.Start(); server .Given( - Request.WithUrl("/some/thing").UsingGet() + Request.Create().WithUrl("/some/thing").UsingGet() ) .RespondWith( - Response + Response.Create() .WithStatusCode(200) .WithHeader("Content-Type", "text/plain") .WithBody("Hello world! Your path is {{request.path}.") @@ -157,7 +157,7 @@ var allRequests = server.RequestLogs; If you need to be more specific on the requests that have been send to the server, you can use the very same fluent API that allows to define routes: ```csharp var customerReadRequests = server.SearchLogsFor( - Request.WithUrl("/api/customer*").UsingGet() + Request.Create().WithUrl("/api/customer*").UsingGet() ); ``` @@ -174,12 +174,12 @@ Delays can also be configured at route level: ```csharp var server = FluentMockServer.Start(); server - .Given(Request.WithUrl("/slow")) + .Given(Request.Create().WithUrl("/slow")) .RespondWith( - Responses + Responses.Create() .WithStatusCode(200) .WithBody(@"{ ""msg"": ""Hello I'm a little bit slow!"" }") - .AfterDelay(TimeSpan.FromSeconds(10) + .WithDelay(TimeSpan.FromSeconds(10) ) ); ``` @@ -211,9 +211,9 @@ public async void Should_respond_to_request() _sut = new SomeComponentDoingHttpCalls(); _server - .Given(Request.WithUrl("/foo").UsingGet()) + .Given(Request.Create().WithUrl("/foo").UsingGet()) .RespondWith( - Response + Response.Create() .WithStatusCode(200) .WithBody(@"{ ""msg"": ""Hello world!"" }") ); @@ -251,37 +251,37 @@ static void Main(string[] args) Console.WriteLine("FluentMockServer running at {0}", server.Port); server - .Given(Request.WithUrl(u => u.Contains("x")).UsingGet()) - .RespondWith(Response + .Given(Request.Create().WithUrl(u => u.Contains("x")).UsingGet()) + .RespondWith(Response.Create() .WithStatusCode(200) .WithHeader("Content-Type", "application/json") .WithBody(@"{ ""result"": ""/x with FUNC 200""}")); server - .Given(Request.WithUrl("/*").UsingGet()) - .RespondWith(Response + .Given(Request.Create().WithUrl("/*").UsingGet()) + .RespondWith(Response.Create() .WithStatusCode(200) .WithHeader("Content-Type", "application/json") .WithBody(@"{ ""msg"": ""Hello world!""}") ); server - .Given(Request.WithUrl("/data").UsingPost().WithBody(b => b.Contains("e"))) - .RespondWith(Response + .Given(Request.Create().WithUrl("/data").UsingPost().WithBody(b => b.Contains("e"))) + .RespondWith(Response.Create() .WithStatusCode(201) .WithHeader("Content-Type", "application/json") .WithBody(@"{ ""result"": ""data posted with FUNC 201""}")); server - .Given(Request.WithUrl("/data").UsingPost()) - .RespondWith(Response + .Given(Request.Create().WithUrl("/data").UsingPost()) + .RespondWith(Response.Create() .WithStatusCode(201) .WithHeader("Content-Type", "application/json") .WithBody(@"{ ""result"": ""data posted with 201""}")); server - .Given(Request.WithUrl("/data").UsingDelete()) - .RespondWith(Response + .Given(Request.Create().WithUrl("/data").UsingDelete()) + .RespondWith(Response.Create() .WithStatusCode(200) .WithHeader("Content-Type", "application/json") .WithBody(@"{ ""result"": ""data deleted with 200""}")); diff --git a/WireMock.Net Solution.sln b/WireMock.Net Solution.sln index 6b3f6a1b..b1cd1593 100644 --- a/WireMock.Net Solution.sln +++ b/WireMock.Net Solution.sln @@ -7,6 +7,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{EF242EDF-713 EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{197A0EE3-94E5-4807-BBCF-2F1BCA28A6AE}" ProjectSection(SolutionItems) = preProject + .runsettings = .runsettings appveyor.yml = appveyor.yml README.md = README.md EndProjectSection diff --git a/src/WireMock/HttpListenerRequestMapper.cs b/src/WireMock/HttpListenerRequestMapper.cs index 3f5d35cd..83d71453 100644 --- a/src/WireMock/HttpListenerRequestMapper.cs +++ b/src/WireMock/HttpListenerRequestMapper.cs @@ -1,19 +1,8 @@ using System; -using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Net; -using WireMock.RequestBuilders; -[module: - SuppressMessage("StyleCop.CSharp.ReadabilityRules", - "SA1101:PrefixLocalCallsWithThis", - Justification = "Reviewed. Suppression is OK here, as it conflicts with internal naming rules.")] -[module: - SuppressMessage("StyleCop.CSharp.DocumentationRules", - "SA1633:FileMustHaveHeader", - Justification = "Reviewed. Suppression is OK here, as unknown copyright and company.")] -// ReSharper disable ArrangeThisQualifier namespace WireMock { /// @@ -24,12 +13,8 @@ namespace WireMock /// /// The map. /// - /// - /// The listener request. - /// - /// - /// The . - /// + /// The listener request. + /// The . public RequestMessage Map(HttpListenerRequest listenerRequest) { Uri url = listenerRequest.Url; @@ -45,12 +30,8 @@ namespace WireMock /// /// The get request body. /// - /// - /// The request. - /// - /// - /// The . - /// + /// The request. + /// The . private byte[] GetRequestBody(HttpListenerRequest request) { if (!request.HasEntityBody) diff --git a/src/WireMock/Matchers/Request/RequestMessageBodyMatcher.cs b/src/WireMock/Matchers/Request/RequestMessageBodyMatcher.cs index 13994414..261be42d 100644 --- a/src/WireMock/Matchers/Request/RequestMessageBodyMatcher.cs +++ b/src/WireMock/Matchers/Request/RequestMessageBodyMatcher.cs @@ -99,16 +99,16 @@ namespace WireMock.Matchers.Request public bool IsMatch(RequestMessage requestMessage) { if (_matcher != null) - return _matcher.IsMatch(requestMessage.BodyAsString); + return _matcher.IsMatch(requestMessage.Body); if (_bodyData != null) - return requestMessage.Body == _bodyData; + return requestMessage.BodyAsBytes == _bodyData; if (_bodyFunc != null) - return _bodyFunc(requestMessage.BodyAsString); + return _bodyFunc(requestMessage.Body); if (_bodyDataFunc != null) - return _bodyDataFunc(requestMessage.Body); + return _bodyDataFunc(requestMessage.BodyAsBytes); return false; } diff --git a/src/WireMock/RequestBuilders/IAndPathRequestBuilder.cs b/src/WireMock/RequestBuilders/IAndPathRequestBuilder.cs index 55d0f5a8..5dbd78e6 100644 --- a/src/WireMock/RequestBuilders/IAndPathRequestBuilder.cs +++ b/src/WireMock/RequestBuilders/IAndPathRequestBuilder.cs @@ -1,6 +1,9 @@ namespace WireMock.RequestBuilders { + /// + /// IRequestBuilder + /// public interface IRequestBuilder : IUrlAndPathRequestBuilder { } -} +} \ No newline at end of file diff --git a/src/WireMock/RequestBuilders/Request.cs b/src/WireMock/RequestBuilders/Request.cs index 3def9ecf..4018e07f 100644 --- a/src/WireMock/RequestBuilders/Request.cs +++ b/src/WireMock/RequestBuilders/Request.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; -using JetBrains.Annotations; using WireMock.Matchers; using WireMock.Matchers.Request; @@ -308,4 +307,4 @@ namespace WireMock.RequestBuilders return this; } } -} +} \ No newline at end of file diff --git a/src/WireMock/RequestMessage.cs b/src/WireMock/RequestMessage.cs index 60fba7dc..2cb5f6ae 100644 --- a/src/WireMock/RequestMessage.cs +++ b/src/WireMock/RequestMessage.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Linq; using JetBrains.Annotations; using WireMock.Extensions; +using WireMock.Validation; namespace WireMock { @@ -14,28 +15,21 @@ namespace WireMock /// /// Initializes a new instance of the class. /// - /// - /// The original url. - /// - /// - /// The verb. - /// - /// - /// The body byte[]. - /// - /// - /// The body string. - /// - /// - /// The headers. - /// - public RequestMessage(Uri url, string verb, byte[] body, string bodyAsString, IDictionary headers = null) + /// The original url. + /// The verb. + /// The bodyAsBytes byte[]. + /// The body string. + /// The headers. + public RequestMessage([NotNull] Uri url, [NotNull] string verb, [CanBeNull] byte[] bodyAsBytes, [CanBeNull] string body, [CanBeNull] IDictionary headers = null) { + Check.NotNull(url, nameof(url)); + Check.NotNull(verb, nameof(verb)); + Url = url.ToString(); Path = url.AbsolutePath; Verb = verb.ToLower(); + BodyAsBytes = bodyAsBytes; Body = body; - BodyAsString = bodyAsString; Headers = headers; string query = url.Query; @@ -108,24 +102,20 @@ namespace WireMock public dynamic Query { get; } /// - /// Gets the body. + /// Gets the bodyAsBytes. /// - public byte[] Body { get; } + public byte[] BodyAsBytes { get; } /// /// Gets the body. /// - public string BodyAsString { get; } + public string Body { get; } /// /// The get parameter. /// - /// - /// The key. - /// - /// - /// The parameter. - /// + /// The key. + /// The parameter.s public List GetParameter(string key) { return Parameters.ContainsKey(key) ? Parameters[key] : new List(); diff --git a/src/WireMock/Validation/Check.cs b/src/WireMock/Validation/Check.cs index 05e9e7ab..abdb5b98 100644 --- a/src/WireMock/Validation/Check.cs +++ b/src/WireMock/Validation/Check.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using JetBrains.Annotations; @@ -11,6 +12,7 @@ using JetBrains.Annotations; // Copied from https://github.com/aspnet/EntityFramework/blob/dev/src/Shared/Check.cs namespace WireMock.Validation { + [ExcludeFromCodeCoverage] [DebuggerStepThrough] internal static class Check { diff --git a/src/WireMock/Validation/CoreStrings.cs b/src/WireMock/Validation/CoreStrings.cs index c6f259d9..07a2ba96 100644 --- a/src/WireMock/Validation/CoreStrings.cs +++ b/src/WireMock/Validation/CoreStrings.cs @@ -1,10 +1,12 @@ using System; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using JetBrains.Annotations; // copied from https://github.com/aspnet/EntityFramework/blob/dev/src/Microsoft.EntityFrameworkCore/Properties/CoreStrings.resx namespace WireMock.Validation { + [ExcludeFromCodeCoverage] internal static class CoreStrings { /// diff --git a/test/WireMock.Net.Tests/FluentMockServerTests.cs b/test/WireMock.Net.Tests/FluentMockServerTests.cs index 64d250e1..d70336d4 100644 --- a/test/WireMock.Net.Tests/FluentMockServerTests.cs +++ b/test/WireMock.Net.Tests/FluentMockServerTests.cs @@ -100,7 +100,7 @@ namespace WireMock.Net.Tests Check.That(_server.RequestLogs).HasSize(1); var requestLogged = _server.RequestLogs.First(); Check.That(requestLogged.Verb).IsEqualTo("get"); - Check.That(requestLogged.Body).IsNull(); + Check.That(requestLogged.BodyAsBytes).IsNull(); } [Test] diff --git a/test/WireMock.Net.Tests/HttpListenerRequestMapperTests.cs b/test/WireMock.Net.Tests/HttpListenerRequestMapperTests.cs index 6a88eaf7..14e078af 100644 --- a/test/WireMock.Net.Tests/HttpListenerRequestMapperTests.cs +++ b/test/WireMock.Net.Tests/HttpListenerRequestMapperTests.cs @@ -8,23 +8,6 @@ using NFluent; using NUnit.Framework; using WireMock.Http; -[module: - SuppressMessage("StyleCop.CSharp.ReadabilityRules", - "SA1101:PrefixLocalCallsWithThis", - Justification = "Reviewed. Suppression is OK here, as it conflicts with internal naming rules.")] -[module: - SuppressMessage("StyleCop.CSharp.NamingRules", - "SA1309:FieldNamesMustNotBeginWithUnderscore", - Justification = "Reviewed. Suppression is OK here, as it conflicts with internal naming rules.")] -[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 { [TestFixture] @@ -77,7 +60,7 @@ namespace WireMock.Net.Tests // then Check.That(MapperServer.LastRequestMessage).IsNotNull(); - Check.That(MapperServer.LastRequestMessage.BodyAsString).IsEqualTo("Hello!"); + Check.That(MapperServer.LastRequestMessage.Body).IsEqualTo("Hello!"); } [Test] diff --git a/test/WireMock.Net.Tests/HttpListenerResponseMapperTests.cs b/test/WireMock.Net.Tests/HttpListenerResponseMapperTests.cs index 495fe72d..8e72c3e3 100644 --- a/test/WireMock.Net.Tests/HttpListenerResponseMapperTests.cs +++ b/test/WireMock.Net.Tests/HttpListenerResponseMapperTests.cs @@ -1,5 +1,4 @@ -using System.Diagnostics.CodeAnalysis; -using System.Net; +using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; @@ -7,24 +6,6 @@ using NFluent; using NUnit.Framework; using WireMock.Http; -[module: - SuppressMessage("StyleCop.CSharp.ReadabilityRules", - "SA1101:PrefixLocalCallsWithThis", - Justification = "Reviewed. Suppression is OK here, as it conflicts with internal naming rules.")] -[module: - SuppressMessage("StyleCop.CSharp.NamingRules", - "SA1309:FieldNamesMustNotBeginWithUnderscore", - Justification = "Reviewed. Suppression is OK here, as it conflicts with internal naming rules.")] -[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.")] -// ReSharper disable ArrangeThisQualifier -// ReSharper disable InconsistentNaming namespace WireMock.Net.Tests { [TestFixture] diff --git a/test/WireMock.Net.Tests/RequestTests.cs b/test/WireMock.Net.Tests/RequestTests.cs index 084fa1bf..3eee15a7 100644 --- a/test/WireMock.Net.Tests/RequestTests.cs +++ b/test/WireMock.Net.Tests/RequestTests.cs @@ -245,7 +245,7 @@ namespace WireMock.Net.Tests // when string bodyAsString = "Hello world!"; byte[] body = Encoding.UTF8.GetBytes(bodyAsString); - var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", body, bodyAsString, new Dictionary { { "X-toto", "tatata" } }); + var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", body, bodyAsString); // then Check.That(spec.IsMatch(request)).IsTrue(); diff --git a/test/WireMock.Net.Tests/ResponseTests.cs b/test/WireMock.Net.Tests/ResponseTests.cs new file mode 100644 index 00000000..e6f9a880 --- /dev/null +++ b/test/WireMock.Net.Tests/ResponseTests.cs @@ -0,0 +1,50 @@ +using System; +using System.Collections.Generic; +using System.Linq; +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_body() + { + // given + string bodyAsString = "abc"; + byte[] body = Encoding.UTF8.GetBytes(bodyAsString); + var request = new RequestMessage(new Uri("http://localhost/foo"), "POST", body, bodyAsString); + + var response = Response.Create().WithBody("test {{request.url}} {{request.path}} {{request.verb}}").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_headers() + { + // given + string bodyAsString = "abc"; + byte[] body = Encoding.UTF8.GetBytes(bodyAsString); + var request = new RequestMessage(new Uri("http://localhost/foo"), "POST", body, bodyAsString, new Dictionary { { "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("x", "text/plain")); + } + } +} \ No newline at end of file diff --git a/test/WireMock.Net.Tests/WireMock.Net.Tests.csproj b/test/WireMock.Net.Tests/WireMock.Net.Tests.csproj index 1f6017e3..ffc630e3 100644 --- a/test/WireMock.Net.Tests/WireMock.Net.Tests.csproj +++ b/test/WireMock.Net.Tests/WireMock.Net.Tests.csproj @@ -66,6 +66,7 @@ +