Compare commits

..

8 Commits

Author SHA1 Message Date
Stef Heyenrath
7cf283ec13 Restricted ResponseHeaders (#126) 2018-04-17 19:43:38 +02:00
Stef Heyenrath
2c0f00d77f Release notes 2018-04-15 14:04:08 +02:00
Stef Heyenrath
1bcdfe31ab 1.0.3.16 2018-04-15 14:02:45 +02:00
raghavendrabankapur
0abe12f5c8 Fix for issue #118 (#121)
* Fix for issue #118

* Adding test cases for fix #118

* Moved the namespace in using block for fix #118
2018-04-15 11:25:17 +02:00
SubjectiveReality
7bd63a0baf Change listen from loopback to any ip address for dotnetcore2.0 apps per issue #124
Change listen from loopback to any ip address for dotnetcore2.0 apps per issue #124 (#125)
2018-04-14 09:56:29 +02:00
Stef Heyenrath
a29363105c 1.0.3.15 2018-04-05 21:07:05 +02:00
Stef Heyenrath
4f294baff2 Small code refactor (#117) 2018-04-05 20:51:10 +02:00
Evan Liang
2d2a2dd6fc Respect start timeout setting and expose exception from server startup (#117)
* Respect start timeout setting and expose exception from server startup

* Dispose running servers properly on error happening

* Addressed comments from Stef
2018-04-05 18:31:10 +00:00
20 changed files with 263 additions and 71 deletions

View File

@@ -1,3 +1,20 @@
# 1.0.3.16 (15 April 2018)
- [#125](https://github.com/WireMock-Net/WireMock.Net/pull/125) - Change listen from loopback to any ip address for dotnetcore2.0 apps contributed by ([SubjectiveReality](https://github.com/SubjectiveReality))
- [#124](https://github.com/WireMock-Net/WireMock.Net/issues/124) - Issue: Unable to get host to listen on ips other than 127.0.0.1 using StandAloneApp
- [#121](https://github.com/WireMock-Net/WireMock.Net/pull/121) - Fix for issue #118 contributed by ([raghavendrabankapur](https://github.com/raghavendrabankapur)) +fix
- [#118](https://github.com/WireMock-Net/WireMock.Net/issues/118) - Not reading the response from a file when mappings are placed in json file
Commits: 7bd63a0baf...1bcdfe31ab
# 1.0.3.15 (05 April 2018)
- [#117](https://github.com/WireMock-Net/WireMock.Net/pull/117) - Respect start timeout setting and expose exception from server startup contributed by Evan Liang ([evanlwj](https://github.com/evanlwj))
Commits: 2d2a2dd6fc...4f294baff2
# 1.0.3.14 (01 April 2018)
- [#114](https://github.com/WireMock-Net/WireMock.Net/issues/114) - Feature: Add PathSegments in Transform +feature

View File

@@ -1,5 +1,5 @@
https://github.com/GitTools/GitReleaseNotes
GitReleaseNotes.exe . /OutputFile CHANGELOG.md /Version 1.0.3.14
GitReleaseNotes.exe . /OutputFile CHANGELOG.md /Version 1.0.3.16
GitReleaseNotes.exe . /OutputFile CHANGELOG.md /allTags

View File

@@ -14,6 +14,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
GitReleaseNotes.txt = GitReleaseNotes.txt
README.md = README.md
ReSharper_WireMock.DotSettings = ReSharper_WireMock.DotSettings
WireMock.Net Solution.sln.DotSettings = WireMock.Net Solution.sln.DotSettings
EndProjectSection
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "examples", "examples", "{F0C22C47-DF71-463C-9B04-B4E0F3B8708A}"

View File

@@ -1,3 +1,11 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=ID/@EntryIndexedValue">ID</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=IP/@EntryIndexedValue">IP</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=SSL/@EntryIndexedValue">SSL</s:String></wpf:ResourceDictionary>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=MD/@EntryIndexedValue">MD5</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=SSL/@EntryIndexedValue">SSL</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=TE/@EntryIndexedValue">TE</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=TSV/@EntryIndexedValue">TSV</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=WWW/@EntryIndexedValue">WWW</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=XMS/@EntryIndexedValue">XMS</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=XUA/@EntryIndexedValue">XUA</s:String>
</wpf:ResourceDictionary>

View File

@@ -3,7 +3,7 @@
<PropertyGroup>
<Description>Lightweight StandAlone Http Mocking Server for .Net.</Description>
<AssemblyTitle>WireMock.Net.StandAlone</AssemblyTitle>
<Version>1.0.3.14</Version>
<Version>1.0.3.16</Version>
<Authors>Stef Heyenrath</Authors>
<TargetFrameworks>net452;net46;netstandard1.3;netstandard2.0</TargetFrameworks>
<GenerateDocumentationFile>true</GenerateDocumentationFile>

View File

@@ -9,6 +9,7 @@ using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using WireMock.Http;
using WireMock.HttpsCertificate;
using WireMock.Logging;
using WireMock.Validation;
namespace WireMock.Owin
@@ -18,6 +19,8 @@ namespace WireMock.Owin
private readonly CancellationTokenSource _cts = new CancellationTokenSource();
private readonly WireMockMiddlewareOptions _options;
private readonly string[] _urls;
private readonly IWireMockLogger _logger;
private Exception _runningException;
private IWebHost _host;
@@ -27,11 +30,15 @@ namespace WireMock.Owin
public List<int> Ports { get; } = new List<int>();
public Exception RunningException => _runningException;
public AspNetCoreSelfHost([NotNull] WireMockMiddlewareOptions options, [NotNull] params string[] uriPrefixes)
{
Check.NotNull(options, nameof(options));
Check.NotNullOrEmpty(uriPrefixes, nameof(uriPrefixes));
_logger = options.Logger ?? new WireMockConsoleLogger();
foreach (string uriPrefix in uriPrefixes)
{
Urls.Add(uriPrefix);
@@ -69,13 +76,13 @@ namespace WireMock.Owin
foreach (string url in _urls.Where(u => u.StartsWith("http://", StringComparison.OrdinalIgnoreCase)))
{
PortUtil.TryExtractProtocolAndPort(url, out string host, out int port);
options.Listen(System.Net.IPAddress.Loopback, port);
options.Listen(System.Net.IPAddress.Any, port);
}
foreach (string url in _urls.Where(u => u.StartsWith("https://", StringComparison.OrdinalIgnoreCase)))
{
PortUtil.TryExtractProtocolAndPort(url, out string host, out int port);
options.Listen(System.Net.IPAddress.Loopback, port, listenOptions =>
options.Listen(System.Net.IPAddress.Any, port, listenOptions =>
{
listenOptions.UseHttps(PublicCertificateHelper.GetX509Certificate2());
});
@@ -89,20 +96,34 @@ namespace WireMock.Owin
IsStarted = true;
#if NETSTANDARD1_3
Console.WriteLine("WireMock.Net server using netstandard1.3");
return Task.Run(() =>
{
_host.Run(_cts.Token);
StartServers();
}, _cts.Token);
#else
System.Console.WriteLine("WireMock.Net server using netstandard2.0");
}
return Task.Run(() =>
private void StartServers()
{
try
{
IsStarted = true;
#if NETSTANDARD1_3
_logger.Info("WireMock.Net server using netstandard1.3");
_host.Run(_cts.Token);
#else
_logger.Info("WireMock.Net server using netstandard2.0");
_host.Run();
}, _cts.Token);
#endif
}
catch (Exception e)
{
_runningException = e;
_logger.Error(e.ToString());
}
finally
{
IsStarted = false;
}
}
public Task StopAsync()

View File

@@ -1,5 +1,6 @@
using System.Collections.Generic;
using System.Threading.Tasks;
using System;
namespace WireMock.Owin
{
@@ -16,19 +17,18 @@ namespace WireMock.Owin
/// <summary>
/// Gets the urls.
/// </summary>
/// <value>
/// The urls.
/// </value>
List<string> Urls { get; }
/// <summary>
/// Gets the ports.
/// </summary>
/// <value>
/// The ports.
/// </value>
List<int> Ports { get; }
/// <summary>
/// The exception occurred when the host is running
/// </summary>
Exception RunningException { get; }
Task StartAsync();
Task StopAsync();

View File

@@ -1,8 +1,6 @@
using System;
using System.Collections.Generic;
// using System.IO;
using System.Linq;
// using System.Text;
using System.Threading.Tasks;
using WireMock.Util;
#if !NETSTANDARD

View File

@@ -5,6 +5,7 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using WireMock.Http;
using WireMock.Util;
#if !NETSTANDARD
using Microsoft.Owin;
@@ -21,17 +22,27 @@ namespace WireMock.Owin
{
private readonly Encoding _utf8NoBom = new UTF8Encoding(false);
// https://stackoverflow.com/questions/239725/cannot-set-some-http-headers-when-using-system-net-webrequest
// https://msdn.microsoft.com/en-us/library/78h415ay(v=vs.110).aspx
#if !NETSTANDARD
private static readonly IDictionary<string, Action<IOwinResponse, WireMockList<string>>> RestrictedResponseHeaders = new Dictionary<string, Action<IOwinResponse, WireMockList<string>>>(StringComparer.OrdinalIgnoreCase) {
#else
private static readonly IDictionary<string, Action<HttpResponse, WireMockList<string>>> RestrictedResponseHeaders = new Dictionary<string, Action<HttpResponse, WireMockList<string>>>(StringComparer.OrdinalIgnoreCase) {
#endif
{ "Content-Length", null },
{ "Content-Type", (r, v) => r.ContentType = v.FirstOrDefault() },
{ "Keep-Alive", null },
{ "Transfer-Encoding", null },
{ "WWW-Authenticate", null }
{ HttpKnownHeaderNames.Accept, null },
{ HttpKnownHeaderNames.Connection, null },
{ HttpKnownHeaderNames.ContentLength, null },
{ HttpKnownHeaderNames.ContentType, (r, v) => r.ContentType = v.FirstOrDefault() },
{ HttpKnownHeaderNames.Date, null },
{ HttpKnownHeaderNames.Expect, null },
{ HttpKnownHeaderNames.Host, null },
{ HttpKnownHeaderNames.IfModifiedSince, null },
{ HttpKnownHeaderNames.KeepAlive, null },
{ HttpKnownHeaderNames.Range, null },
{ HttpKnownHeaderNames.Referer, null },
{ HttpKnownHeaderNames.TransferEncoding, null },
{ HttpKnownHeaderNames.UserAgent, null },
{ HttpKnownHeaderNames.ProxyConnection, null },
{ HttpKnownHeaderNames.WWWAuthenticate, null }
};
/// <summary>

View File

@@ -1,13 +1,14 @@
#if !NETSTANDARD
using JetBrains.Annotations;
using Microsoft.Owin.Hosting;
using Owin;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using JetBrains.Annotations;
using WireMock.Validation;
using Owin;
using Microsoft.Owin.Hosting;
using WireMock.Http;
using WireMock.Logging;
using WireMock.Validation;
namespace WireMock.Owin
{
@@ -15,12 +16,16 @@ namespace WireMock.Owin
{
private readonly WireMockMiddlewareOptions _options;
private readonly CancellationTokenSource _cts = new CancellationTokenSource();
private readonly IWireMockLogger _logger;
private Exception _runningException;
public OwinSelfHost([NotNull] WireMockMiddlewareOptions options, [NotNull] params string[] uriPrefixes)
{
Check.NotNull(options, nameof(options));
Check.NotNullOrEmpty(uriPrefixes, nameof(uriPrefixes));
_logger = options.Logger ?? new WireMockConsoleLogger();
foreach (string uriPrefix in uriPrefixes)
{
Urls.Add(uriPrefix);
@@ -38,6 +43,8 @@ namespace WireMock.Owin
public List<int> Ports { get; } = new List<int>();
public Exception RunningException => _runningException;
[PublicAPI]
public Task StartAsync()
{
@@ -58,37 +65,46 @@ namespace WireMock.Owin
private void StartServers()
{
#if NET46
Console.WriteLine("WireMock.Net server using .net 4.6.x or higher");
_logger.Info("WireMock.Net server using .net 4.6.x or higher");
#else
Console.WriteLine("WireMock.Net server using .net 4.5.x or higher");
_logger.Info("WireMock.Net server using .net 4.5.x or higher");
#endif
Action<IAppBuilder> startup = app =>
{
app.Use<GlobalExceptionMiddleware>(_options);
_options.PreWireMockMiddlewareInit?.Invoke(app);
app.Use<WireMockMiddleware>(_options);
_options.PostWireMockMiddlewareInit?.Invoke(app);
};
var servers = new List<IDisposable>();
foreach (var url in Urls)
try
{
servers.Add(WebApp.Start(url, startup));
Action<IAppBuilder> startup = app =>
{
app.Use<GlobalExceptionMiddleware>(_options);
_options.PreWireMockMiddlewareInit?.Invoke(app);
app.Use<WireMockMiddleware>(_options);
_options.PostWireMockMiddlewareInit?.Invoke(app);
};
foreach (var url in Urls)
{
servers.Add(WebApp.Start(url, startup));
}
IsStarted = true;
// WaitHandle is signaled when the token is cancelled,
// which will be more efficent than Thread.Sleep in while loop
_cts.Token.WaitHandle.WaitOne();
}
IsStarted = true;
while (!_cts.IsCancellationRequested)
catch (Exception e)
{
Thread.Sleep(30000);
// Expose exception of starting host, otherwise it's hard to be troubleshooting if keeping quiet
// For example, WebApp.Start will fail with System.MissingMemberException if Microsoft.Owin.Host.HttpListener.dll is being located
// https://stackoverflow.com/questions/25090211/owin-httplistener-not-located/31369857
_runningException = e;
_logger.Error(e.ToString());
}
IsStarted = false;
foreach (var server in servers)
finally
{
server.Dispose();
IsStarted = false;
// Dispose all servers in finally block to make sure clean up allocated resource on error happening
servers.ForEach(s => s.Dispose());
}
}
}

View File

@@ -31,9 +31,6 @@ namespace WireMock.ResponseBuilders
/// <summary>
/// Gets a value indicating whether [use transformer].
/// </summary>
/// <value>
/// <c>true</c> if [use transformer]; otherwise, <c>false</c>.
/// </value>
public bool UseTransformer { get; private set; }
/// <summary>
@@ -258,7 +255,7 @@ namespace WireMock.ResponseBuilders
return this;
}
/// <inheritdoc cref="IBodyResponseBuilder.WithBodyAsJson(object, Encoding, bool)"/>
/// <inheritdoc cref="IBodyResponseBuilder.WithBodyAsJson(object, Encoding, bool?)"/>
public IResponseBuilder WithBodyAsJson(object body, Encoding encoding = null, bool? indented = null)
{
Check.NotNull(body, nameof(body));

View File

@@ -745,6 +745,11 @@ namespace WireMock.Server
responseBuilder = responseBuilder.WithBodyFromBase64(responseModel.BodyFromBase64, ToEncoding(responseModel.BodyEncoding));
}
else if (responseModel.BodyAsFile != null)
{
responseBuilder = responseBuilder.WithBodyFromFile(responseModel.BodyAsFile);
}
if (responseModel.UseTransformer)
{
responseBuilder = responseBuilder.WithTransformer();

View File

@@ -1,20 +1,20 @@
using JetBrains.Annotations;
using Newtonsoft.Json;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using JetBrains.Annotations;
using Newtonsoft.Json;
using System.Threading;
using WireMock.Http;
using WireMock.Logging;
using WireMock.Matchers;
using WireMock.Matchers.Request;
using WireMock.Owin;
using WireMock.RequestBuilders;
using WireMock.ResponseProviders;
using WireMock.Settings;
using WireMock.Validation;
using WireMock.Owin;
using WireMock.ResponseProviders;
namespace WireMock.Server
{
@@ -32,7 +32,7 @@ namespace WireMock.Server
/// Gets a value indicating whether this server is started.
/// </summary>
[PublicAPI]
public bool IsStarted { get; }
public bool IsStarted => _httpServer != null && _httpServer.IsStarted;
/// <summary>
/// Gets the ports.
@@ -186,10 +186,23 @@ namespace WireMock.Server
_httpServer.StartAsync();
// Fix for 'Bug: Server not listening after Start() returns (on macOS)'
Task.Delay(ServerStartDelay).Wait();
IsStarted = _httpServer.IsStarted;
using (var ctsStartTimeout = new CancellationTokenSource(settings.StartTimeout))
{
while (!_httpServer.IsStarted)
{
// Throw out exception if service start fails
if (_httpServer.RunningException != null)
{
throw new Exception($"Service start failed with error: {_httpServer.RunningException.Message}", _httpServer.RunningException);
}
// Respect start timeout setting by throwing TimeoutException
if (ctsStartTimeout.IsCancellationRequested)
{
throw new TimeoutException($"Service start timed out after {TimeSpan.FromMilliseconds(settings.StartTimeout)}");
}
ctsStartTimeout.Token.WaitHandle.WaitOne(ServerStartDelay);
}
}
if (settings.AllowPartialMapping == true)
{

View File

@@ -11,8 +11,7 @@ namespace WireMock.Util
return default(T);
}
var token = value as JToken;
return token == null ? default(T) : token.ToObject<T>();
return !(value is JToken token) ? default(T) : token.ToObject<T>();
}
}
}

View File

@@ -3,7 +3,7 @@
<PropertyGroup>
<Description>Lightweight Http Mocking Server for .Net, inspired by WireMock from the Java landscape.</Description>
<AssemblyTitle>WireMock.Net</AssemblyTitle>
<Version>1.0.3.14</Version>
<Version>1.0.3.16</Version>
<Authors>Stef Heyenrath</Authors>
<TargetFrameworks>net452;net46;netstandard1.3;netstandard2.0</TargetFrameworks>
<GenerateDocumentationFile>true</GenerateDocumentationFile>

View File

@@ -11,6 +11,7 @@ using WireMock.RequestBuilders;
using WireMock.ResponseBuilders;
using WireMock.Server;
using Xunit;
using Newtonsoft.Json;
namespace WireMock.Net.Tests
{
@@ -76,6 +77,34 @@ namespace WireMock.Net.Tests
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(), "ResponseBodyFiles", "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()
{
@@ -85,7 +114,7 @@ namespace WireMock.Net.Tests
_server.ReadStaticMappings(folder);
var mappings = _server.Mappings.ToArray();
Check.That(mappings).HasSize(2);
Check.That(mappings).HasSize(3);
}
[Fact]
@@ -516,6 +545,24 @@ namespace WireMock.Net.Tests
Check.That(response).IsEqualTo("/fooBar");
}
[Fact]
public async Task FluentMockServer_Should_IgnoreRestrictedHeader()
{
// Assign
_server = FluentMockServer.Start();
_server
.Given(Request.Create().WithPath("/head").UsingHead())
.RespondWith(Response.Create().WithHeader("Content-Length", "1024"));
var request = new HttpRequestMessage(HttpMethod.Head, "http://localhost:" + _server.Ports[0] + "/head");
// Act
var response = await new HttpClient().SendAsync(request);
// Assert
Check.That(response.Content.Headers.GetValues("Content-Length")).ContainsExactly("0");
}
public void Dispose()
{
_server?.Stop();

View File

@@ -0,0 +1,3 @@
{
"test": "test"
}

View File

@@ -0,0 +1,26 @@
using System;
using NFluent;
using WireMock.ResponseBuilders;
using Xunit;
namespace WireMock.Net.Tests
{
public class ResponseTests
{
private const string ClientIp = "::1";
[Fact]
public async void Response_Create_WithHeader_ContentLength()
{
// Assign
var requestMock = new RequestMessage(new Uri("http://localhost/foo"), "PUT", ClientIp);
IResponseBuilder builder = Response.Create().WithHeader("Content-Length", "1024");
// Act
var response = await builder.ProvideResponseAsync(requestMock);
// Assert
Check.That(response.Headers["Content-Length"].ToString()).Equals("1024");
}
}
}

View File

@@ -31,9 +31,15 @@
</ItemGroup>
<ItemGroup>
<None Update="ResponseBodyFiles\responsebody.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="__admin\mappings\00000002-ee28-4f29-ae63-1ac9b0802d86.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="__admin\mappings\00000002-ee28-4f29-ae63-1ac9b0802d87.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="__admin\mappings\documentdb_root.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>

View File

@@ -0,0 +1,24 @@
{
"Guid": "00000002-ee28-4f29-ae63-1ac9b0802d87",
"Priority": 0,
"Request": {
"Path": {
"Matchers": [
{
"Name": "ExactMatcher",
"Pattern": "/response/staticfile"
}
]
},
"Methods": [
"get"
]
},
"Response": {
"StatusCode": 200,
"BodyAsFile": "responsebody.json",
"Headers": {
"Content-Type": "application/json"
}
}
}