mirror of
https://github.com/wiremock/WireMock.Net.git
synced 2026-01-15 08:03:31 +01:00
Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dd115a69b7 | ||
|
|
12444cc11e | ||
|
|
6c32b9c31a | ||
|
|
3d845d5be5 |
@@ -1,3 +1,11 @@
|
||||
# 1.0.13.0 (11 April 2019)
|
||||
- [#266](https://github.com/WireMock-Net/WireMock.Net/pull/266) - [265] Add file upload to allow mocking of file operations contributed by [JackCreativeCrew](https://github.com/JackCreativeCrew)
|
||||
- [#265](https://github.com/WireMock-Net/WireMock.Net/issues/265) - File Upload [feature]
|
||||
|
||||
# 1.0.12.0 (05 April 2019)
|
||||
- [#264](https://github.com/WireMock-Net/WireMock.Net/pull/264) - Proxy : also save multipart as string in mapping file contributed by [StefH](https://github.com/StefH)
|
||||
- [#263](https://github.com/WireMock-Net/WireMock.Net/issues/263) - Content-Type multipart/form-data is not serialized in proxy and recording mode [bug]
|
||||
|
||||
# 1.0.11.0 (30 March 2019)
|
||||
- [#261](https://github.com/WireMock-Net/WireMock.Net/pull/261) - Fix BodyAsJson transform bug in ResponseMessageTransformer contributed by [psypilat](https://github.com/psypilat)
|
||||
- [#262](https://github.com/WireMock-Net/WireMock.Net/pull/262) - Add ProvideResponse_WithJsonBodyAndTransform test contributed by [psypilat](https://github.com/psypilat)
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup>
|
||||
<VersionPrefix>1.0.11</VersionPrefix>
|
||||
<VersionPrefix>1.0.13</VersionPrefix>
|
||||
</PropertyGroup>
|
||||
|
||||
<Choose>
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
https://github.com/StefH/GitHubReleaseNotes
|
||||
|
||||
GitHubReleaseNotes.exe --output CHANGELOG.md --skip-empty-releases --version 1.0.11.0
|
||||
GitHubReleaseNotes.exe --output CHANGELOG.md --skip-empty-releases --version 1.0.13.0
|
||||
@@ -52,6 +52,12 @@ namespace WireMock.Net.Client
|
||||
var scenarioStates = api.GetScenariosAsync().Result;
|
||||
Console.WriteLine($"GetScenariosAsync = {JsonConvert.SerializeObject(scenarioStates)}");
|
||||
|
||||
var postFileResult = api.PostFileAsync("1.cs", "C# Hello").GetAwaiter().GetResult();
|
||||
Console.WriteLine($"postFileResult = {JsonConvert.SerializeObject(postFileResult)}");
|
||||
|
||||
var getFileResult = api.GetFileAsync("1.cs").GetAwaiter().GetResult();
|
||||
Console.WriteLine($"getFileResult = {getFileResult}");
|
||||
|
||||
Console.WriteLine("Press any key to quit");
|
||||
Console.ReadKey();
|
||||
}
|
||||
|
||||
@@ -49,5 +49,39 @@ namespace WireMock.Net.ConsoleApplication
|
||||
{
|
||||
return File.ReadAllBytes(Path.GetFileName(path) == path ? Path.Combine(GetMappingFolder(), path) : path);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IFileSystemHandler.FileExists"/>
|
||||
public bool FileExists(string path)
|
||||
{
|
||||
return File.Exists(AdjustPath(path));
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IFileSystemHandler.WriteFile(string, byte[])"/>
|
||||
public void WriteFile(string path, byte[] bytes)
|
||||
{
|
||||
File.WriteAllBytes(AdjustPath(path), bytes);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IFileSystemHandler.DeleteFile"/>
|
||||
public void DeleteFile(string path)
|
||||
{
|
||||
File.Delete(AdjustPath(path));
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IFileSystemHandler.ReadFile"/>
|
||||
public byte[] ReadFile(string path)
|
||||
{
|
||||
return File.ReadAllBytes(AdjustPath(path));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adjusts the path to the MappingFolder.
|
||||
/// </summary>
|
||||
/// <param name="path">The path.</param>
|
||||
/// <returns>Adjusted path</returns>
|
||||
private string AdjustPath(string path)
|
||||
{
|
||||
return Path.Combine(GetMappingFolder(), path);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
using Newtonsoft.Json;
|
||||
using System;
|
||||
using System.Net.Http;
|
||||
using Newtonsoft.Json;
|
||||
using WireMock.Server;
|
||||
using WireMock.Settings;
|
||||
|
||||
@@ -8,14 +10,15 @@ namespace WireMock.Net.Console.Proxy.Net452
|
||||
{
|
||||
static void Main(string[] args)
|
||||
{
|
||||
string[] urls = { "http://localhost:9091/", "https://localhost:9443/" };
|
||||
var server = FluentMockServer.Start(new FluentMockServerSettings
|
||||
{
|
||||
Urls = new[] { "http://localhost:9091/", "https://localhost:9443/" },
|
||||
Urls = urls,
|
||||
StartAdminInterface = true,
|
||||
ReadStaticMappings = false,
|
||||
ProxyAndRecordSettings = new ProxyAndRecordSettings
|
||||
{
|
||||
Url = "https://www.google.com",
|
||||
Url = "http://postman-echo.com/post",
|
||||
//ClientX509Certificate2ThumbprintOrSubjectName = "www.yourclientcertname.com OR yourcertificatethumbprint (only if the service you're proxying to requires it)",
|
||||
SaveMapping = true,
|
||||
SaveMappingToFile = false,
|
||||
@@ -28,6 +31,13 @@ namespace WireMock.Net.Console.Proxy.Net452
|
||||
System.Console.WriteLine(JsonConvert.SerializeObject(eventRecordArgs.NewItems, Formatting.Indented));
|
||||
};
|
||||
|
||||
var uri = new Uri(urls[0]);
|
||||
var form = new MultipartFormDataContent
|
||||
{
|
||||
{ new StringContent("data"), "test", "test.txt" }
|
||||
};
|
||||
new HttpClient().PostAsync(uri, form).GetAwaiter().GetResult();
|
||||
|
||||
System.Console.WriteLine("Press any key to stop the server");
|
||||
System.Console.ReadKey();
|
||||
server.Stop();
|
||||
|
||||
@@ -167,5 +167,42 @@ namespace WireMock.Client
|
||||
/// </summary>
|
||||
[Post("__admin/scenarios")]
|
||||
Task<StatusModel> ResetScenariosAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Create a new File
|
||||
/// </summary>
|
||||
/// <param name="filename">The filename</param>
|
||||
/// <param name="body">The body</param>
|
||||
[Post("__admin/files/{filename}")]
|
||||
Task<StatusModel> PostFileAsync([Path] string filename, [Body] string body);
|
||||
|
||||
/// <summary>
|
||||
/// Update an existing File
|
||||
/// </summary>
|
||||
/// <param name="filename">The filename</param>
|
||||
/// <param name="body">The body</param>
|
||||
[Put("__admin/files/{filename}")]
|
||||
Task<StatusModel> PutFileAsync([Path] string filename, [Body] string body);
|
||||
|
||||
/// <summary>
|
||||
/// Get the content of an existing File
|
||||
/// </summary>
|
||||
/// <param name="filename">The filename</param>
|
||||
[Get("__admin/files/{filename}")]
|
||||
Task<string> GetFileAsync([Path] string filename);
|
||||
|
||||
/// <summary>
|
||||
/// Delete an existing File
|
||||
/// </summary>
|
||||
/// <param name="filename">The filename</param>
|
||||
[Delete("__admin/files/{filename}")]
|
||||
Task<StatusModel> DeleteFileAsync([Path] string filename);
|
||||
|
||||
/// <summary>
|
||||
/// Check if a file exists
|
||||
/// </summary>
|
||||
/// <param name="filename">The filename</param>
|
||||
[Head("__admin/files/{filename}")]
|
||||
Task FileExistsAsync([Path] string filename);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using System.Collections.Generic;
|
||||
using JetBrains.Annotations;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace WireMock.Handlers
|
||||
{
|
||||
@@ -18,40 +19,67 @@ namespace WireMock.Handlers
|
||||
/// </summary>
|
||||
/// <param name="path">The path.</param>
|
||||
/// <returns>true if path refers to an existing directory; false if the directory does not exist or an error occurs when trying to determine if the specified directory exists.</returns>
|
||||
bool FolderExists(string path);
|
||||
bool FolderExists([NotNull] string path);
|
||||
|
||||
/// <summary>
|
||||
/// Creates all directories and subdirectories in the specified path unless they already exist.
|
||||
/// </summary>
|
||||
/// <param name="path">The path.</param>
|
||||
void CreateFolder(string path);
|
||||
void CreateFolder([NotNull] string path);
|
||||
|
||||
/// <summary>
|
||||
/// Returns an enumerable collection of file names in a specified path.
|
||||
/// </summary>
|
||||
/// <param name="path">The path.</param>
|
||||
/// <returns>An enumerable collection of the full names (including paths) for the files in the directory specified by path.</returns>
|
||||
IEnumerable<string> EnumerateFiles(string path);
|
||||
IEnumerable<string> EnumerateFiles([NotNull] string path);
|
||||
|
||||
/// <summary>
|
||||
/// Read a static mapping file as text.
|
||||
/// </summary>
|
||||
/// <param name="path">The path (folder + filename with .json extension).</param>
|
||||
/// <returns>The file content as text.</returns>
|
||||
string ReadMappingFile(string path);
|
||||
string ReadMappingFile([NotNull] string path);
|
||||
|
||||
/// <summary>
|
||||
/// Write the static mapping.
|
||||
/// Write the static mapping file.
|
||||
/// </summary>
|
||||
/// <param name="path">The path (folder + filename with .json extension).</param>
|
||||
/// <param name="text">The text.</param>
|
||||
void WriteMappingFile(string path, string text);
|
||||
void WriteMappingFile([NotNull] string path, [NotNull] string text);
|
||||
|
||||
/// <summary>
|
||||
/// Read a response body file as text.
|
||||
/// </summary>
|
||||
/// <param name="path">The path or filename from the file to read.</param>
|
||||
/// <returns>The file content as bytes.</returns>
|
||||
byte[] ReadResponseBodyAsFile(string path);
|
||||
byte[] ReadResponseBodyAsFile([NotNull] string path);
|
||||
|
||||
/// <summary>
|
||||
/// Delete a file.
|
||||
/// </summary>
|
||||
/// <param name="filename">The filename.</param>
|
||||
void DeleteFile([NotNull] string filename);
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the given path refers to an existing file on disk.
|
||||
/// </summary>
|
||||
/// <param name="filename">The filename.</param>
|
||||
/// <returns>true if path refers to an existing file; false if the file does not exist.</returns>
|
||||
bool FileExists([NotNull] string filename);
|
||||
|
||||
/// <summary>
|
||||
/// Write a file.
|
||||
/// </summary>
|
||||
/// <param name="filename">The filename.</param>
|
||||
/// <param name="bytes">The bytes.</param>
|
||||
void WriteFile([NotNull] string filename, [NotNull] byte[] bytes);
|
||||
|
||||
/// <summary>
|
||||
/// Read a file as bytes.
|
||||
/// </summary>
|
||||
/// <param name="filename">The filename.</param>
|
||||
/// <returns>The file content as bytes.</returns>
|
||||
byte[] ReadFile([NotNull] string filename);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
using JetBrains.Annotations;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using WireMock.Validation;
|
||||
|
||||
@@ -13,7 +12,7 @@ namespace WireMock.Handlers
|
||||
private static readonly string AdminMappingsFolder = Path.Combine("__admin", "mappings");
|
||||
|
||||
/// <inheritdoc cref="IFileSystemHandler.FolderExists"/>
|
||||
public bool FolderExists([NotNull] string path)
|
||||
public bool FolderExists(string path)
|
||||
{
|
||||
Check.NotNullOrEmpty(path, nameof(path));
|
||||
|
||||
@@ -21,7 +20,7 @@ namespace WireMock.Handlers
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IFileSystemHandler.CreateFolder"/>
|
||||
public void CreateFolder([NotNull] string path)
|
||||
public void CreateFolder(string path)
|
||||
{
|
||||
Check.NotNullOrEmpty(path, nameof(path));
|
||||
|
||||
@@ -29,7 +28,7 @@ namespace WireMock.Handlers
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IFileSystemHandler.EnumerateFiles"/>
|
||||
public IEnumerable<string> EnumerateFiles([NotNull] string path)
|
||||
public IEnumerable<string> EnumerateFiles(string path)
|
||||
{
|
||||
Check.NotNullOrEmpty(path, nameof(path));
|
||||
|
||||
@@ -43,15 +42,15 @@ namespace WireMock.Handlers
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IFileSystemHandler.ReadMappingFile"/>
|
||||
public string ReadMappingFile([NotNull] string path)
|
||||
public string ReadMappingFile(string path)
|
||||
{
|
||||
Check.NotNullOrEmpty(path, nameof(path));
|
||||
|
||||
return File.ReadAllText(path);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IFileSystemHandler.WriteMappingFile"/>
|
||||
public void WriteMappingFile([NotNull] string path, [NotNull] string text)
|
||||
/// <inheritdoc cref="IFileSystemHandler.WriteMappingFile(string, string)"/>
|
||||
public void WriteMappingFile(string path, string text)
|
||||
{
|
||||
Check.NotNullOrEmpty(path, nameof(path));
|
||||
Check.NotNull(text, nameof(text));
|
||||
@@ -68,5 +67,48 @@ namespace WireMock.Handlers
|
||||
// Else the path will just be as-is.
|
||||
return File.ReadAllBytes(Path.GetFileName(path) == path ? Path.Combine(GetMappingFolder(), path) : path);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IFileSystemHandler.FileExists"/>
|
||||
public bool FileExists(string filename)
|
||||
{
|
||||
Check.NotNullOrEmpty(filename, nameof(filename));
|
||||
|
||||
return File.Exists(AdjustPath(filename));
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IFileSystemHandler.WriteFile(string, byte[])"/>
|
||||
public void WriteFile(string filename, byte[] bytes)
|
||||
{
|
||||
Check.NotNullOrEmpty(filename, nameof(filename));
|
||||
Check.NotNull(bytes, nameof(bytes));
|
||||
|
||||
File.WriteAllBytes(AdjustPath(filename), bytes);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IFileSystemHandler.DeleteFile"/>
|
||||
public void DeleteFile(string filename)
|
||||
{
|
||||
Check.NotNullOrEmpty(filename, nameof(filename));
|
||||
|
||||
File.Delete(AdjustPath(filename));
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IFileSystemHandler.ReadFile"/>
|
||||
public byte[] ReadFile(string filename)
|
||||
{
|
||||
Check.NotNullOrEmpty(filename, nameof(filename));
|
||||
|
||||
return File.ReadAllBytes(AdjustPath(filename));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adjusts the path to the MappingFolder.
|
||||
/// </summary>
|
||||
/// <param name="filename">The path.</param>
|
||||
/// <returns>Adjusted path</returns>
|
||||
private string AdjustPath(string filename)
|
||||
{
|
||||
return Path.Combine(GetMappingFolder(), filename);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
using System.Linq;
|
||||
using JetBrains.Annotations;
|
||||
using JetBrains.Annotations;
|
||||
using System.Linq;
|
||||
using WireMock.Validation;
|
||||
|
||||
namespace WireMock.Matchers
|
||||
@@ -10,8 +10,9 @@ namespace WireMock.Matchers
|
||||
/// <seealso cref="IObjectMatcher" />
|
||||
public class ExactObjectMatcher : IObjectMatcher
|
||||
{
|
||||
private readonly object _object;
|
||||
private readonly byte[] _bytes;
|
||||
public object ValueAsObject { get; }
|
||||
|
||||
public byte[] ValueAsBytes { get; }
|
||||
|
||||
/// <inheritdoc cref="IMatcher.MatchBehaviour"/>
|
||||
public MatchBehaviour MatchBehaviour { get; }
|
||||
@@ -33,7 +34,7 @@ namespace WireMock.Matchers
|
||||
{
|
||||
Check.NotNull(value, nameof(value));
|
||||
|
||||
_object = value;
|
||||
ValueAsObject = value;
|
||||
MatchBehaviour = matchBehaviour;
|
||||
}
|
||||
|
||||
@@ -54,14 +55,14 @@ namespace WireMock.Matchers
|
||||
{
|
||||
Check.NotNull(value, nameof(value));
|
||||
|
||||
_bytes = value;
|
||||
ValueAsBytes = value;
|
||||
MatchBehaviour = matchBehaviour;
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="IObjectMatcher.IsMatch"/>
|
||||
public double IsMatch(object input)
|
||||
{
|
||||
bool equals = _object != null ? Equals(_object, input) : _bytes.SequenceEqual((byte[])input);
|
||||
bool equals = ValueAsObject != null ? Equals(ValueAsObject, input) : ValueAsBytes.SequenceEqual((byte[])input);
|
||||
return MatchBehaviourHelper.Convert(MatchBehaviour, MatchScores.ToScore(equals));
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,10 @@ namespace WireMock
|
||||
internal static class ResponseMessageBuilder
|
||||
{
|
||||
private static string ContentTypeJson = "application/json";
|
||||
private static readonly IDictionary<string, WireMockList<string>> ContentTypeJsonHeaders = new Dictionary<string, WireMockList<string>> { { HttpKnownHeaderNames.ContentType, new WireMockList<string> { ContentTypeJson } } };
|
||||
private static readonly IDictionary<string, WireMockList<string>> ContentTypeJsonHeaders = new Dictionary<string, WireMockList<string>>
|
||||
{
|
||||
{ HttpKnownHeaderNames.ContentType, new WireMockList<string> { ContentTypeJson } }
|
||||
};
|
||||
|
||||
internal static ResponseMessage Create(string message, int statusCode = 200, Guid? guid = null)
|
||||
{
|
||||
@@ -30,5 +33,13 @@ namespace WireMock
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
internal static ResponseMessage Create(int statusCode)
|
||||
{
|
||||
return new ResponseMessage
|
||||
{
|
||||
StatusCode = statusCode
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -77,7 +77,7 @@ namespace WireMock.Serialization
|
||||
},
|
||||
Response = new ResponseModel
|
||||
{
|
||||
Delay = (int?) response.Delay?.TotalMilliseconds
|
||||
Delay = (int?)response.Delay?.TotalMilliseconds
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
using System;
|
||||
using JetBrains.Annotations;
|
||||
using SimMetrics.Net;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using JetBrains.Annotations;
|
||||
using SimMetrics.Net;
|
||||
using WireMock.Admin.Mappings;
|
||||
using WireMock.Matchers;
|
||||
|
||||
@@ -32,6 +32,10 @@ namespace WireMock.Serialization
|
||||
case "ExactMatcher":
|
||||
return new ExactMatcher(matchBehaviour, stringPatterns);
|
||||
|
||||
case "ExactObjectMatcher":
|
||||
var bytePattern = Convert.FromBase64String(stringPatterns[0]);
|
||||
return new ExactObjectMatcher(matchBehaviour, bytePattern);
|
||||
|
||||
case "RegexMatcher":
|
||||
return new RegexMatcher(matchBehaviour, stringPatterns, matcher.IgnoreCase == true);
|
||||
|
||||
@@ -73,20 +77,33 @@ namespace WireMock.Serialization
|
||||
return null;
|
||||
}
|
||||
|
||||
// If the matcher is a IStringMatcher, get the patterns.
|
||||
// If the matcher is a IValueMatcher, get the value (can be string or object).
|
||||
// Else empty array
|
||||
object[] patterns = matcher is IStringMatcher stringMatcher ?
|
||||
stringMatcher.GetPatterns().Cast<object>().ToArray() :
|
||||
matcher is IValueMatcher valueMatcher ? new[] { valueMatcher.Value } :
|
||||
new object[0];
|
||||
bool? ignorecase = matcher is IIgnoreCaseMatcher ignoreCaseMatcher ? ignoreCaseMatcher.IgnoreCase : (bool?)null;
|
||||
object[] patterns = new object[0]; // Default empty array
|
||||
switch (matcher)
|
||||
{
|
||||
// If the matcher is a IStringMatcher, get the patterns.
|
||||
case IStringMatcher stringMatcher:
|
||||
patterns = stringMatcher.GetPatterns().Cast<object>().ToArray();
|
||||
break;
|
||||
|
||||
// If the matcher is a IValueMatcher, get the value (can be string or object).
|
||||
case IValueMatcher valueMatcher:
|
||||
patterns = new[] { valueMatcher.Value };
|
||||
break;
|
||||
|
||||
// If the matcher is a ExactObjectMatcher, get the ValueAsObject or ValueAsBytes.
|
||||
case ExactObjectMatcher exactObjectMatcher:
|
||||
patterns = new[] { exactObjectMatcher.ValueAsObject ?? exactObjectMatcher.ValueAsBytes };
|
||||
break;
|
||||
}
|
||||
|
||||
bool? ignoreCase = matcher is IIgnoreCaseMatcher ignoreCaseMatcher ? ignoreCaseMatcher.IgnoreCase : (bool?)null;
|
||||
|
||||
bool? rejectOnMatch = matcher.MatchBehaviour == MatchBehaviour.RejectOnMatch ? true : (bool?)null;
|
||||
|
||||
return new MatcherModel
|
||||
{
|
||||
RejectOnMatch = rejectOnMatch,
|
||||
IgnoreCase = ignorecase,
|
||||
IgnoreCase = ignoreCase,
|
||||
Name = matcher.Name,
|
||||
Pattern = patterns.Length == 1 ? patterns.First() : null,
|
||||
Patterns = patterns.Length > 1 ? patterns : null
|
||||
|
||||
@@ -34,13 +34,14 @@ namespace WireMock.Server
|
||||
private const int AdminPriority = int.MinValue;
|
||||
private const int ProxyPriority = 1000;
|
||||
private const string ContentTypeJson = "application/json";
|
||||
private const string AdminFiles = "/__admin/files";
|
||||
private const string AdminMappings = "/__admin/mappings";
|
||||
private const string AdminRequests = "/__admin/requests";
|
||||
private const string AdminSettings = "/__admin/settings";
|
||||
private const string AdminScenarios = "/__admin/scenarios";
|
||||
|
||||
private readonly RegexMatcher _adminMappingsGuidPathMatcher = new RegexMatcher(MatchBehaviour.AcceptOnMatch, @"^\/__admin\/mappings\/(\{{0,1}([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}\}{0,1})$");
|
||||
private readonly RegexMatcher _adminRequestsGuidPathMatcher = new RegexMatcher(MatchBehaviour.AcceptOnMatch, @"^\/__admin\/requests\/(\{{0,1}([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}\}{0,1})$");
|
||||
private readonly RegexMatcher _adminMappingsGuidPathMatcher = new RegexMatcher(MatchBehaviour.AcceptOnMatch, @"^\/__admin\/mappings\/([0-9A-Fa-f]{8}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{12})$");
|
||||
private readonly RegexMatcher _adminRequestsGuidPathMatcher = new RegexMatcher(MatchBehaviour.AcceptOnMatch, @"^\/__admin\/requests\/([0-9A-Fa-f]{8}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{12})$");
|
||||
|
||||
private readonly JsonSerializerSettings _settings = new JsonSerializerSettings
|
||||
{
|
||||
@@ -97,10 +98,17 @@ namespace WireMock.Server
|
||||
|
||||
// __admin/scenarios/reset
|
||||
Given(Request.Create().WithPath(AdminScenarios + "/reset").UsingPost()).AtPriority(AdminPriority).RespondWith(new DynamicResponseProvider(ScenariosReset));
|
||||
|
||||
// __admin/files/{filename}
|
||||
Given(Request.Create().WithPath(_adminFilesFilenamePathMatcher).UsingPost()).AtPriority(AdminPriority).RespondWith(new DynamicResponseProvider(FilePost));
|
||||
Given(Request.Create().WithPath(_adminFilesFilenamePathMatcher).UsingPut()).AtPriority(AdminPriority).RespondWith(new DynamicResponseProvider(FilePut));
|
||||
Given(Request.Create().WithPath(_adminFilesFilenamePathMatcher).UsingGet()).AtPriority(AdminPriority).RespondWith(new DynamicResponseProvider(FileGet));
|
||||
Given(Request.Create().WithPath(_adminFilesFilenamePathMatcher).UsingHead()).AtPriority(AdminPriority).RespondWith(new DynamicResponseProvider(FileHead));
|
||||
Given(Request.Create().WithPath(_adminFilesFilenamePathMatcher).UsingDelete()).AtPriority(AdminPriority).RespondWith(new DynamicResponseProvider(FileDelete));
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region StaticMappings
|
||||
#region StaticMappings
|
||||
/// <summary>
|
||||
/// Saves the static mappings.
|
||||
/// </summary>
|
||||
@@ -277,13 +285,19 @@ namespace WireMock.Server
|
||||
}
|
||||
});
|
||||
|
||||
if (requestMessage.BodyData?.DetectedBodyType == BodyType.Json)
|
||||
switch (requestMessage.BodyData?.DetectedBodyType)
|
||||
{
|
||||
request.WithBody(new JsonMatcher(MatchBehaviour.AcceptOnMatch, requestMessage.BodyData.BodyAsJson));
|
||||
}
|
||||
else if (requestMessage.BodyData?.DetectedBodyType == BodyType.String)
|
||||
{
|
||||
request.WithBody(new ExactMatcher(MatchBehaviour.AcceptOnMatch, requestMessage.BodyData.BodyAsString));
|
||||
case BodyType.Json:
|
||||
request.WithBody(new JsonMatcher(MatchBehaviour.AcceptOnMatch, requestMessage.BodyData.BodyAsJson));
|
||||
break;
|
||||
|
||||
case BodyType.String:
|
||||
request.WithBody(new ExactMatcher(MatchBehaviour.AcceptOnMatch, requestMessage.BodyData.BodyAsString));
|
||||
break;
|
||||
|
||||
case BodyType.Bytes:
|
||||
request.WithBody(new ExactObjectMatcher(MatchBehaviour.AcceptOnMatch, requestMessage.BodyData.BodyAsBytes));
|
||||
break;
|
||||
}
|
||||
|
||||
var response = Response.Create(responseMessage);
|
||||
|
||||
114
src/WireMock.Net/Server/FluentMockServer.AdminFiles.cs
Normal file
114
src/WireMock.Net/Server/FluentMockServer.AdminFiles.cs
Normal file
@@ -0,0 +1,114 @@
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using WireMock.Matchers;
|
||||
using WireMock.Util;
|
||||
|
||||
namespace WireMock.Server
|
||||
{
|
||||
public partial class FluentMockServer
|
||||
{
|
||||
private readonly RegexMatcher _adminFilesFilenamePathMatcher = new RegexMatcher(MatchBehaviour.AcceptOnMatch, @"^\/__admin\/files\/.*$");
|
||||
private static readonly Encoding[] FileBodyIsString = { Encoding.UTF8, Encoding.ASCII };
|
||||
|
||||
#region Files/{filename}
|
||||
private ResponseMessage FilePost(RequestMessage requestMessage)
|
||||
{
|
||||
string filename = GetFileNameFromRequestMessage(requestMessage);
|
||||
|
||||
string mappingFolder = _fileSystemHandler.GetMappingFolder();
|
||||
if (!_fileSystemHandler.FolderExists(mappingFolder))
|
||||
{
|
||||
_fileSystemHandler.CreateFolder(mappingFolder);
|
||||
}
|
||||
|
||||
_fileSystemHandler.WriteFile(filename, requestMessage.BodyAsBytes);
|
||||
|
||||
return ResponseMessageBuilder.Create("File created");
|
||||
}
|
||||
|
||||
private ResponseMessage FilePut(RequestMessage requestMessage)
|
||||
{
|
||||
string filename = GetFileNameFromRequestMessage(requestMessage);
|
||||
|
||||
if (!_fileSystemHandler.FileExists(filename))
|
||||
{
|
||||
_logger.Info("The file '{0}' does not exist, updating file will be skipped.", filename);
|
||||
return ResponseMessageBuilder.Create("File is not found", 404);
|
||||
}
|
||||
|
||||
_fileSystemHandler.WriteFile(filename, requestMessage.BodyAsBytes);
|
||||
|
||||
return ResponseMessageBuilder.Create("File updated");
|
||||
}
|
||||
|
||||
private ResponseMessage FileGet(RequestMessage requestMessage)
|
||||
{
|
||||
string filename = GetFileNameFromRequestMessage(requestMessage);
|
||||
|
||||
if (!_fileSystemHandler.FileExists(filename))
|
||||
{
|
||||
_logger.Info("The file '{0}' does not exist.", filename);
|
||||
return ResponseMessageBuilder.Create("File is not found", 404);
|
||||
}
|
||||
|
||||
byte[] bytes = _fileSystemHandler.ReadFile(filename);
|
||||
var response = new ResponseMessage
|
||||
{
|
||||
StatusCode = 200,
|
||||
BodyData = new BodyData
|
||||
{
|
||||
BodyAsBytes = bytes,
|
||||
DetectedBodyType = BodyType.Bytes,
|
||||
DetectedBodyTypeFromContentType = BodyType.None
|
||||
}
|
||||
};
|
||||
|
||||
if (BytesEncodingUtils.TryGetEncoding(bytes, out Encoding encoding) && FileBodyIsString.Select(x => x.Equals(encoding)).Any())
|
||||
{
|
||||
response.BodyData.DetectedBodyType = BodyType.String;
|
||||
response.BodyData.BodyAsString = encoding.GetString(bytes);
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Checks if file exists.
|
||||
/// Note: Response is returned with no body as a head request doesn't accept a body, only the status code.
|
||||
/// </summary>
|
||||
/// <param name="requestMessage">The request message.</param>
|
||||
private ResponseMessage FileHead(RequestMessage requestMessage)
|
||||
{
|
||||
string filename = GetFileNameFromRequestMessage(requestMessage);
|
||||
|
||||
if (!_fileSystemHandler.FileExists(filename))
|
||||
{
|
||||
_logger.Info("The file '{0}' does not exist.", filename);
|
||||
return ResponseMessageBuilder.Create(404);
|
||||
}
|
||||
|
||||
return ResponseMessageBuilder.Create(204);
|
||||
}
|
||||
|
||||
private ResponseMessage FileDelete(RequestMessage requestMessage)
|
||||
{
|
||||
string filename = GetFileNameFromRequestMessage(requestMessage);
|
||||
|
||||
if (!_fileSystemHandler.FileExists(filename))
|
||||
{
|
||||
_logger.Info("The file '{0}' does not exist.", filename);
|
||||
return ResponseMessageBuilder.Create("File is not deleted", 404);
|
||||
}
|
||||
|
||||
_fileSystemHandler.DeleteFile(filename);
|
||||
return ResponseMessageBuilder.Create("File deleted.");
|
||||
}
|
||||
|
||||
private string GetFileNameFromRequestMessage(RequestMessage requestMessage)
|
||||
{
|
||||
return Path.GetFileName(requestMessage.Path.Substring(AdminFiles.Length + 1));
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@ namespace WireMock.Util
|
||||
internal static class BodyParser
|
||||
{
|
||||
private static readonly Encoding DefaultEncoding = Encoding.UTF8;
|
||||
private static readonly Encoding[] SupportedBodyAsStringEncodingForMultipart = { Encoding.UTF8, Encoding.ASCII };
|
||||
|
||||
/*
|
||||
HEAD - No defined body semantics.
|
||||
@@ -91,9 +92,19 @@ namespace WireMock.Util
|
||||
DetectedBodyTypeFromContentType = DetectBodyTypeFromContentType(contentType)
|
||||
};
|
||||
|
||||
// In case of MultiPart: never try to read as String but keep as-is
|
||||
// In case of MultiPart: check if the BodyAsBytes is a valid UTF8 or ASCII string, in that case read as String else keep as-is
|
||||
if (data.DetectedBodyTypeFromContentType == BodyType.MultiPart)
|
||||
{
|
||||
if (BytesEncodingUtils.TryGetEncoding(data.BodyAsBytes, out Encoding encoding) &&
|
||||
SupportedBodyAsStringEncodingForMultipart.Select(x => x.Equals(encoding)).Any())
|
||||
{
|
||||
data.BodyAsString = encoding.GetString(data.BodyAsBytes);
|
||||
data.Encoding = encoding;
|
||||
data.DetectedBodyType = BodyType.String;
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
|
||||
230
src/WireMock.Net/Util/BytesEncodingUtils.cs
Normal file
230
src/WireMock.Net/Util/BytesEncodingUtils.cs
Normal file
@@ -0,0 +1,230 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace WireMock.Util
|
||||
{
|
||||
/// <summary>
|
||||
/// Based on:
|
||||
/// http://utf8checker.codeplex.com
|
||||
/// https://github.com/0x53A/Mvvm/blob/master/src/Mvvm/src/Utf8Checker.cs
|
||||
///
|
||||
/// References:
|
||||
/// http://anubis.dkuug.dk/JTC1/SC2/WG2/docs/n1335
|
||||
/// http://www.cl.cam.ac.uk/~mgk25/ucs/ISO-10646-UTF-8.html
|
||||
/// http://www.unicode.org/versions/corrigendum1.html
|
||||
/// http://www.ietf.org/rfc/rfc2279.txt
|
||||
/// </summary>
|
||||
public static class BytesEncodingUtils
|
||||
{
|
||||
/// <summary>
|
||||
/// Tries the get the Encoding from an array of bytes.
|
||||
/// </summary>
|
||||
/// <param name="bytes">The bytes.</param>
|
||||
/// <param name="encoding">The output encoding.</param>
|
||||
public static bool TryGetEncoding(byte[] bytes, out Encoding encoding)
|
||||
{
|
||||
encoding = null;
|
||||
if (bytes.All(b => b < 80))
|
||||
{
|
||||
encoding = Encoding.ASCII;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (StartsWith(bytes, new byte[] { 0xff, 0xfe, 0x00, 0x00 }))
|
||||
{
|
||||
encoding = Encoding.UTF32;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (StartsWith(bytes, new byte[] { 0xfe, 0xff }))
|
||||
{
|
||||
encoding = Encoding.BigEndianUnicode;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (StartsWith(bytes, new byte[] { 0xff, 0xfe }))
|
||||
{
|
||||
encoding = Encoding.Unicode;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (StartsWith(bytes, new byte[] { 0xef, 0xbb, 0xbf }))
|
||||
{
|
||||
encoding = Encoding.UTF8;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (IsUtf8(bytes, bytes.Length))
|
||||
{
|
||||
encoding = new UTF8Encoding(false);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool StartsWith(IEnumerable<byte> data, IReadOnlyCollection<byte> other)
|
||||
{
|
||||
byte[] arraySelf = data.Take(other.Count).ToArray();
|
||||
return other.SequenceEqual(arraySelf);
|
||||
}
|
||||
|
||||
private static bool IsUtf8(IReadOnlyList<byte> buffer, int length)
|
||||
{
|
||||
int position = 0;
|
||||
int bytes = 0;
|
||||
while (position < length)
|
||||
{
|
||||
if (!IsValid(buffer, position, length, ref bytes))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
position += bytes;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
#pragma warning disable S3776 // Cognitive Complexity of methods should not be too high
|
||||
private static bool IsValid(IReadOnlyList<byte> buffer, int position, int length, ref int bytes)
|
||||
{
|
||||
if (length > buffer.Count)
|
||||
{
|
||||
throw new ArgumentException("Invalid length");
|
||||
}
|
||||
|
||||
if (position > length - 1)
|
||||
{
|
||||
bytes = 0;
|
||||
return true;
|
||||
}
|
||||
|
||||
byte ch = buffer[position];
|
||||
if (ch <= 0x7F)
|
||||
{
|
||||
bytes = 1;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (ch >= 0xc2 && ch <= 0xdf)
|
||||
{
|
||||
if (position >= length - 2)
|
||||
{
|
||||
bytes = 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (buffer[position + 1] < 0x80 || buffer[position + 1] > 0xbf)
|
||||
{
|
||||
bytes = 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
bytes = 2;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (ch == 0xe0)
|
||||
{
|
||||
if (position >= length - 3)
|
||||
{
|
||||
bytes = 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (buffer[position + 1] < 0xa0 || buffer[position + 1] > 0xbf ||
|
||||
buffer[position + 2] < 0x80 || buffer[position + 2] > 0xbf)
|
||||
{
|
||||
bytes = 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
bytes = 3;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (ch >= 0xe1 && ch <= 0xef)
|
||||
{
|
||||
if (position >= length - 3)
|
||||
{
|
||||
bytes = 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (buffer[position + 1] < 0x80 || buffer[position + 1] > 0xbf ||
|
||||
buffer[position + 2] < 0x80 || buffer[position + 2] > 0xbf)
|
||||
{
|
||||
bytes = 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
bytes = 3;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (ch == 0xf0)
|
||||
{
|
||||
if (position >= length - 4)
|
||||
{
|
||||
bytes = 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (buffer[position + 1] < 0x90 || buffer[position + 1] > 0xbf ||
|
||||
buffer[position + 2] < 0x80 || buffer[position + 2] > 0xbf ||
|
||||
buffer[position + 3] < 0x80 || buffer[position + 3] > 0xbf)
|
||||
{
|
||||
bytes = 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
bytes = 4;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (ch == 0xf4)
|
||||
{
|
||||
if (position >= length - 4)
|
||||
{
|
||||
bytes = 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (buffer[position + 1] < 0x80 || buffer[position + 1] > 0x8f ||
|
||||
buffer[position + 2] < 0x80 || buffer[position + 2] > 0xbf ||
|
||||
buffer[position + 3] < 0x80 || buffer[position + 3] > 0xbf)
|
||||
{
|
||||
bytes = 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
bytes = 4;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (ch >= 0xf1 && ch <= 0xf3)
|
||||
{
|
||||
if (position >= length - 4)
|
||||
{
|
||||
bytes = 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (buffer[position + 1] < 0x80 || buffer[position + 1] > 0xbf ||
|
||||
buffer[position + 2] < 0x80 || buffer[position + 2] > 0xbf ||
|
||||
buffer[position + 3] < 0x80 || buffer[position + 3] > 0xbf)
|
||||
{
|
||||
bytes = 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
bytes = 4;
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
#pragma warning restore S3776 // Cognitive Complexity of methods should not be too high
|
||||
}
|
||||
215
test/WireMock.Net.Tests/FLuentMockServerTests.AdminFiles.cs
Normal file
215
test/WireMock.Net.Tests/FLuentMockServerTests.AdminFiles.cs
Normal file
@@ -0,0 +1,215 @@
|
||||
using Moq;
|
||||
using NFluent;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using WireMock.Handlers;
|
||||
using WireMock.Server;
|
||||
using WireMock.Settings;
|
||||
using Xunit;
|
||||
|
||||
namespace WireMock.Net.Tests
|
||||
{
|
||||
public class FluentMockServerAdminFilesTests
|
||||
{
|
||||
private readonly HttpClient _client = new HttpClient();
|
||||
|
||||
[Fact]
|
||||
public async Task FluentMockServer_Admin_Files_Post_Ascii()
|
||||
{
|
||||
// Arrange
|
||||
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
|
||||
filesystemHandlerMock.Setup(fs => fs.GetMappingFolder()).Returns("__admin/mappings");
|
||||
filesystemHandlerMock.Setup(fs => fs.FolderExists(It.IsAny<string>())).Returns(true);
|
||||
filesystemHandlerMock.Setup(fs => fs.WriteFile(It.IsAny<string>(), It.IsAny<byte[]>()));
|
||||
|
||||
var server = FluentMockServer.Start(new FluentMockServerSettings
|
||||
{
|
||||
UseSSL = false,
|
||||
StartAdminInterface = true,
|
||||
FileSystemHandler = filesystemHandlerMock.Object
|
||||
});
|
||||
|
||||
var multipartFormDataContent = new MultipartFormDataContent();
|
||||
multipartFormDataContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
|
||||
multipartFormDataContent.Add(new StreamContent(new MemoryStream(Encoding.ASCII.GetBytes("Here's a string."))));
|
||||
|
||||
// Act
|
||||
var httpResponseMessage = await _client.PostAsync("http://localhost:" + server.Ports[0] + "/__admin/files/filename.txt", multipartFormDataContent);
|
||||
|
||||
// Assert
|
||||
Check.That(httpResponseMessage.StatusCode).Equals(HttpStatusCode.OK);
|
||||
Check.That(server.LogEntries.Count().Equals(1));
|
||||
|
||||
// Verify
|
||||
filesystemHandlerMock.Verify(fs => fs.GetMappingFolder(), Times.Once);
|
||||
filesystemHandlerMock.Verify(fs => fs.FolderExists(It.IsAny<string>()), Times.Once);
|
||||
filesystemHandlerMock.Verify(fs => fs.WriteFile(It.Is<string>(p => p == "filename.txt"), It.IsAny<byte[]>()), Times.Once);
|
||||
filesystemHandlerMock.VerifyNoOtherCalls();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task FluentMockServer_Admin_Files_Post_MappingFolderDoesNotExistsButWillBeCreated()
|
||||
{
|
||||
// Arrange
|
||||
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
|
||||
filesystemHandlerMock.Setup(fs => fs.GetMappingFolder()).Returns("x");
|
||||
filesystemHandlerMock.Setup(fs => fs.CreateFolder(It.IsAny<string>()));
|
||||
filesystemHandlerMock.Setup(fs => fs.FolderExists(It.IsAny<string>())).Returns(false);
|
||||
filesystemHandlerMock.Setup(fs => fs.WriteFile(It.IsAny<string>(), It.IsAny<byte[]>()));
|
||||
|
||||
var server = FluentMockServer.Start(new FluentMockServerSettings
|
||||
{
|
||||
UseSSL = false,
|
||||
StartAdminInterface = true,
|
||||
FileSystemHandler = filesystemHandlerMock.Object
|
||||
});
|
||||
|
||||
var multipartFormDataContent = new MultipartFormDataContent();
|
||||
multipartFormDataContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
|
||||
multipartFormDataContent.Add(new StreamContent(new MemoryStream(Encoding.ASCII.GetBytes("Here's a string."))));
|
||||
|
||||
// Act
|
||||
var httpResponseMessage = await _client.PostAsync("http://localhost:" + server.Ports[0] + "/__admin/files/filename.txt", multipartFormDataContent);
|
||||
|
||||
// Assert
|
||||
Check.That(httpResponseMessage.StatusCode).Equals(HttpStatusCode.OK);
|
||||
|
||||
// Verify
|
||||
filesystemHandlerMock.Verify(fs => fs.GetMappingFolder(), Times.Once);
|
||||
filesystemHandlerMock.Verify(fs => fs.FolderExists(It.IsAny<string>()), Times.Once);
|
||||
filesystemHandlerMock.Verify(fs => fs.CreateFolder(It.Is<string>(p => p == "x")), Times.Once);
|
||||
filesystemHandlerMock.Verify(fs => fs.WriteFile(It.Is<string>(p => p == "filename.txt"), It.IsAny<byte[]>()), Times.Once);
|
||||
filesystemHandlerMock.VerifyNoOtherCalls();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task FluentMockServer_Admin_Files_GetAscii()
|
||||
{
|
||||
// Arrange
|
||||
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
|
||||
filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny<string>())).Returns(true);
|
||||
filesystemHandlerMock.Setup(fs => fs.ReadFile(It.IsAny<string>())).Returns(Encoding.ASCII.GetBytes("Here's a string."));
|
||||
|
||||
var server = FluentMockServer.Start(new FluentMockServerSettings
|
||||
{
|
||||
UseSSL = false,
|
||||
StartAdminInterface = true,
|
||||
FileSystemHandler = filesystemHandlerMock.Object
|
||||
});
|
||||
|
||||
var multipartFormDataContent = new MultipartFormDataContent();
|
||||
multipartFormDataContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
|
||||
multipartFormDataContent.Add(new StreamContent(new MemoryStream()));
|
||||
|
||||
// Act
|
||||
var httpResponseMessageGet = await _client.GetAsync("http://localhost:" + server.Ports[0] + "/__admin/files/filename.txt");
|
||||
|
||||
// Assert
|
||||
Check.That(httpResponseMessageGet.StatusCode).Equals(HttpStatusCode.OK);
|
||||
|
||||
Check.That(httpResponseMessageGet.Content.ReadAsStringAsync().Result).Equals("Here's a string.");
|
||||
|
||||
Check.That(server.LogEntries.Count().Equals(2));
|
||||
|
||||
// Verify
|
||||
filesystemHandlerMock.Verify(fs => fs.ReadFile(It.Is<string>(p => p == "filename.txt")), Times.Once);
|
||||
filesystemHandlerMock.Verify(fs => fs.FileExists(It.Is<string>(p => p == "filename.txt")), Times.Once);
|
||||
filesystemHandlerMock.VerifyNoOtherCalls();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task FluentMockServer_Admin_Files_GetUTF16()
|
||||
{
|
||||
// Arrange
|
||||
byte[] symbol = Encoding.UTF32.GetBytes(char.ConvertFromUtf32(0x1D161));
|
||||
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
|
||||
filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny<string>())).Returns(true);
|
||||
filesystemHandlerMock.Setup(fs => fs.ReadFile(It.IsAny<string>())).Returns(symbol);
|
||||
|
||||
var server = FluentMockServer.Start(new FluentMockServerSettings
|
||||
{
|
||||
UseSSL = false,
|
||||
StartAdminInterface = true,
|
||||
FileSystemHandler = filesystemHandlerMock.Object
|
||||
});
|
||||
|
||||
var multipartFormDataContent = new MultipartFormDataContent();
|
||||
multipartFormDataContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
|
||||
multipartFormDataContent.Add(new StreamContent(new MemoryStream()));
|
||||
|
||||
// Act
|
||||
var httpResponseMessageGet = await _client.GetAsync("http://localhost:" + server.Ports[0] + "/__admin/files/filename.bin");
|
||||
|
||||
// Assert
|
||||
Check.That(httpResponseMessageGet.StatusCode).Equals(HttpStatusCode.OK);
|
||||
Check.That(httpResponseMessageGet.Content.ReadAsByteArrayAsync().Result).Equals(symbol);
|
||||
Check.That(server.LogEntries.Count().Equals(2));
|
||||
|
||||
// Verify
|
||||
filesystemHandlerMock.Verify(fs => fs.ReadFile(It.Is<string>(p => p == "filename.bin")), Times.Once);
|
||||
filesystemHandlerMock.Verify(fs => fs.FileExists(It.Is<string>(p => p == "filename.bin")), Times.Once);
|
||||
filesystemHandlerMock.VerifyNoOtherCalls();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task FluentMockServer_Admin_Files_Head()
|
||||
{
|
||||
// Arrange
|
||||
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
|
||||
filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny<string>())).Returns(true);
|
||||
|
||||
var server = FluentMockServer.Start(new FluentMockServerSettings
|
||||
{
|
||||
UseSSL = false,
|
||||
StartAdminInterface = true,
|
||||
FileSystemHandler = filesystemHandlerMock.Object
|
||||
});
|
||||
|
||||
// Act
|
||||
var requestUri = "http://localhost:" + server.Ports[0] + "/__admin/files/filename.txt";
|
||||
var httpRequestMessage = new HttpRequestMessage(HttpMethod.Head, requestUri);
|
||||
var httpResponseMessage = await _client.SendAsync(httpRequestMessage);
|
||||
|
||||
// Assert
|
||||
Check.That(httpResponseMessage.StatusCode).Equals(HttpStatusCode.NoContent);
|
||||
Check.That(server.LogEntries.Count().Equals(1));
|
||||
|
||||
// Verify
|
||||
filesystemHandlerMock.Verify(fs => fs.FileExists(It.IsAny<string>()), Times.Once);
|
||||
filesystemHandlerMock.VerifyNoOtherCalls();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task FluentMockServer_Admin_Files_Head_FileDoesNotExistsReturns404()
|
||||
{
|
||||
// Arrange
|
||||
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
|
||||
filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny<string>())).Returns(false);
|
||||
|
||||
var server = FluentMockServer.Start(new FluentMockServerSettings
|
||||
{
|
||||
UseSSL = false,
|
||||
StartAdminInterface = true,
|
||||
FileSystemHandler = filesystemHandlerMock.Object
|
||||
});
|
||||
|
||||
// Act
|
||||
var requestUri = "http://localhost:" + server.Ports[0] + "/__admin/files/filename.txt";
|
||||
var httpRequestMessage = new HttpRequestMessage(HttpMethod.Head, requestUri);
|
||||
var httpResponseMessage = await _client.SendAsync(httpRequestMessage);
|
||||
|
||||
// Assert
|
||||
Check.That(httpResponseMessage.StatusCode).Equals(HttpStatusCode.NotFound);
|
||||
Check.That(server.LogEntries.Count().Equals(1));
|
||||
|
||||
// Verify
|
||||
filesystemHandlerMock.Verify(fs => fs.FileExists(It.IsAny<string>()), Times.Once);
|
||||
filesystemHandlerMock.VerifyNoOtherCalls();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,15 @@
|
||||
using NFluent;
|
||||
using Moq;
|
||||
using NFluent;
|
||||
using RestEase;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using WireMock.Admin.Mappings;
|
||||
using WireMock.Admin.Settings;
|
||||
using WireMock.Client;
|
||||
using WireMock.Handlers;
|
||||
using WireMock.Logging;
|
||||
using WireMock.Server;
|
||||
using WireMock.Settings;
|
||||
@@ -232,6 +235,237 @@ namespace WireMock.Net.Tests
|
||||
Check.That(requestLogged.Request.Body).IsNotNull();
|
||||
Check.That(requestLogged.Request.Body).Contains("T000001");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task IFluentMockServerAdmin_PostFileAsync_Ascii()
|
||||
{
|
||||
// Arrange
|
||||
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
|
||||
filesystemHandlerMock.Setup(fs => fs.GetMappingFolder()).Returns("__admin/mappings");
|
||||
filesystemHandlerMock.Setup(fs => fs.FolderExists(It.IsAny<string>())).Returns(true);
|
||||
filesystemHandlerMock.Setup(fs => fs.WriteFile(It.IsAny<string>(), It.IsAny<byte[]>()));
|
||||
|
||||
var server = FluentMockServer.Start(new FluentMockServerSettings
|
||||
{
|
||||
UseSSL = false,
|
||||
StartAdminInterface = true,
|
||||
FileSystemHandler = filesystemHandlerMock.Object
|
||||
});
|
||||
|
||||
var api = RestClient.For<IFluentMockServerAdmin>(server.Urls[0]);
|
||||
|
||||
// Act
|
||||
var request = await api.PostFileAsync("filename.txt", "abc");
|
||||
|
||||
// Assert
|
||||
Check.That(request.Guid).IsNull();
|
||||
Check.That(request.Status).Contains("File");
|
||||
|
||||
// Verify
|
||||
filesystemHandlerMock.Verify(fs => fs.GetMappingFolder(), Times.Once);
|
||||
filesystemHandlerMock.Verify(fs => fs.FolderExists(It.IsAny<string>()), Times.Once);
|
||||
filesystemHandlerMock.Verify(fs => fs.WriteFile(It.Is<string>(p => p == "filename.txt"), It.IsAny<byte[]>()), Times.Once);
|
||||
filesystemHandlerMock.VerifyNoOtherCalls();
|
||||
|
||||
server.Stop();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task IFluentMockServerAdmin_PutFileAsync_Ascii()
|
||||
{
|
||||
// Arrange
|
||||
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
|
||||
filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny<string>())).Returns(true);
|
||||
filesystemHandlerMock.Setup(fs => fs.WriteFile(It.IsAny<string>(), It.IsAny<byte[]>()));
|
||||
|
||||
var server = FluentMockServer.Start(new FluentMockServerSettings
|
||||
{
|
||||
UseSSL = false,
|
||||
StartAdminInterface = true,
|
||||
FileSystemHandler = filesystemHandlerMock.Object
|
||||
});
|
||||
|
||||
var api = RestClient.For<IFluentMockServerAdmin>(server.Urls[0]);
|
||||
|
||||
// Act
|
||||
var request = await api.PutFileAsync("filename.txt", "abc-abc");
|
||||
|
||||
// Assert
|
||||
Check.That(request.Guid).IsNull();
|
||||
Check.That(request.Status).Contains("File");
|
||||
|
||||
// Verify
|
||||
filesystemHandlerMock.Verify(fs => fs.WriteFile(It.Is<string>(p => p == "filename.txt"), It.IsAny<byte[]>()), Times.Once);
|
||||
filesystemHandlerMock.Verify(fs => fs.FileExists(It.Is<string>(p => p == "filename.txt")), Times.Once);
|
||||
filesystemHandlerMock.VerifyNoOtherCalls();
|
||||
|
||||
server.Stop();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IFluentMockServerAdmin_PutFileAsync_NotFound()
|
||||
{
|
||||
// Arrange
|
||||
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
|
||||
filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny<string>())).Returns(false);
|
||||
|
||||
var server = FluentMockServer.Start(new FluentMockServerSettings
|
||||
{
|
||||
UseSSL = false,
|
||||
StartAdminInterface = true,
|
||||
FileSystemHandler = filesystemHandlerMock.Object
|
||||
});
|
||||
|
||||
var api = RestClient.For<IFluentMockServerAdmin>(server.Urls[0]);
|
||||
|
||||
// Act and Assert
|
||||
Check.ThatAsyncCode(() => api.PutFileAsync("filename.txt", "xxx")).Throws<ApiException>();
|
||||
|
||||
// Verify
|
||||
filesystemHandlerMock.Verify(fs => fs.FileExists(It.Is<string>(p => p == "filename.txt")), Times.Once);
|
||||
filesystemHandlerMock.VerifyNoOtherCalls();
|
||||
|
||||
server.Stop();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IFluentMockServerAdmin_GetFileAsync_NotFound()
|
||||
{
|
||||
// Arrange
|
||||
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
|
||||
filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny<string>())).Returns(false);
|
||||
filesystemHandlerMock.Setup(fs => fs.ReadFile(It.IsAny<string>())).Returns(Encoding.ASCII.GetBytes("Here's a string."));
|
||||
|
||||
var server = FluentMockServer.Start(new FluentMockServerSettings
|
||||
{
|
||||
UseSSL = false,
|
||||
StartAdminInterface = true,
|
||||
FileSystemHandler = filesystemHandlerMock.Object
|
||||
});
|
||||
|
||||
var api = RestClient.For<IFluentMockServerAdmin>(server.Urls[0]);
|
||||
|
||||
// Act and Assert
|
||||
Check.ThatAsyncCode(() => api.GetFileAsync("filename.txt")).Throws<ApiException>();
|
||||
|
||||
// Verify
|
||||
filesystemHandlerMock.Verify(fs => fs.FileExists(It.Is<string>(p => p == "filename.txt")), Times.Once);
|
||||
filesystemHandlerMock.VerifyNoOtherCalls();
|
||||
|
||||
server.Stop();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task IFluentMockServerAdmin_GetFileAsync_Found()
|
||||
{
|
||||
// Arrange
|
||||
string data = "Here's a string.";
|
||||
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
|
||||
filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny<string>())).Returns(true);
|
||||
filesystemHandlerMock.Setup(fs => fs.ReadFile(It.IsAny<string>())).Returns(Encoding.ASCII.GetBytes(data));
|
||||
|
||||
var server = FluentMockServer.Start(new FluentMockServerSettings
|
||||
{
|
||||
UseSSL = false,
|
||||
StartAdminInterface = true,
|
||||
FileSystemHandler = filesystemHandlerMock.Object
|
||||
});
|
||||
|
||||
var api = RestClient.For<IFluentMockServerAdmin>(server.Urls[0]);
|
||||
|
||||
// Act
|
||||
string file = await api.GetFileAsync("filename.txt");
|
||||
|
||||
// Assert
|
||||
Check.That(file).Equals(data);
|
||||
|
||||
// Verify
|
||||
filesystemHandlerMock.Verify(fs => fs.FileExists(It.Is<string>(p => p == "filename.txt")), Times.Once);
|
||||
filesystemHandlerMock.Verify(fs => fs.ReadFile(It.Is<string>(p => p == "filename.txt")), Times.Once);
|
||||
filesystemHandlerMock.VerifyNoOtherCalls();
|
||||
|
||||
server.Stop();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task IFluentMockServerAdmin_DeleteFileAsync_Ok()
|
||||
{
|
||||
// Arrange
|
||||
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
|
||||
filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny<string>())).Returns(true);
|
||||
filesystemHandlerMock.Setup(fs => fs.DeleteFile(It.IsAny<string>()));
|
||||
|
||||
var server = FluentMockServer.Start(new FluentMockServerSettings
|
||||
{
|
||||
UseSSL = false,
|
||||
StartAdminInterface = true,
|
||||
FileSystemHandler = filesystemHandlerMock.Object
|
||||
});
|
||||
|
||||
var api = RestClient.For<IFluentMockServerAdmin>(server.Urls[0]);
|
||||
|
||||
// Act
|
||||
await api.DeleteFileAsync("filename.txt");
|
||||
|
||||
// Verify
|
||||
filesystemHandlerMock.Verify(fs => fs.FileExists(It.Is<string>(p => p == "filename.txt")), Times.Once);
|
||||
filesystemHandlerMock.Verify(fs => fs.DeleteFile(It.Is<string>(p => p == "filename.txt")), Times.Once);
|
||||
filesystemHandlerMock.VerifyNoOtherCalls();
|
||||
|
||||
server.Stop();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IFluentMockServerAdmin_DeleteFileAsync_NotFound()
|
||||
{
|
||||
// Arrange
|
||||
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
|
||||
filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny<string>())).Returns(false);
|
||||
filesystemHandlerMock.Setup(fs => fs.DeleteFile(It.IsAny<string>()));
|
||||
|
||||
var server = FluentMockServer.Start(new FluentMockServerSettings
|
||||
{
|
||||
UseSSL = false,
|
||||
StartAdminInterface = true,
|
||||
FileSystemHandler = filesystemHandlerMock.Object
|
||||
});
|
||||
|
||||
var api = RestClient.For<IFluentMockServerAdmin>(server.Urls[0]);
|
||||
|
||||
// Act and Assert
|
||||
Check.ThatAsyncCode(() => api.DeleteFileAsync("filename.txt")).Throws<ApiException>();
|
||||
|
||||
// Verify
|
||||
filesystemHandlerMock.Verify(fs => fs.FileExists(It.Is<string>(p => p == "filename.txt")), Times.Once);
|
||||
filesystemHandlerMock.VerifyNoOtherCalls();
|
||||
|
||||
server.Stop();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void IFluentMockServerAdmin_FileExistsAsync_NotFound()
|
||||
{
|
||||
// Arrange
|
||||
var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict);
|
||||
filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny<string>())).Returns(false);
|
||||
|
||||
var server = FluentMockServer.Start(new FluentMockServerSettings
|
||||
{
|
||||
UseSSL = false,
|
||||
StartAdminInterface = true,
|
||||
FileSystemHandler = filesystemHandlerMock.Object
|
||||
});
|
||||
|
||||
var api = RestClient.For<IFluentMockServerAdmin>(server.Urls[0]);
|
||||
|
||||
// Act and Assert
|
||||
Check.ThatAsyncCode(() => api.FileExistsAsync("filename.txt")).Throws<ApiException>();
|
||||
|
||||
// Verify
|
||||
filesystemHandlerMock.Verify(fs => fs.FileExists(It.Is<string>(p => p == "filename.txt")), Times.Once);
|
||||
filesystemHandlerMock.VerifyNoOtherCalls();
|
||||
|
||||
server.Stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,11 @@
|
||||
using System;
|
||||
using Moq;
|
||||
using Newtonsoft.Json;
|
||||
using NFluent;
|
||||
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.Logging;
|
||||
using WireMock.RequestBuilders;
|
||||
|
||||
@@ -290,6 +290,36 @@ namespace WireMock.Net.Tests
|
||||
Check.That(response.Content.Headers.GetValues("Content-Type")).ContainsExactly("application/json; charset=utf-8");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task FluentMockServer_Proxy_Should_set_Body_in_multipart_proxied_response()
|
||||
{
|
||||
// Assign
|
||||
string path = $"/prx_{Guid.NewGuid().ToString()}";
|
||||
var serverForProxyForwarding = FluentMockServer.Start();
|
||||
serverForProxyForwarding
|
||||
.Given(Request.Create().WithPath(path))
|
||||
.RespondWith(Response.Create()
|
||||
.WithBodyAsJson(new { i = 42 })
|
||||
);
|
||||
|
||||
var server = FluentMockServer.Start();
|
||||
server
|
||||
.Given(Request.Create().WithPath(path))
|
||||
.RespondWith(Response.Create().WithProxy(serverForProxyForwarding.Urls[0]));
|
||||
|
||||
// Act
|
||||
var uri = new Uri($"{server.Urls[0]}{path}");
|
||||
var form = new MultipartFormDataContent
|
||||
{
|
||||
{ new StringContent("data"), "test", "test.txt" }
|
||||
};
|
||||
var response = await new HttpClient().PostAsync(uri, form);
|
||||
|
||||
// Assert
|
||||
string content = await response.Content.ReadAsStringAsync();
|
||||
Check.That(content).IsEqualTo("{\"i\":42}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task FluentMockServer_Proxy_Should_Not_overrule_AdminMappings()
|
||||
{
|
||||
|
||||
@@ -62,7 +62,7 @@ namespace WireMock.Net.Tests
|
||||
|
||||
// Assert
|
||||
var mappings = server.Mappings;
|
||||
Check.That(mappings.Count()).IsEqualTo(19);
|
||||
Check.That(mappings.Count()).IsEqualTo(24);
|
||||
Check.That(mappings.All(m => m.Priority == int.MinValue)).IsTrue();
|
||||
}
|
||||
|
||||
@@ -81,8 +81,8 @@ namespace WireMock.Net.Tests
|
||||
|
||||
// Assert
|
||||
var mappings = server.Mappings;
|
||||
Check.That(mappings.Count()).IsEqualTo(20);
|
||||
Check.That(mappings.Count(m => m.Priority == int.MinValue)).IsEqualTo(19);
|
||||
Check.That(mappings.Count()).IsEqualTo(25);
|
||||
Check.That(mappings.Count(m => m.Priority == int.MinValue)).IsEqualTo(24);
|
||||
Check.That(mappings.Count(m => m.Priority == 1000)).IsEqualTo(1);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
using System;
|
||||
using NFluent;
|
||||
using System;
|
||||
using System.IO;
|
||||
using NFluent;
|
||||
using WireMock.Handlers;
|
||||
using Xunit;
|
||||
|
||||
@@ -21,24 +21,62 @@ namespace WireMock.Net.Tests.Handlers
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LocalFileSystemHandler_CreateFolder_Throws()
|
||||
public void LocalFileSystemHandler_CreateFolder_ThrowsArgumentNullException()
|
||||
{
|
||||
// Act
|
||||
Check.ThatCode(() => _sut.CreateFolder(null)).Throws<ArgumentNullException>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LocalFileSystemHandler_WriteMappingFile_Throws()
|
||||
public void LocalFileSystemHandler_WriteMappingFile_ThrowsArgumentNullException()
|
||||
{
|
||||
// Act
|
||||
Check.ThatCode(() => _sut.WriteMappingFile(null, null)).Throws<ArgumentNullException>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LocalFileSystemHandler_ReadResponseBodyAsFile_Throws()
|
||||
public void LocalFileSystemHandler_ReadResponseBodyAsFile_ThrowsArgumentNullException()
|
||||
{
|
||||
// Act
|
||||
Check.ThatCode(() => _sut.ReadResponseBodyAsFile(null)).Throws<ArgumentNullException>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LocalFileSystemHandler_FileExists_ReturnsFalse()
|
||||
{
|
||||
// Act
|
||||
var result = _sut.FileExists("x.x");
|
||||
|
||||
// Assert
|
||||
Check.That(result).IsFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LocalFileSystemHandler_FileExists_ThrowsArgumentNullException()
|
||||
{
|
||||
// Act
|
||||
Check.ThatCode(() => _sut.FileExists(null)).Throws<ArgumentNullException>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LocalFileSystemHandler_ReadFile_ThrowsArgumentNullException()
|
||||
{
|
||||
// Act
|
||||
Check.ThatCode(() => _sut.ReadFile(null)).Throws<ArgumentNullException>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LocalFileSystemHandler_WriteFile_ThrowsArgumentNullException()
|
||||
{
|
||||
// Act
|
||||
Check.ThatCode(() => _sut.WriteFile(null, null)).Throws<ArgumentNullException>();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LocalFileSystemHandler_DeleteFile_ThrowsArgumentNullException()
|
||||
{
|
||||
// Act
|
||||
Check.ThatCode(() => _sut.DeleteFile(null)).Throws<ArgumentNullException>();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using System.Text;
|
||||
using System;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using NFluent;
|
||||
using WireMock.Models;
|
||||
@@ -231,5 +232,53 @@ namespace WireMock.Net.Tests.ResponseBuilders
|
||||
Check.That(response2Message.BodyData.BodyAsString).IsNull();
|
||||
Check.That(response2Message.StatusCode).IsEqualTo(200);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Response_ProvideResponse_WithBodyAsFile()
|
||||
{
|
||||
var fileContents = "testFileContents" + Guid.NewGuid();
|
||||
var bodyDataAsFile = new BodyData {BodyAsFile = fileContents};
|
||||
|
||||
var request1 = new RequestMessage(new UrlDetails("http://localhost/__admin/files/filename.txt"), "PUT", ClientIp, bodyDataAsFile);
|
||||
|
||||
var response = Response.Create().WithStatusCode(200).WithBody(fileContents);
|
||||
|
||||
var provideResponseAsync = await response.ProvideResponseAsync(request1);
|
||||
|
||||
Check.That(provideResponseAsync.StatusCode).IsEqualTo(200);
|
||||
Check.That(provideResponseAsync.BodyData.BodyAsString).Contains(fileContents);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Response_ProvideResponse_WithResponseAsFile()
|
||||
{
|
||||
var fileContents = "testFileContents" + Guid.NewGuid();
|
||||
var bodyDataAsFile = new BodyData { BodyAsFile = fileContents };
|
||||
|
||||
var request1 = new RequestMessage(new UrlDetails("http://localhost/__admin/files/filename.txt"), "GET", ClientIp, bodyDataAsFile);
|
||||
|
||||
var response = Response.Create().WithStatusCode(200).WithBody(fileContents);
|
||||
|
||||
var provideResponseAsync = await response.ProvideResponseAsync(request1);
|
||||
|
||||
Check.That(provideResponseAsync.StatusCode).IsEqualTo(200);
|
||||
Check.That(provideResponseAsync.BodyData.BodyAsString).Contains(fileContents);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Response_ProvideResponse_WithResponseDeleted()
|
||||
{
|
||||
var fileContents = "testFileContents" + Guid.NewGuid();
|
||||
var bodyDataAsFile = new BodyData { BodyAsFile = fileContents };
|
||||
|
||||
var request1 = new RequestMessage(new UrlDetails("http://localhost/__admin/files/filename.txt"), "DELETE", ClientIp, bodyDataAsFile);
|
||||
|
||||
var response = Response.Create().WithStatusCode(200).WithBody("File deleted.");
|
||||
|
||||
var provideResponseAsync = await response.ProvideResponseAsync(request1);
|
||||
|
||||
Check.That(provideResponseAsync.StatusCode).IsEqualTo(200);
|
||||
Check.That(provideResponseAsync.BodyData.BodyAsString).Contains("File deleted.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
using System;
|
||||
using NFluent;
|
||||
using NFluent;
|
||||
using System;
|
||||
using WireMock.Admin.Mappings;
|
||||
using WireMock.Matchers;
|
||||
using WireMock.Serialization;
|
||||
@@ -53,6 +53,23 @@ namespace WireMock.Net.Tests.Serialization
|
||||
Check.That(matcher.GetPatterns()).ContainsExactly("x", "y");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MatcherModelMapper_Map_ExactObjectMatcher_Pattern()
|
||||
{
|
||||
// Assign
|
||||
var model = new MatcherModel
|
||||
{
|
||||
Name = "ExactObjectMatcher",
|
||||
Patterns = new object[] { "c3RlZg==" }
|
||||
};
|
||||
|
||||
// Act
|
||||
var matcher = (ExactObjectMatcher)MatcherMapper.Map(model);
|
||||
|
||||
// Assert
|
||||
Check.That(matcher.ValueAsBytes).ContainsExactly(new byte[] { 115, 116, 101, 102 });
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void MatcherModelMapper_Map_RegexMatcher()
|
||||
{
|
||||
|
||||
@@ -51,7 +51,7 @@ namespace WireMock.Net.Tests.Util
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task BodyParser_Parse_ContentTypeMultipart()
|
||||
public async Task BodyParser_Parse_WithUTF8EncodingAndContentTypeMultipart_DetectedBodyTypeEqualsString()
|
||||
{
|
||||
// Arrange
|
||||
string contentType = "multipart/form-data";
|
||||
@@ -80,6 +80,26 @@ Content-Type: text/html
|
||||
// Act
|
||||
var result = await BodyParser.Parse(memoryStream, contentType);
|
||||
|
||||
// Assert
|
||||
Check.That(result.DetectedBodyType).IsEqualTo(BodyType.String);
|
||||
Check.That(result.DetectedBodyTypeFromContentType).IsEqualTo(BodyType.MultiPart);
|
||||
Check.That(result.BodyAsBytes).IsNotNull();
|
||||
Check.That(result.BodyAsJson).IsNull();
|
||||
Check.That(result.BodyAsString).IsNotNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task BodyParser_Parse_WithUTF16EncodingAndContentTypeMultipart_DetectedBodyTypeEqualsString()
|
||||
{
|
||||
// Arrange
|
||||
string contentType = "multipart/form-data";
|
||||
string body = char.ConvertFromUtf32(0x1D161); //U+1D161 = MUSICAL SYMBOL SIXTEENTH NOTE
|
||||
|
||||
var memoryStream = new MemoryStream(Encoding.UTF32.GetBytes(body));
|
||||
|
||||
// Act
|
||||
var result = await BodyParser.Parse(memoryStream, contentType);
|
||||
|
||||
// Assert
|
||||
Check.That(result.DetectedBodyType).IsEqualTo(BodyType.Bytes);
|
||||
Check.That(result.DetectedBodyTypeFromContentType).IsEqualTo(BodyType.MultiPart);
|
||||
|
||||
Reference in New Issue
Block a user