Compare commits

..

1 Commits

Author SHA1 Message Date
Stef Heyenrath
43177d45c3 wip 2018-11-22 16:44:14 +01:00
20 changed files with 147 additions and 358 deletions

View File

@@ -1,22 +1,8 @@
# 1.0.6 (15 December 2018)
- [#242](https://github.com/WireMock-Net/WireMock.Net/pull/242) - Post multiple Mappings [feature] contributed by [StefH](https://github.com/StefH)
- [#237](https://github.com/WireMock-Net/WireMock.Net/issues/237) - Port not released [question]
- [#239](https://github.com/WireMock-Net/WireMock.Net/issues/239) - Not able to hit the mock server if AllowPartialMapping is not set to true [question]
- [#240](https://github.com/WireMock-Net/WireMock.Net/issues/240) - How to submit mappings for multiple request, responses [feature]
# 1.0.5 (07 December 2018)
- [#236](https://github.com/WireMock-Net/WireMock.Net/pull/236) - Add Random Regex (using Fare) [feature] contributed by [StefH](https://github.com/StefH)
# 1.0.4.21 (30 November 2018)
# 1.0.4.21 (09 November 2018)
- [#221](https://github.com/WireMock-Net/WireMock.Net/pull/221) - Update dependencies [feature] contributed by [StefH](https://github.com/StefH)
- [#229](https://github.com/WireMock-Net/WireMock.Net/pull/229) - Fix proxy tests [test] contributed by [StefH](https://github.com/StefH)
- [#230](https://github.com/WireMock-Net/WireMock.Net/pull/230) - Add HandleBars Random functionality (#219) [feature] contributed by [StefH](https://github.com/StefH)
- [#231](https://github.com/WireMock-Net/WireMock.Net/pull/231) - Use RandomDataGenerator.Net 1.0.3.0 contributed by [StefH](https://github.com/StefH)
- [#232](https://github.com/WireMock-Net/WireMock.Net/pull/232) - Add SonarLint checks [feature] contributed by [StefH](https://github.com/StefH)
- [#233](https://github.com/WireMock-Net/WireMock.Net/pull/233) - RandomDataGenerator.Net 1.0.4 [feature] contributed by [StefH](https://github.com/StefH)
- [#235](https://github.com/WireMock-Net/WireMock.Net/pull/235) - Check aggregate exception during startup [bug] contributed by [StefH](https://github.com/StefH)
- [#219](https://github.com/WireMock-Net/WireMock.Net/issues/219) - Feature: random value helper [feature]
- [#234](https://github.com/WireMock-Net/WireMock.Net/issues/234) - Timeout Exception on VSTS Test Platform (Azure DevOps), with private build agent
# 1.0.4.20 (07 November 2018)
- [#222](https://github.com/WireMock-Net/WireMock.Net/pull/222) - Codecov contributed by [StefH](https://github.com/StefH)

View File

@@ -4,7 +4,7 @@
</PropertyGroup>
<PropertyGroup>
<VersionPrefix>1.0.6</VersionPrefix>
<VersionPrefix>1.0.4.20</VersionPrefix>
</PropertyGroup>
<Choose>

View File

@@ -1,3 +1,3 @@
https://github.com/StefH/GitHubReleaseNotes
GitHubReleaseNotes.exe --output CHANGELOG.md --skip-empty-releases --version 1.0.6
GitHubReleaseNotes.exe --output CHANGELOG.md --skip-empty-releases --version 1.0.4.21

View File

@@ -5,10 +5,10 @@ A C# .NET version based on [mock4net](https://github.com/alexvictoor/mock4net) w
* HTTP response stubbing, matchable on URL/Path, headers, cookies and body content patterns
* Runs in unit tests, as a standalone process, as windows service, as Azure or IIS or as docker
* Configurable via a fluent DotNet API, JSON files and JSON over HTTP
* Record/playback of stubs (proxying)
* Record/playback of stubs
* Per-request conditional proxying
* Stateful behaviour simulation
* Response transformation
* Configurable response delays
## Info
| | |

View File

@@ -388,10 +388,11 @@ namespace WireMock.Net.ConsoleApplication
.WithStatusCode(500)
.WithBody(requestMessage =>
{
return JsonConvert.SerializeObject(new
string returnStr = JsonConvert.SerializeObject(new
{
Message = "Test error"
});
return returnStr;
})
);
@@ -401,28 +402,22 @@ namespace WireMock.Net.ConsoleApplication
.WithHeader("Content-Type", "application/json")
.WithBodyAsJson(new
{
Xeger1 = "{{Xeger \"\\w{4}\\d{5}\"}}",
Xeger2 = "{{Xeger \"\\d{5}\"}}",
TextRegexPostcode = "{{Random Type=\"TextRegex\" Pattern=\"[1-9][0-9]{3}[A-Z]{2}\"}}",
Text = "{{Random Type=\"Text\" Min=8 Max=20}}",
TextLipsum = "{{Random Type=\"TextLipsum\"}}",
IBAN = "{{Random Type=\"IBAN\" CountryCode=\"NL\"}}",
TimeSpan1 = "{{Random Type=\"TimeSpan\" Format=\"c\" IncludeMilliseconds=false}}",
TimeSpan2 = "{{Random Type=\"TimeSpan\"}}",
DateTime1 = "{{Random Type=\"DateTime\"}}",
DateTimeNow = DateTime.Now,
DateTimeNowToString = DateTime.Now.ToString("s", CultureInfo.InvariantCulture),
DateTimeToString = DateTime.Now.ToString("s", CultureInfo.InvariantCulture),
Guid1 = "{{Random Type=\"Guid\" Uppercase=false}}",
Guid2 = "{{Random Type=\"Guid\"}}",
Boolean = "{{Random Type=\"Boolean\"}}",
Integer = "{{Random Type=\"Integer\" Min=1000 Max=9999}}",
Long = "{{#Random Type=\"Long\" Min=10000000 Max=99999999}}{{this}}{{/Random}}",
Double = "{{Random Type=\"Double\" Min=10 Max=99}}",
Float = "{{Random Type=\"Float\" Min=100 Max=999}}",
Integer1 = "{{Random Type=\"Integer\" Min=1000 Max=9999}}",
Integer2 = "{{#Random Type=\"Integer\" Min=10000000 Max=99999999}}{{this}}{{/Random}}",
Double1 = "{{Random Type=\"Double\" Min=10 Max=99}}",
Double2 = "{{Random Type=\"Double\" Min=100 Max=999}}",
IP4Address = "{{Random Type=\"IPv4Address\" Min=\"10.2.3.4\"}}",
IP6Address = "{{Random Type=\"IPv6Address\"}}",
MACAddress = "{{Random Type=\"MACAddress\" Separator=\"-\"}}",
StringListValue = "{{Random Type=\"StringList\" Values=[\"a\", \"b\", \"c\"]}}"
MACAddress = "{{Random Type=\"MACAddress\" Separator=\"-\"}}"
})
.WithTransformer()
);

View File

@@ -0,0 +1,32 @@
using CommandLineParser.Arguments;
namespace WireMock.Net.StandAlone
{
public class CommandLineArguments
{
[ValueArgument(typeof(bool), "StartAdminInterface", DefaultValue = true, Description = "Start the AdminInterface")]
public bool StartAdminInterface { get; set; }
[ValueArgument(typeof(bool), "ReadStaticMappings", DefaultValue = false, Description = "Read StaticMappings")]
public bool ReadStaticMappings { get; set; }
[ValueArgument(typeof(bool), 'w', "WatchStaticMappings", DefaultValue = false, Description = "Watch the static mapping files + folder for changes when running.")]
public bool WatchStaticMappings { get; set; }
[ValueArgument(typeof(bool), 'm', "AllowPartialMapping", DefaultValue = false, Description = "Allow PartialMapping")]
public bool AllowPartialMapping { get; set; }
[ValueArgument(typeof(string), 'u', "AdminUsername", Description = "The username needed for __admin access.")]
public string AdminUsername { get; set; }
[ValueArgument(typeof(string), 'p', "AdminPassword", Description = "The password needed for __admin access.")]
public string AdminPassword { get; set; }
[BoundedValueArgument(typeof(int), 'o', "MaxRequestLogCount", MinValue = 0, Description = "The Maximum number of RequestLogs to keep")]
public int MaxRequestLogCount { get; set; }
[BoundedValueArgument(typeof(int), 'x', "RequestLogExpirationDuration", MinValue = 0, Description = "The RequestLog Expiration Duration in hours")]
public int RequestLogExpirationDuration { get; set; }
}
}

View File

@@ -38,8 +38,9 @@ namespace WireMock.Net.StandAlone
{
Check.NotNull(args, nameof(args));
var parser = new SimpleCommandLineParser();
parser.Parse(args);
var parser = new CommandLineParser.CommandLineParser();
var p = new CommandLineArguments();
parser.ExtractArgumentAttributes(p);
var settings = new FluentMockServerSettings
{

View File

@@ -41,6 +41,11 @@
</PropertyGroup>
<ItemGroup>
<Compile Remove="SimpleCommandLineParser.cs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="CommandLineArgumentsParser" Version="3.0.19" />
<PackageReference Include="JetBrains.Annotations" Version="2018.2.1">
<PrivateAssets>All</PrivateAssets>
</PackageReference>

View File

@@ -58,14 +58,6 @@ namespace WireMock.Client
[Header("Content-Type", "application/json")]
Task<StatusModel> PostMappingAsync([Body] MappingModel mapping);
/// <summary>
/// Add new mappings.
/// </summary>
/// <param name="mappings">MappingModels</param>
[Post("__admin/mappings")]
[Header("Content-Type", "application/json")]
Task<StatusModel> PostMappingsAsync([Body] IList<MappingModel> mappings);
/// <summary>
/// Delete all mappings.
/// </summary>

View File

@@ -1,35 +0,0 @@
using System;
namespace WireMock.Exceptions
{
/// <summary>
/// WireMockException
/// </summary>
/// <seealso cref="Exception" />
public class WireMockException : Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="WireMockException"/> class.
/// </summary>
public WireMockException()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="WireMockException"/> class.
/// </summary>
/// <param name="message">The message that describes the error.</param>
public WireMockException(string message) : base(message)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="WireMockException"/> class.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="inner">The inner.</param>
public WireMockException(string message, Exception inner) : base(message, inner)
{
}
}
}

View File

@@ -102,44 +102,49 @@ namespace WireMock.Serialization
mappingModel.Response.Headers = Map(response.ResponseMessage.Headers);
mappingModel.Response.UseTransformer = response.UseTransformer;
if (response.ResponseMessage.BodyData != null)
{
switch (response.ResponseMessage.BodyData?.DetectedBodyType)
{
case BodyType.String:
mappingModel.Response.Body = response.ResponseMessage.BodyData.BodyAsString;
break;
case BodyType.Json:
mappingModel.Response.BodyAsJson = response.ResponseMessage.BodyData.BodyAsJson;
mappingModel.Response.BodyAsJsonIndented = response.ResponseMessage.BodyData.BodyAsJsonIndented;
break;
case BodyType.Bytes:
mappingModel.Response.BodyAsBytes = response.ResponseMessage.BodyData.BodyAsBytes;
break;
case BodyType.File:
mappingModel.Response.BodyAsFile = response.ResponseMessage.BodyData.BodyAsFile;
mappingModel.Response.BodyAsFileIsCached = response.ResponseMessage.BodyData.BodyAsFileIsCached;
break;
}
if (response.ResponseMessage.BodyData.Encoding != null && response.ResponseMessage.BodyData.Encoding.WebName != "utf-8")
{
mappingModel.Response.BodyEncoding = new EncodingModel
{
EncodingName = response.ResponseMessage.BodyData.Encoding.EncodingName,
CodePage = response.ResponseMessage.BodyData.Encoding.CodePage,
WebName = response.ResponseMessage.BodyData.Encoding.WebName
};
}
}
MapBodyData(response, mappingModel);
}
return mappingModel;
}
private static void MapBodyData(Response response, MappingModel mappingModel)
{
if (response.ResponseMessage.BodyData != null)
{
switch (response.ResponseMessage.BodyData?.DetectedBodyType)
{
case BodyType.String:
mappingModel.Response.Body = response.ResponseMessage.BodyData.BodyAsString;
break;
case BodyType.Json:
mappingModel.Response.BodyAsJson = response.ResponseMessage.BodyData.BodyAsJson;
mappingModel.Response.BodyAsJsonIndented = response.ResponseMessage.BodyData.BodyAsJsonIndented;
break;
case BodyType.Bytes:
mappingModel.Response.BodyAsBytes = response.ResponseMessage.BodyData.BodyAsBytes;
break;
case BodyType.File:
mappingModel.Response.BodyAsFile = response.ResponseMessage.BodyData.BodyAsFile;
mappingModel.Response.BodyAsFileIsCached = response.ResponseMessage.BodyData.BodyAsFileIsCached;
break;
}
if (response.ResponseMessage.BodyData.Encoding != null && response.ResponseMessage.BodyData.Encoding.WebName != "utf-8")
{
mappingModel.Response.BodyEncoding = new EncodingModel
{
EncodingName = response.ResponseMessage.BodyData.Encoding.EncodingName,
CodePage = response.ResponseMessage.BodyData.Encoding.CodePage,
WebName = response.ResponseMessage.BodyData.Encoding.WebName
};
}
}
}
private static IDictionary<string, object> Map(IDictionary<string, WireMockList<string>> dictionary)
{
if (dictionary == null || dictionary.Count == 0)

View File

@@ -1,6 +1,3 @@
using JetBrains.Annotations;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
@@ -8,6 +5,9 @@ using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using JetBrains.Annotations;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using WireMock.Admin.Mappings;
using WireMock.Admin.Scenarios;
using WireMock.Admin.Settings;
@@ -412,21 +412,11 @@ namespace WireMock.Server
private ResponseMessage MappingsPost(RequestMessage requestMessage)
{
Guid? guid;
try
{
var mappingModels = DeserializeObjectArray<MappingModel>(requestMessage);
if (mappingModels.Length == 1)
{
Guid? guid = DeserializeAndAddOrUpdateMapping(mappingModels[0]);
return ResponseMessageBuilder.Create("Mapping added", 201, guid);
}
foreach (var mappingModel in mappingModels)
{
DeserializeAndAddOrUpdateMapping(mappingModel);
}
return ResponseMessageBuilder.Create("Mappings added", 201);
var mappingModel = DeserializeObject<MappingModel>(requestMessage);
guid = DeserializeAndAddOrUpdateMapping(mappingModel);
}
catch (ArgumentException a)
{
@@ -438,6 +428,8 @@ namespace WireMock.Server
_logger.Error("HttpStatusCode set to 500 {0}", e);
return ResponseMessageBuilder.Create(e.ToString(), 500);
}
return ResponseMessageBuilder.Create("Mapping added", 201, guid);
}
private Guid? DeserializeAndAddOrUpdateMapping(MappingModel mappingModel, Guid? guid = null, string path = null)
@@ -801,23 +793,5 @@ namespace WireMock.Server
return default(T);
}
private T[] DeserializeObjectArray<T>(RequestMessage requestMessage)
{
if (requestMessage?.BodyData?.DetectedBodyType == BodyType.Json)
{
var bodyAsJson = requestMessage.BodyData.BodyAsJson;
if (bodyAsJson is JArray jArray)
{
return jArray.ToObject<T[]>();
}
var value = ((JObject)requestMessage.BodyData.BodyAsJson).ToObject<T>();
return new[] { value };
}
return default(T[]);
}
}
}

View File

@@ -6,7 +6,6 @@ using System.Linq;
using System.Text;
using System.Threading;
using Newtonsoft.Json;
using WireMock.Exceptions;
using WireMock.Handlers;
using WireMock.Logging;
using WireMock.Matchers;
@@ -214,27 +213,21 @@ namespace WireMock.Server
#endif
Ports = _httpServer.Ports;
var startTask = _httpServer.StartAsync();
_httpServer.StartAsync();
using (var ctsStartTimeout = new CancellationTokenSource(settings.StartTimeout))
{
while (!_httpServer.IsStarted)
{
// Throw exception if service start fails
// Throw out exception if service start fails
if (_httpServer.RunningException != null)
{
throw new WireMockException($"Service start failed with error: {_httpServer.RunningException.Message}", _httpServer.RunningException);
throw new Exception($"Service start failed with error: {_httpServer.RunningException.Message}", _httpServer.RunningException);
}
// Respect start timeout setting by throwing TimeoutException
if (ctsStartTimeout.IsCancellationRequested)
{
// In case of an aggregate exception, throw the exception.
if (startTask.Exception != null)
{
throw new WireMockException($"Service start failed with error: {startTask.Exception.Message}", startTask.Exception);
}
// Else throw TimeoutException
throw new TimeoutException($"Service start timed out after {TimeSpan.FromMilliseconds(settings.StartTimeout)}");
}

View File

@@ -13,8 +13,6 @@ namespace WireMock.Transformers
HandleBarsLinq.Register(handlebarsContext);
HandleBarsRandom.Register(handlebarsContext);
HandleBarsXeger.Register(handlebarsContext);
}
}
}

View File

@@ -1,39 +0,0 @@
using System;
using Fare;
using HandlebarsDotNet;
using WireMock.Validation;
namespace WireMock.Transformers
{
internal static class HandleBarsXeger
{
public static void Register(IHandlebars handlebarsContext)
{
handlebarsContext.RegisterHelper("Xeger", (writer, context, arguments) =>
{
string value = ParseArgumentAndGenerate(arguments);
writer.Write(value);
});
handlebarsContext.RegisterHelper("Xeger", (writer, options, context, arguments) =>
{
string value = ParseArgumentAndGenerate(arguments);
options.Template(writer, value);
});
}
private static string ParseArgumentAndGenerate(object[] arguments)
{
Check.Condition(arguments, args => args.Length == 1, nameof(arguments));
Check.NotNull(arguments[0], "arguments[0]");
switch (arguments[0])
{
case string pattern:
return new Xeger(pattern).Generate();
}
throw new NotSupportedException($"The value '{arguments[0]}' with type '{arguments[0]?.GetType()}' cannot be used in Handlebars Xeger.");
}
}
}

View File

@@ -120,34 +120,23 @@ namespace WireMock.Transformers
string transformedString = templateForStringValue(template);
if (!string.Equals(stringValue, transformedString))
{
ReplaceNodeValue(node, transformedString);
JToken value;
try
{
// Try to convert this string into a real JsonObject
value = JToken.Parse(transformedString);
}
catch (JsonException)
{
// Ignore JsonException and just convert to JToken
value = transformedString;
}
node.Replace(value);
}
}
}
private static void ReplaceNodeValue(JToken node, string stringValue)
{
if (bool.TryParse(stringValue, out bool valueAsBoolean))
{
node.Replace(valueAsBoolean);
return;
}
JToken value;
try
{
// Try to convert this string into a JsonObject
value = JToken.Parse(stringValue);
}
catch (JsonException)
{
// Ignore JsonException and just keep string value and convert to JToken
value = stringValue;
}
node.Replace(value);
}
private static void TransformBodyAsString(object template, ResponseMessage original, ResponseMessage responseMessage)
{
var templateBody = HandlebarsContext.Compile(original.BodyData.BodyAsString);

View File

@@ -58,7 +58,7 @@
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
<PackageReference Include="System.Linq.Dynamic.Core" Version="1.0.9" />
<PackageReference Include="RandomDataGenerator.Net" Version="1.0.7" />
<PackageReference Include="RandomDataGenerator.Net" Version="1.0.4" />
</ItemGroup>
<ItemGroup Condition=" '$(TargetFramework)' == 'net451' ">

View File

@@ -1,9 +1,9 @@
using NFluent;
using RestEase;
using System.Linq;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using NFluent;
using RestEase;
using WireMock.Admin.Mappings;
using WireMock.Admin.Settings;
using WireMock.Client;
@@ -19,7 +19,7 @@ namespace WireMock.Net.Tests
[Fact]
public async Task IFluentMockServerAdmin_GetSettingsAsync()
{
// Arrange
// Assign
var server = FluentMockServer.StartWithAdminInterface();
var api = RestClient.For<IFluentMockServerAdmin>(server.Urls[0]);
@@ -31,7 +31,7 @@ namespace WireMock.Net.Tests
[Fact]
public async Task IFluentMockServerAdmin_PostSettingsAsync()
{
// Arrange
// Assign
var server = FluentMockServer.StartWithAdminInterface();
var api = RestClient.For<IFluentMockServerAdmin>(server.Urls[0]);
@@ -44,7 +44,7 @@ namespace WireMock.Net.Tests
[Fact]
public async Task IFluentMockServerAdmin_PutSettingsAsync()
{
// Arrange
// Assign
var server = FluentMockServer.StartWithAdminInterface();
var api = RestClient.For<IFluentMockServerAdmin>(server.Urls[0]);
@@ -57,15 +57,22 @@ namespace WireMock.Net.Tests
[Fact]
public async Task IFluentMockServerAdmin_PostMappingAsync()
{
// Arrange
// Assign
var server = FluentMockServer.StartWithAdminInterface();
var api = RestClient.For<IFluentMockServerAdmin>(server.Urls[0]);
// Act
var model = new MappingModel
{
Request = new RequestModel { Path = "/1" },
Response = new ResponseModel { Body = "txt", StatusCode = 200 },
Request = new RequestModel
{
Path = "/1"
},
Response = new ResponseModel
{
Body = "txt",
StatusCode = 200
},
Priority = 500,
Title = "test"
};
@@ -83,41 +90,10 @@ namespace WireMock.Net.Tests
server.Stop();
}
[Fact]
public async Task IFluentMockServerAdmin_PostMappingsAsync()
{
// Arrange
var server = FluentMockServer.StartWithAdminInterface();
var api = RestClient.For<IFluentMockServerAdmin>(server.Urls[0]);
// Act
var model1 = new MappingModel
{
Request = new RequestModel { Path = "/1" },
Response = new ResponseModel { Body = "txt 1" },
Title = "test 1"
};
var model2 = new MappingModel
{
Request = new RequestModel { Path = "/2" },
Response = new ResponseModel { Body = "txt 2" },
Title = "test 2"
};
var result = await api.PostMappingsAsync(new[] { model1, model2 });
// Assert
Check.That(result).IsNotNull();
Check.That(result.Status).IsNotNull();
Check.That(result.Guid).IsNull();
Check.That(server.Mappings.Where(m => !m.IsAdminInterface)).HasSize(2);
server.Stop();
}
[Fact]
public async Task IFluentMockServerAdmin_FindRequestsAsync()
{
// Arrange
// given
var server = FluentMockServer.Start(new FluentMockServerSettings
{
StartAdminInterface = true,
@@ -127,10 +103,10 @@ namespace WireMock.Net.Tests
await new HttpClient().GetAsync(serverUrl + "/foo");
var api = RestClient.For<IFluentMockServerAdmin>(serverUrl);
// Act
// when
var requests = await api.FindRequestsAsync(new RequestModel { Methods = new[] { "GET" } });
// Assert
// then
Check.That(requests).HasSize(1);
var requestLogged = requests.First();
Check.That(requestLogged.Request.Method).IsEqualTo("GET");
@@ -141,7 +117,7 @@ namespace WireMock.Net.Tests
[Fact]
public async Task IFluentMockServerAdmin_GetRequestsAsync()
{
// Arrange
// given
var server = FluentMockServer.Start(new FluentMockServerSettings
{
StartAdminInterface = true,
@@ -151,10 +127,10 @@ namespace WireMock.Net.Tests
await new HttpClient().GetAsync(serverUrl + "/foo");
var api = RestClient.For<IFluentMockServerAdmin>(serverUrl);
// Act
// when
var requests = await api.GetRequestsAsync();
// Assert
// then
Check.That(requests).HasSize(1);
var requestLogged = requests.First();
Check.That(requestLogged.Request.Method).IsEqualTo("GET");
@@ -165,7 +141,7 @@ namespace WireMock.Net.Tests
[Fact]
public async Task IFluentMockServerAdmin_GetRequestsAsync_JsonApi()
{
// Arrange
// given
var server = FluentMockServer.Start(new FluentMockServerSettings
{
StartAdminInterface = true,
@@ -183,14 +159,13 @@ namespace WireMock.Net.Tests
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(jsonApiContentType);
var response = await new HttpClient().SendAsync(request);
Check.That(response).IsNotNull();
var api = RestClient.For<IFluentMockServerAdmin>(serverUrl);
// Act
// when
var requests = await api.GetRequestsAsync();
// Assert
// then
Check.That(requests).HasSize(1);
var requestLogged = requests.First();
Check.That(requestLogged.Request.Method).IsEqualTo("POST");
@@ -201,7 +176,7 @@ namespace WireMock.Net.Tests
[Fact]
public async Task IFluentMockServerAdmin_GetRequestsAsync_Json()
{
// Arrange
// given
var server = FluentMockServer.Start(new FluentMockServerSettings
{
StartAdminInterface = true,
@@ -218,14 +193,13 @@ namespace WireMock.Net.Tests
request.Content = new StringContent(data);
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(jsonApiContentType);
var response = await new HttpClient().SendAsync(request);
Check.That(response).IsNotNull();
var api = RestClient.For<IFluentMockServerAdmin>(serverUrl);
// Act
// when
var requests = await api.GetRequestsAsync();
// Assert
// then
Check.That(requests).HasSize(1);
var requestLogged = requests.First();
Check.That(requestLogged.Request.Method).IsEqualTo("POST");

View File

@@ -34,30 +34,9 @@ namespace WireMock.Net.Tests.ResponseBuilders
// Assert
JObject j = JObject.FromObject(responseMessage.BodyData.BodyAsJson);
Check.That(j["Text"].Value<string>()).IsNotEmpty();
Check.That(j["Text"]).IsNotNull();
Check.That(j["Integer"].Value<int>()).IsEqualTo(1000);
Check.That(j["Long"].Value<long>()).IsStrictlyGreaterThan(77777777).And.IsStrictlyLessThan(99999999);
}
[Fact]
public async Task Response_ProvideResponseAsync_Handlebars_Random1_Boolean()
{
// Assign
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "GET", ClientIp);
var response = Response.Create()
.WithBodyAsJson(new
{
Value = "{{Random Type=\"Boolean\"}}"
})
.WithTransformer();
// Act
var responseMessage = await response.ProvideResponseAsync(request);
// Assert
JObject j = JObject.FromObject(responseMessage.BodyData.BodyAsJson);
Check.That(j["Value"].Type).IsEqualTo(JTokenType.Boolean);
Check.That(j["Long"].Value<int>()).IsStrictlyGreaterThan(77777777).And.IsStrictlyLessThan(99999999);
}
[Fact]

View File

@@ -1,60 +0,0 @@
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using NFluent;
using WireMock.Models;
using WireMock.ResponseBuilders;
using Xunit;
namespace WireMock.Net.Tests.ResponseBuilders
{
public class ResponseWithHandlebarsXegerTests
{
private const string ClientIp = "::1";
[Fact]
public async Task Response_ProvideResponseAsync_Handlebars_Xeger1()
{
// Assign
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "GET", ClientIp);
var response = Response.Create()
.WithBodyAsJson(new
{
Number = "{{Xeger \"[1-9]{1}\\d{3}\"}}",
Postcode = "{{Xeger \"[1-9][0-9]{3}[A-Z]{2}\"}}"
})
.WithTransformer();
// Act
var responseMessage = await response.ProvideResponseAsync(request);
// Assert
JObject j = JObject.FromObject(responseMessage.BodyData.BodyAsJson);
Check.That(j["Number"].Value<int>()).IsStrictlyGreaterThan(1000).And.IsStrictlyLessThan(9999);
Check.That(j["Postcode"].Value<string>()).IsNotEmpty();
}
[Fact]
public async Task Response_ProvideResponseAsync_Handlebars_Xeger2()
{
// Assign
var request = new RequestMessage(new UrlDetails("http://localhost:1234"), "GET", ClientIp);
var response = Response.Create()
.WithBodyAsJson(new
{
Number = "{{#Xeger \"[1-9]{1}\\d{3}\"}}{{this}}{{/Xeger}}",
Postcode = "{{#Xeger \"[1-9][0-9]{3}[A-Z]{2}\"}}{{this}}{{/Xeger}}"
})
.WithTransformer();
// Act
var responseMessage = await response.ProvideResponseAsync(request);
// Assert
JObject j = JObject.FromObject(responseMessage.BodyData.BodyAsJson);
Check.That(j["Number"].Value<int>()).IsStrictlyGreaterThan(1000).And.IsStrictlyLessThan(9999);
Check.That(j["Postcode"].Value<string>()).IsNotEmpty();
}
}
}