Add unit test for Response Handlebars

This commit is contained in:
Stef Heyenrath
2017-01-20 17:52:49 +01:00
parent 1b2d20fd69
commit 6c16d45256
16 changed files with 141 additions and 121 deletions

27
.runsettings Normal file
View File

@@ -0,0 +1,27 @@
<?xml version="1.0" encoding="utf-8"?>
<RunSettings>
<DataCollectionRunSettings>
<DataCollectors>
<DataCollector friendlyName="Code Coverage"
uri="datacollector://Microsoft/CodeCoverage/2.0"
assemblyQualifiedName="Microsoft.VisualStudio.Coverage.DynamicCoverageDataCollector, Microsoft.VisualStudio.TraceCollector, Version=11.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<Configuration>
<CodeCoverage>
<ModulePaths>
<Include>
<ModulePath>.*\.dll$</ModulePath>
</Include>
<Exclude>
<ModulePath>.*\.tests.dll</ModulePath>
</Exclude>
</ModulePaths>
<UseVerifiableInstrumentation>True</UseVerifiableInstrumentation>
<AllowLowIntegrityProcesses>True</AllowLowIntegrityProcesses>
<CollectFromChildProcesses>True</CollectFromChildProcesses>
<CollectAspDotNet>False</CollectAspDotNet>
</CodeCoverage>
</Configuration>
</DataCollector>
</DataCollectors>
</DataCollectionRunSettings>
</RunSettings>

View File

@@ -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""}"));

View File

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

View File

@@ -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
{
/// <summary>
@@ -24,12 +13,8 @@ namespace WireMock
/// <summary>
/// The map.
/// </summary>
/// <param name="listenerRequest">
/// The listener request.
/// </param>
/// <returns>
/// The <see cref="AndPathRequest"/>.
/// </returns>
/// <param name="listenerRequest">The listener request.</param>
/// <returns>The <see cref="RequestMessage"/>.</returns>
public RequestMessage Map(HttpListenerRequest listenerRequest)
{
Uri url = listenerRequest.Url;
@@ -45,12 +30,8 @@ namespace WireMock
/// <summary>
/// The get request body.
/// </summary>
/// <param name="request">
/// The request.
/// </param>
/// <returns>
/// The <see cref="string"/>.
/// </returns>
/// <param name="request">The request.</param>
/// <returns>The <see cref="string"/>.</returns>
private byte[] GetRequestBody(HttpListenerRequest request)
{
if (!request.HasEntityBody)

View File

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

View File

@@ -1,6 +1,9 @@
namespace WireMock.RequestBuilders
{
/// <summary>
/// IRequestBuilder
/// </summary>
public interface IRequestBuilder : IUrlAndPathRequestBuilder
{
}
}
}

View File

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

View File

@@ -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
/// <summary>
/// Initializes a new instance of the <see cref="RequestMessage"/> class.
/// </summary>
/// <param name="url">
/// The original url.
/// </param>
/// <param name="verb">
/// The verb.
/// </param>
/// <param name="body">
/// The body byte[].
/// </param>
/// <param name="bodyAsString">
/// The body string.
/// </param>
/// <param name="headers">
/// The headers.
/// </param>
public RequestMessage(Uri url, string verb, byte[] body, string bodyAsString, IDictionary<string, string> headers = null)
/// <param name="url">The original url.</param>
/// <param name="verb">The verb.</param>
/// <param name="bodyAsBytes">The bodyAsBytes byte[].</param>
/// <param name="body">The body string.</param>
/// <param name="headers">The headers.</param>
public RequestMessage([NotNull] Uri url, [NotNull] string verb, [CanBeNull] byte[] bodyAsBytes, [CanBeNull] string body, [CanBeNull] IDictionary<string, string> 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; }
/// <summary>
/// Gets the body.
/// Gets the bodyAsBytes.
/// </summary>
public byte[] Body { get; }
public byte[] BodyAsBytes { get; }
/// <summary>
/// Gets the body.
/// </summary>
public string BodyAsString { get; }
public string Body { get; }
/// <summary>
/// The get parameter.
/// </summary>
/// <param name="key">
/// The key.
/// </param>
/// <returns>
/// The parameter.
/// </returns>
/// <param name="key">The key.</param>
/// <returns>The parameter.s</returns>
public List<string> GetParameter(string key)
{
return Parameters.ContainsKey(key) ? Parameters[key] : new List<string>();

View File

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

View File

@@ -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
{
/// <summary>

View File

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

View File

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

View File

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

View File

@@ -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<string, string> { { "X-toto", "tatata" } });
var request = new RequestMessage(new Uri("http://localhost/foo"), "PUT", body, bodyAsString);
// then
Check.That(spec.IsMatch(request)).IsTrue();

View File

@@ -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<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"));
}
}
}

View File

@@ -66,6 +66,7 @@
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="RequestTests.cs" />
<Compile Include="RequestMessageTests.cs" />
<Compile Include="ResponseTests.cs" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />