mirror of
https://github.com/wiremock/WireMock.Net.git
synced 2026-04-28 19:58:09 +02:00
Version 2.x (#1359)
* Version 2.x * Setup .NET 9 * 12 * cleanup some #if for NETSTANDARD1_3 * cleanup + fix tests for net8 * openapi * NO ConfigureAwait(false) + cleanup * . * #endif * HashSet * WireMock.Net.NUnit * HttpContext * Add WebSockets (#1423) * Add WebSockets * Add tests * fix * more tests * Add tests * ... * remove IOwin * - * tests * fluent * ok * match * . * byte[] * x * func * func * byte * trans * ... * frameworks......... * jmes * xxx * sc * using var httpClient = new HttpClient(); * usings * maxRetries * up * xunit v3 * ct * --- * ct * ct2 * T Unit * WireMock.Net.TUnitTests / 10 * t unit first * --project * no tunit * t2 * --project * --project * ci - --project * publish ./test/wiremock-coverage.xml * windows * . * log * ... * log * goed * BodyType * . * . * --scenario * ... * pact * ct * . * WireMock.Net.RestClient.AwesomeAssertions (#1427) * WireMock.Net.RestClient.AwesomeAssertions * ok * atpath * fix test * sonar fixes * ports * proxy test * FIX? * --- * await Task.Delay(100, _ct); * ? * --project * Aspire: use IDistributedApplicationEventingSubscriber (#1428) * broadcast * ok * more tsts * . * Collection * up * . * 2 * remove nfluent * <VersionPrefix>2.0.0-preview-02</VersionPrefix> * ... * . * nuget icon * . * <PackageReference Include="JmesPath.Net" Version="1.1.0" /> * x * 500 * . * fix some warnings * ws
This commit is contained in:
20
src/WireMock.Net.Shared/Extensions/ArrayPoolExtensions.cs
Normal file
20
src/WireMock.Net.Shared/Extensions/ArrayPoolExtensions.cs
Normal file
@@ -0,0 +1,20 @@
|
||||
// Copyright © WireMock.Net
|
||||
|
||||
namespace System.Buffers;
|
||||
|
||||
internal sealed class Lease<T>(ArrayPool<T> pool, int length) : IDisposable
|
||||
{
|
||||
public T[] Rented { get; } = pool.Rent(length);
|
||||
|
||||
public static implicit operator T[](Lease<T> lease) => lease.Rented;
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
pool.Return(Rented, true);
|
||||
}
|
||||
}
|
||||
|
||||
internal static class ArrayPoolExtensions
|
||||
{
|
||||
public static Lease<T> Lease<T>(this ArrayPool<T> source, int length) => new(source, length);
|
||||
}
|
||||
@@ -28,4 +28,18 @@ internal static class DictionaryExtensions
|
||||
value = default;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool TryGetValue<T>(this IDictionary<object, object?> dictionary, string key, [NotNullWhen(true)] out T? value)
|
||||
{
|
||||
Guard.NotNull(dictionary);
|
||||
|
||||
if (dictionary[key] is T typedValue)
|
||||
{
|
||||
value = typedValue;
|
||||
return true;
|
||||
}
|
||||
|
||||
value = default;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,10 @@
|
||||
using System.Globalization;
|
||||
// Copyright © WireMock.Net
|
||||
|
||||
namespace WireMock.Extensions;
|
||||
using System.Globalization;
|
||||
using System.Text.RegularExpressions;
|
||||
using WireMock.Constants;
|
||||
|
||||
namespace System;
|
||||
|
||||
internal static class StringExtensions
|
||||
{
|
||||
@@ -28,4 +32,12 @@ internal static class StringExtensions
|
||||
return result.ToString(CultureInfo.InvariantCulture).Replace('-', '_');
|
||||
}
|
||||
}
|
||||
|
||||
#if !NET8_0_OR_GREATER
|
||||
public static string Replace(this string text, string oldValue, string newValue, StringComparison stringComparison)
|
||||
{
|
||||
var options = stringComparison == StringComparison.OrdinalIgnoreCase ? RegexOptions.IgnoreCase : RegexOptions.None;
|
||||
return Regex.Replace(text, oldValue, newValue, options, RegexConstants.DefaultTimeout);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using System.Web;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using WireMock.Matchers.Request;
|
||||
using WireMock.Models;
|
||||
using WireMock.ResponseProviders;
|
||||
@@ -146,9 +148,10 @@ public interface IMapping
|
||||
/// <summary>
|
||||
/// ProvideResponseAsync
|
||||
/// </summary>
|
||||
/// <param name="context">The HttpContext.</param>
|
||||
/// <param name="requestMessage">The request message.</param>
|
||||
/// <returns>The <see cref="ResponseMessage"/> including a new (optional) <see cref="IMapping"/>.</returns>
|
||||
Task<(IResponseMessage Message, IMapping? Mapping)> ProvideResponseAsync(IRequestMessage requestMessage);
|
||||
/// <returns>The <see cref="IResponseMessage"/> including a new (optional) <see cref="IMapping"/>.</returns>
|
||||
Task<(IResponseMessage Message, IMapping? Mapping)> ProvideResponseAsync(HttpContext context, IRequestMessage requestMessage);
|
||||
|
||||
/// <summary>
|
||||
/// Gets the RequestMatchResult based on the RequestMessage.
|
||||
|
||||
17
src/WireMock.Net.Shared/Matchers/IFuncMatcher.cs
Normal file
17
src/WireMock.Net.Shared/Matchers/IFuncMatcher.cs
Normal file
@@ -0,0 +1,17 @@
|
||||
// Copyright © WireMock.Net
|
||||
|
||||
namespace WireMock.Matchers;
|
||||
|
||||
/// <summary>
|
||||
/// IFuncMatcher
|
||||
/// </summary>
|
||||
/// <inheritdoc cref="IMatcher"/>
|
||||
public interface IFuncMatcher : IMatcher
|
||||
{
|
||||
/// <summary>
|
||||
/// Determines whether the specified function is match.
|
||||
/// </summary>
|
||||
/// <param name="value">The value to check for a match.</param>
|
||||
/// <returns>MatchResult</returns>
|
||||
MatchResult IsMatch(object? value);
|
||||
}
|
||||
@@ -1,7 +1,5 @@
|
||||
// Copyright © WireMock.Net
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Stef.Validation;
|
||||
using WireMock.Extensions;
|
||||
@@ -40,6 +38,18 @@ public class MatchResult
|
||||
/// </summary>
|
||||
public bool IsPerfect() => MatchScores.IsPerfect(Score);
|
||||
|
||||
/// <summary>
|
||||
/// Create a MatchResult.
|
||||
/// </summary>
|
||||
/// <param name="name">The name or description of the matcher.</param>
|
||||
/// <param name="matchBehaviour">The match behaviour.</param>
|
||||
/// <param name="isMatch">Is this a match?</param>
|
||||
/// <param name="exception">The exception in case the matching fails. [Optional]</param>
|
||||
public static MatchResult From(string name, MatchBehaviour matchBehaviour, bool isMatch, Exception? exception = null)
|
||||
{
|
||||
return From(name, MatchBehaviourHelper.Convert(matchBehaviour, MatchScores.ToScore(isMatch)), exception);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Create a MatchResult.
|
||||
/// </summary>
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
// Copyright © WireMock.Net
|
||||
|
||||
using System;
|
||||
using WireMock.Models;
|
||||
using WireMock.Util;
|
||||
|
||||
@@ -40,6 +39,6 @@ public class RequestMessageProtoBufMatcher : IRequestMatcher
|
||||
|
||||
private MatchResult GetMatchResult(IRequestMessage requestMessage)
|
||||
{
|
||||
return Matcher?.IsMatchAsync(requestMessage.BodyAsBytes).GetAwaiter().GetResult() ?? default;
|
||||
return Matcher?.IsMatchAsync(requestMessage.BodyAsBytes).GetAwaiter().GetResult() ?? MatchResult.From(nameof(RequestMessageProtoBufMatcher));
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,5 @@
|
||||
// Copyright © WireMock.Net
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text.RegularExpressions;
|
||||
using Stef.Validation;
|
||||
|
||||
@@ -10,9 +8,7 @@ namespace WireMock.RegularExpressions;
|
||||
/// <summary>
|
||||
/// Extension to the <see cref="Regex"/> object, adding support for GUID tokens for matching on.
|
||||
/// </summary>
|
||||
#if !NETSTANDARD1_3
|
||||
[Serializable]
|
||||
#endif
|
||||
internal class RegexExtended : Regex
|
||||
{
|
||||
/// <inheritdoc cref="Regex"/>
|
||||
@@ -32,7 +28,7 @@ internal class RegexExtended : Regex
|
||||
{
|
||||
}
|
||||
|
||||
#if !NETSTANDARD1_3 && !NET8_0_OR_GREATER
|
||||
#if !NET8_0_OR_GREATER
|
||||
/// <inheritdoc cref="Regex"/>
|
||||
protected RegexExtended(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) :
|
||||
base(info, context)
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
// Copyright © WireMock.Net
|
||||
|
||||
using WireMock.Matchers;
|
||||
using WireMock.Matchers.Request;
|
||||
|
||||
namespace WireMock.RequestBuilders;
|
||||
|
||||
/// <summary>
|
||||
/// The HttpVersionBuilder interface.
|
||||
/// </summary>
|
||||
public interface IHttpVersionBuilder : IRequestMatcher
|
||||
public interface IHttpVersionBuilder : IWebSocketRequestBuilder
|
||||
{
|
||||
/// <summary>
|
||||
/// WithHttpVersion
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
// Copyright © WireMock.Net
|
||||
using WireMock.Matchers.Request;
|
||||
|
||||
namespace WireMock.RequestBuilders;
|
||||
|
||||
/// <summary>
|
||||
/// The BodyRequestBuilder interface.
|
||||
/// </summary>
|
||||
public interface IWebSocketRequestBuilder : IRequestMatcher
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets a value indicating whether the connection uses the WebSocket protocol.
|
||||
/// </summary>
|
||||
bool IsWebSocket { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Match WebSocket upgrade with optional protocols.
|
||||
/// </summary>
|
||||
IRequestBuilder WithWebSocketUpgrade(params string[] protocols);
|
||||
}
|
||||
@@ -3,14 +3,13 @@
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
using JetBrains.Annotations;
|
||||
using WireMock.ResponseProviders;
|
||||
|
||||
namespace WireMock.ResponseBuilders;
|
||||
|
||||
/// <summary>
|
||||
/// The CallbackResponseBuilder interface.
|
||||
/// </summary>
|
||||
public interface ICallbackResponseBuilder : IResponseProvider
|
||||
public interface ICallbackResponseBuilder : IWebSocketResponseBuilder
|
||||
{
|
||||
/// <summary>
|
||||
/// The callback builder
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
// Copyright © WireMock.Net
|
||||
|
||||
using System;
|
||||
using WireMock.ResponseProviders;
|
||||
using WireMock.Settings;
|
||||
using WireMock.WebSockets;
|
||||
|
||||
namespace WireMock.ResponseBuilders;
|
||||
|
||||
/// <summary>
|
||||
/// The WebSocketResponseBuilder interface.
|
||||
/// </summary>
|
||||
public interface IWebSocketResponseBuilder : IResponseProvider
|
||||
{
|
||||
/// <summary>
|
||||
/// Configure WebSocket response behavior
|
||||
/// </summary>
|
||||
IResponseBuilder WithWebSocket(Action<IWebSocketBuilder> configure);
|
||||
|
||||
/// <summary>
|
||||
/// Proxy WebSocket to another server
|
||||
/// </summary>
|
||||
IResponseBuilder WithWebSocketProxy(string targetUrl);
|
||||
|
||||
/// <summary>
|
||||
/// Proxy WebSocket to another server with settings
|
||||
/// </summary>
|
||||
IResponseBuilder WithWebSocketProxy(ProxyAndRecordSettings settings);
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
// This source file is based on mock4net by Alexandre Victoor which is licensed under the Apache 2.0 License.
|
||||
// For more details see 'mock4net/LICENSE.txt' and 'mock4net/readme.md' in this project root.
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using WireMock.Settings;
|
||||
|
||||
namespace WireMock.ResponseProviders;
|
||||
@@ -16,8 +17,9 @@ public interface IResponseProvider
|
||||
/// The provide response.
|
||||
/// </summary>
|
||||
/// <param name="mapping">The used mapping.</param>
|
||||
/// <param name="context">The HttpContext.</param>
|
||||
/// <param name="requestMessage">The request.</param>
|
||||
/// <param name="settings">The WireMockServerSettings.</param>
|
||||
/// <returns>The <see cref="IResponseMessage"/> including a new (optional) <see cref="IMapping"/>.</returns>
|
||||
Task<(IResponseMessage Message, IMapping? Mapping)> ProvideResponseAsync(IMapping mapping, IRequestMessage requestMessage, WireMockServerSettings settings);
|
||||
Task<(IResponseMessage Message, IMapping? Mapping)> ProvideResponseAsync(IMapping mapping, HttpContext context, IRequestMessage requestMessage, WireMockServerSettings settings);
|
||||
}
|
||||
@@ -39,4 +39,4 @@ public class ActivityTracingOptions
|
||||
/// Default is <c>true</c>.
|
||||
/// </summary>
|
||||
public bool RecordMatchDetails { get; set; } = true;
|
||||
}
|
||||
}
|
||||
@@ -82,11 +82,13 @@ public class ProxyAndRecordSettings : HttpClientSettings
|
||||
[PublicAPI]
|
||||
public ProxyUrlReplaceSettings? ReplaceSettings { get; set; }
|
||||
|
||||
/*
|
||||
/// <summary>
|
||||
/// Prefer the Proxy Mapping over the saved Mapping (in case SaveMapping is set to <c>true</c>).
|
||||
/// </summary>
|
||||
//[PublicAPI]
|
||||
//public bool PreferProxyMapping { get; set; }
|
||||
*/
|
||||
|
||||
/// <summary>
|
||||
/// When SaveMapping is set to <c>true</c>, this setting can be used to control the behavior of the generated request matchers for the new mapping.
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
// Copyright © WireMock.Net
|
||||
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using WireMock.Extensions;
|
||||
using WireMock.Util;
|
||||
|
||||
@@ -197,6 +194,6 @@ internal class SimpleSettingsParser
|
||||
public T? GetObjectValueFromJson<T>(string name)
|
||||
{
|
||||
var value = GetValue(name, values => values.FirstOrDefault());
|
||||
return string.IsNullOrWhiteSpace(value) ? default : JsonUtils.DeserializeObject<T>(value);
|
||||
return string.IsNullOrWhiteSpace(value) ? default : JsonUtils.DeserializeObject<T>(value!);
|
||||
}
|
||||
}
|
||||
|
||||
21
src/WireMock.Net.Shared/Settings/WebSocketSettings.cs
Normal file
21
src/WireMock.Net.Shared/Settings/WebSocketSettings.cs
Normal file
@@ -0,0 +1,21 @@
|
||||
// Copyright © WireMock.Net
|
||||
|
||||
using WireMock.Constants;
|
||||
|
||||
namespace WireMock.Settings;
|
||||
|
||||
/// <summary>
|
||||
/// WebSocket-specific settings
|
||||
/// </summary>
|
||||
public class WebSocketSettings
|
||||
{
|
||||
/// <summary>
|
||||
/// Maximum number of concurrent WebSocket connections (default: 100)
|
||||
/// </summary>
|
||||
public int MaxConnections { get; set; } = 100;
|
||||
|
||||
/// <summary>
|
||||
/// Default keep-alive interval (default: 30 seconds)
|
||||
/// </summary>
|
||||
public int KeepAliveIntervalSeconds { get; set; } = WebSocketConstants.DefaultKeepAliveIntervalSeconds;
|
||||
}
|
||||
@@ -1,25 +1,20 @@
|
||||
// Copyright © WireMock.Net
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Text.RegularExpressions;
|
||||
using HandlebarsDotNet;
|
||||
using JetBrains.Annotations;
|
||||
using JsonConverter.Abstractions;
|
||||
using JsonConverter.Newtonsoft.Json;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Newtonsoft.Json;
|
||||
using WireMock.Admin.Mappings;
|
||||
using WireMock.Handlers;
|
||||
using WireMock.Logging;
|
||||
using WireMock.Matchers;
|
||||
using WireMock.Models;
|
||||
using WireMock.RegularExpressions;
|
||||
using WireMock.Types;
|
||||
using System.Globalization;
|
||||
using WireMock.Models;
|
||||
using JsonConverter.Abstractions;
|
||||
using JsonConverter.Newtonsoft.Json;
|
||||
|
||||
#if USE_ASPNETCORE
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
#endif
|
||||
|
||||
namespace WireMock.Settings;
|
||||
|
||||
@@ -153,7 +148,6 @@ public class WireMockServerSettings
|
||||
[JsonIgnore]
|
||||
public Action<object>? PostWireMockMiddlewareInit { get; set; }
|
||||
|
||||
#if USE_ASPNETCORE
|
||||
/// <summary>
|
||||
/// Action which is called with IServiceCollection when ASP.NET Core DI is being configured. [Optional]
|
||||
/// </summary>
|
||||
@@ -166,7 +160,6 @@ public class WireMockServerSettings
|
||||
/// </summary>
|
||||
[PublicAPI]
|
||||
public CorsPolicyOptions? CorsPolicyOptions { get; set; }
|
||||
#endif
|
||||
|
||||
/// <summary>
|
||||
/// The IWireMockLogger which logs Debug, Info, Warning or Error
|
||||
@@ -251,7 +244,6 @@ public class WireMockServerSettings
|
||||
[PublicAPI]
|
||||
public bool CustomCertificateDefined => CertificateSettings?.IsDefined == true;
|
||||
|
||||
#if USE_ASPNETCORE
|
||||
/// <summary>
|
||||
/// Client certificate mode for the server
|
||||
/// </summary>
|
||||
@@ -262,8 +254,7 @@ public class WireMockServerSettings
|
||||
/// Whether to accept any client certificate
|
||||
/// </summary>
|
||||
public bool AcceptAnyClientCertificate { get; set; }
|
||||
#endif
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Defines the global IWebhookSettings to use.
|
||||
/// </summary>
|
||||
@@ -361,4 +352,10 @@ public class WireMockServerSettings
|
||||
/// </remarks>
|
||||
[PublicAPI]
|
||||
public IJsonConverter DefaultJsonSerializer { get; set; } = new NewtonsoftJsonConverter();
|
||||
|
||||
/// <summary>
|
||||
/// WebSocket settings.
|
||||
/// </summary>
|
||||
[PublicAPI]
|
||||
public WebSocketSettings? WebSocketSettings { get; set; }
|
||||
}
|
||||
@@ -1,11 +1,8 @@
|
||||
// Copyright © WireMock.Net
|
||||
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Stef.Validation;
|
||||
using WireMock.Constants;
|
||||
using WireMock.Matchers;
|
||||
@@ -16,7 +13,7 @@ namespace WireMock.Util;
|
||||
internal static class BodyParser
|
||||
{
|
||||
private static readonly Encoding DefaultEncoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);
|
||||
private static readonly Encoding[] SupportedBodyAsStringEncodingForMultipart = [ DefaultEncoding, Encoding.ASCII ];
|
||||
private static readonly Encoding[] SupportedBodyAsStringEncodingForMultipart = [DefaultEncoding, Encoding.ASCII];
|
||||
|
||||
/*
|
||||
HEAD - No defined body semantics.
|
||||
@@ -156,7 +153,7 @@ internal static class BodyParser
|
||||
}
|
||||
|
||||
// Try to get the body as String, FormUrlEncoded or Json
|
||||
try
|
||||
if (IsProbablyText(data.BodyAsBytes))
|
||||
{
|
||||
data.BodyAsString = DefaultEncoding.GetString(data.BodyAsBytes);
|
||||
data.Encoding = DefaultEncoding;
|
||||
@@ -168,15 +165,8 @@ internal static class BodyParser
|
||||
QueryStringParser.TryParse(data.BodyAsString, false, out var nameValueCollection)
|
||||
)
|
||||
{
|
||||
try
|
||||
{
|
||||
data.BodyAsFormUrlEncoded = nameValueCollection;
|
||||
data.DetectedBodyType = BodyType.FormUrlEncoded;
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Deserialize FormUrlEncoded failed, just ignore.
|
||||
}
|
||||
data.BodyAsFormUrlEncoded = nameValueCollection;
|
||||
data.DetectedBodyType = BodyType.FormUrlEncoded;
|
||||
}
|
||||
|
||||
// If string is not null or empty, try to deserialize the string to a JObject
|
||||
@@ -193,14 +183,10 @@ internal static class BodyParser
|
||||
}
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Reading as string failed, just ignore
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
|
||||
private static async Task<(string? ContentType, byte[] Bytes)> ReadBytesAsync(Stream stream, string? contentEncoding = null, bool decompressGZipAndDeflate = true)
|
||||
{
|
||||
using var memoryStream = new MemoryStream();
|
||||
@@ -215,4 +201,39 @@ internal static class BodyParser
|
||||
|
||||
return (null, data);
|
||||
}
|
||||
|
||||
public static bool IsProbablyText(byte[] data)
|
||||
{
|
||||
if (data.Length == 0)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
// 1) Quick binary detection
|
||||
for (int i = 0; i < data.Length; i++)
|
||||
{
|
||||
if (data[i] == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 2) Validate UTF-8
|
||||
string text;
|
||||
try
|
||||
{
|
||||
text = DefaultEncoding.GetString(data);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// 3) Count printable characters
|
||||
var printable = text.Count(c => !char.IsControl(c) || char.IsWhiteSpace(c));
|
||||
var ratio = (double)printable / text.Length;
|
||||
|
||||
// Threshold commonly used by tools like git
|
||||
return ratio > 0.85;
|
||||
}
|
||||
}
|
||||
@@ -22,10 +22,7 @@ internal static class CompressionUtils
|
||||
using var compressedStream = new MemoryStream();
|
||||
using var zipStream = Create(contentEncoding, compressedStream, CompressionMode.Compress);
|
||||
zipStream.Write(data, 0, data.Length);
|
||||
|
||||
#if !NETSTANDARD1_3
|
||||
zipStream.Close();
|
||||
#endif
|
||||
return compressedStream.ToArray();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,5 @@
|
||||
// Copyright © WireMock.Net
|
||||
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using JsonConverter.Abstractions;
|
||||
using WireMock.ResponseBuilders;
|
||||
|
||||
@@ -13,7 +10,24 @@ namespace WireMock.Util;
|
||||
/// </summary>
|
||||
public interface IProtoBufUtils
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts a JSON-like object to a ProtoBuf message including the length header.
|
||||
/// </summary>
|
||||
/// <param name="protoDefinitions">The Proto definition content used to resolve message types.</param>
|
||||
/// <param name="messageType">The fully qualified ProtoBuf message type name to serialize to.</param>
|
||||
/// <param name="value">The source object to convert.</param>
|
||||
/// <param name="jsonConverter">Optional JSON converter used during serialization.</param>
|
||||
/// <param name="cancellationToken">The cancellation token.</param>
|
||||
/// <returns>The serialized ProtoBuf payload with header, or an empty byte array when input is invalid.</returns>
|
||||
Task<byte[]> GetProtoBufMessageWithHeaderAsync(IReadOnlyList<string>? protoDefinitions, string? messageType, object? value, IJsonConverter? jsonConverter = null, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Updates the response builder to return a ProtoBuf body using method-level or mapping-level proto definitions.
|
||||
/// </summary>
|
||||
/// <param name="responseBuilder">The response builder to update.</param>
|
||||
/// <param name="protoBufMessageType">The ProtoBuf message type for the response body.</param>
|
||||
/// <param name="bodyAsJson">The response body object represented as JSON-like data.</param>
|
||||
/// <param name="protoDefinitions">Optional Proto definitions for this call; when omitted, mapping/server-level definitions are used.</param>
|
||||
/// <returns>The updated response builder.</returns>
|
||||
IResponseBuilder UpdateResponseBuilder(IResponseBuilder responseBuilder, string protoBufMessageType, object bodyAsJson, params string[] protoDefinitions);
|
||||
}
|
||||
@@ -1,9 +1,8 @@
|
||||
// Copyright © WireMock.Net
|
||||
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Diagnostics;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using Stef.Validation;
|
||||
@@ -142,16 +141,13 @@ internal static class TypeLoader
|
||||
|
||||
private static bool TryFindTypeInDlls<TInterface>(string? implementationTypeFullName, [NotNullWhen(true)] out Type? pluginType) where TInterface : class
|
||||
{
|
||||
#if NETSTANDARD1_3
|
||||
var directoriesToSearch = new[] { AppContext.BaseDirectory };
|
||||
#else
|
||||
var processDirectory = Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule?.FileName);
|
||||
var processDirectory = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule?.FileName);
|
||||
var assemblyDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
|
||||
var directoriesToSearch = new[] { processDirectory, assemblyDirectory }
|
||||
.Where(d => !string.IsNullOrEmpty(d))
|
||||
.Distinct()
|
||||
.ToArray();
|
||||
#endif
|
||||
|
||||
foreach (var directory in directoriesToSearch)
|
||||
{
|
||||
foreach (var file in Directory.GetFiles(directory!, "*.dll"))
|
||||
|
||||
96
src/WireMock.Net.Shared/WebSockets/IWebSocketBuilder.cs
Normal file
96
src/WireMock.Net.Shared/WebSockets/IWebSocketBuilder.cs
Normal file
@@ -0,0 +1,96 @@
|
||||
// Copyright © WireMock.Net
|
||||
|
||||
using JetBrains.Annotations;
|
||||
using WireMock.Matchers;
|
||||
using WireMock.Settings;
|
||||
|
||||
namespace WireMock.WebSockets;
|
||||
|
||||
/// <summary>
|
||||
/// WebSocket Response Builder interface
|
||||
/// </summary>
|
||||
public interface IWebSocketBuilder
|
||||
{
|
||||
/// <summary>
|
||||
/// Accept the WebSocket with a specific protocol
|
||||
/// </summary>
|
||||
[PublicAPI]
|
||||
IWebSocketBuilder WithAcceptProtocol(string protocol);
|
||||
|
||||
/// <summary>
|
||||
/// Echo all received messages back to client
|
||||
/// </summary>
|
||||
[PublicAPI]
|
||||
IWebSocketBuilder WithEcho();
|
||||
|
||||
/// <summary>
|
||||
/// Configure and send a single message in response to any received message
|
||||
/// </summary>
|
||||
/// <param name="configure">Action to configure the message</param>
|
||||
[PublicAPI]
|
||||
IWebSocketBuilder SendMessage(Action<IWebSocketMessageBuilder> configure);
|
||||
|
||||
/// <summary>
|
||||
/// Configure and send multiple messages in response to any received message
|
||||
/// </summary>
|
||||
/// <param name="configure">Action to configure the messages</param>
|
||||
[PublicAPI]
|
||||
IWebSocketBuilder SendMessages(Action<IWebSocketMessagesBuilder> configure);
|
||||
|
||||
/// <summary>
|
||||
/// Configure message sending based on message content matching
|
||||
/// </summary>
|
||||
/// <param name="wildcardPattern">String to match in message text</param>
|
||||
[PublicAPI]
|
||||
IWebSocketMessageConditionBuilder WhenMessage(string wildcardPattern);
|
||||
|
||||
/// <summary>
|
||||
/// Configure message sending based on message content matching
|
||||
/// </summary>
|
||||
/// <param name="exactPattern">Bytes to match in message</param>
|
||||
[PublicAPI]
|
||||
IWebSocketMessageConditionBuilder WhenMessage(byte[] exactPattern);
|
||||
|
||||
/// <summary>
|
||||
/// Configure message sending based on IMatcher
|
||||
/// </summary>
|
||||
/// <param name="matcher">IMatcher to match the message</param>
|
||||
[PublicAPI]
|
||||
IWebSocketMessageConditionBuilder WhenMessage(IMatcher matcher);
|
||||
|
||||
/// <summary>
|
||||
/// Handle incoming WebSocket messages
|
||||
/// </summary>
|
||||
[PublicAPI]
|
||||
IWebSocketBuilder WithMessageHandler(Func<WebSocketMessage, IWebSocketContext, Task> handler);
|
||||
|
||||
/// <summary>
|
||||
/// Proxy to another WebSocket server
|
||||
/// </summary>
|
||||
[PublicAPI]
|
||||
IWebSocketBuilder WithProxy(ProxyAndRecordSettings settings);
|
||||
|
||||
/// <summary>
|
||||
/// Set close timeout (default: 10 minutes)
|
||||
/// </summary>
|
||||
[PublicAPI]
|
||||
IWebSocketBuilder WithCloseTimeout(TimeSpan timeout);
|
||||
|
||||
/// <summary>
|
||||
/// Set maximum message size in bytes (default: 1 MB)
|
||||
/// </summary>
|
||||
[PublicAPI]
|
||||
IWebSocketBuilder WithMaxMessageSize(int sizeInBytes);
|
||||
|
||||
/// <summary>
|
||||
/// Set receive buffer size (default: 4096 bytes)
|
||||
/// </summary>
|
||||
[PublicAPI]
|
||||
IWebSocketBuilder WithReceiveBufferSize(int sizeInBytes);
|
||||
|
||||
/// <summary>
|
||||
/// Set keep-alive interval (default: 30 seconds)
|
||||
/// </summary>
|
||||
[PublicAPI]
|
||||
IWebSocketBuilder WithKeepAliveInterval(TimeSpan interval);
|
||||
}
|
||||
67
src/WireMock.Net.Shared/WebSockets/IWebSocketContext.cs
Normal file
67
src/WireMock.Net.Shared/WebSockets/IWebSocketContext.cs
Normal file
@@ -0,0 +1,67 @@
|
||||
// Copyright © WireMock.Net
|
||||
|
||||
using System.Net.WebSockets;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace WireMock.WebSockets;
|
||||
|
||||
/// <summary>
|
||||
/// WebSocket context interface for handling WebSocket connections
|
||||
/// </summary>
|
||||
public interface IWebSocketContext
|
||||
{
|
||||
/// <summary>
|
||||
/// Unique connection identifier
|
||||
/// </summary>
|
||||
Guid ConnectionId { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The ASP.NET Core HttpContext
|
||||
/// </summary>
|
||||
HttpContext HttpContext { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The WebSocket instance
|
||||
/// </summary>
|
||||
WebSocket WebSocket { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The original request that initiated the WebSocket connection
|
||||
/// </summary>
|
||||
IRequestMessage RequestMessage { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The mapping that matched this WebSocket request
|
||||
/// </summary>
|
||||
IMapping Mapping { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Send text message to the client
|
||||
/// </summary>
|
||||
Task SendAsync(string text, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Send binary message to the client
|
||||
/// </summary>
|
||||
Task SendAsync(byte[] bytes, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Close the WebSocket connection
|
||||
/// </summary>
|
||||
Task CloseAsync(WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Abort the WebSocket connection to immediately close the connection without waiting for the close handshake
|
||||
/// </summary>
|
||||
void Abort(string? statusDescription = null);
|
||||
|
||||
/// <summary>
|
||||
/// Broadcast text message to all connections in this mapping
|
||||
/// </summary>
|
||||
Task BroadcastAsync(string text, bool excludeSender = false, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// Broadcast binary message to all connections in this mapping
|
||||
/// </summary>
|
||||
Task BroadcastAsync(byte[] bytes, bool excludeSender = false, CancellationToken cancellationToken = default);
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
// Copyright © WireMock.Net
|
||||
|
||||
using JetBrains.Annotations;
|
||||
|
||||
namespace WireMock.WebSockets;
|
||||
|
||||
/// <summary>
|
||||
/// WebSocket Message Builder interface for building individual messages with optional delays
|
||||
/// </summary>
|
||||
public interface IWebSocketMessageBuilder
|
||||
{
|
||||
/// <summary>
|
||||
/// Echo all received messages back to client
|
||||
/// </summary>
|
||||
[PublicAPI]
|
||||
IWebSocketMessageBuilder WithEcho();
|
||||
|
||||
/// <summary>
|
||||
/// Send a specific text message
|
||||
/// </summary>
|
||||
/// <param name="text">The text message to send</param>
|
||||
[PublicAPI]
|
||||
IWebSocketMessageBuilder WithText(string text);
|
||||
|
||||
/// <summary>
|
||||
/// Send specific binary data
|
||||
/// </summary>
|
||||
/// <param name="bytes">The binary data to send</param>
|
||||
[PublicAPI]
|
||||
IWebSocketMessageBuilder WithBinary(byte[] bytes);
|
||||
|
||||
/// <summary>
|
||||
/// Set a delay before sending the message (using TimeSpan)
|
||||
/// </summary>
|
||||
/// <param name="delay">The delay before sending the message</param>
|
||||
[PublicAPI]
|
||||
IWebSocketMessageBuilder WithDelay(TimeSpan delay);
|
||||
|
||||
/// <summary>
|
||||
/// Set a delay before sending the message (using milliseconds)
|
||||
/// </summary>
|
||||
/// <param name="delayInMilliseconds">The delay in milliseconds before sending the message</param>
|
||||
[PublicAPI]
|
||||
IWebSocketMessageBuilder WithDelay(int delayInMilliseconds);
|
||||
|
||||
/// <summary>
|
||||
/// Close the WebSocket connection after this message
|
||||
/// </summary>
|
||||
[PublicAPI]
|
||||
IWebSocketMessageBuilder AndClose();
|
||||
|
||||
/// <summary>
|
||||
/// Close the WebSocket connection.
|
||||
/// </summary>
|
||||
[PublicAPI]
|
||||
IWebSocketMessageBuilder Close();
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
// Copyright © WireMock.Net
|
||||
|
||||
using JetBrains.Annotations;
|
||||
|
||||
namespace WireMock.WebSockets;
|
||||
|
||||
/// <summary>
|
||||
/// WebSocket Message Condition Builder interface for building conditional message responses
|
||||
/// </summary>
|
||||
public interface IWebSocketMessageConditionBuilder
|
||||
{
|
||||
/// <summary>
|
||||
/// Configure and send a message when the condition matches
|
||||
/// </summary>
|
||||
/// <param name="configure">Action to configure the message</param>
|
||||
[PublicAPI]
|
||||
IWebSocketBuilder ThenSendMessage(Action<IWebSocketMessageBuilder> configure);
|
||||
|
||||
/// <summary>
|
||||
/// Configure and send multiple messages when the condition matches
|
||||
/// </summary>
|
||||
/// <param name="configure">Action to configure the messages</param>
|
||||
[PublicAPI]
|
||||
IWebSocketBuilder SendMessages(Action<IWebSocketMessagesBuilder> configure);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
// Copyright © WireMock.Net
|
||||
|
||||
using JetBrains.Annotations;
|
||||
|
||||
namespace WireMock.WebSockets;
|
||||
|
||||
/// <summary>
|
||||
/// WebSocket Messages Builder interface for building multiple messages
|
||||
/// </summary>
|
||||
public interface IWebSocketMessagesBuilder
|
||||
{
|
||||
/// <summary>
|
||||
/// Add a message to the sequence
|
||||
/// </summary>
|
||||
/// <param name="configure">Action to configure the message</param>
|
||||
[PublicAPI]
|
||||
IWebSocketMessagesBuilder AddMessage(Action<IWebSocketMessageBuilder> configure);
|
||||
}
|
||||
36
src/WireMock.Net.Shared/WebSockets/WebSocketMessage.cs
Normal file
36
src/WireMock.Net.Shared/WebSockets/WebSocketMessage.cs
Normal file
@@ -0,0 +1,36 @@
|
||||
// Copyright © WireMock.Net
|
||||
|
||||
using System.Net.WebSockets;
|
||||
|
||||
namespace WireMock.WebSockets;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a WebSocket message
|
||||
/// </summary>
|
||||
public class WebSocketMessage
|
||||
{
|
||||
/// <summary>
|
||||
/// The message type (Text or Binary)
|
||||
/// </summary>
|
||||
public WebSocketMessageType MessageType { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Text content (when MessageType is Text)
|
||||
/// </summary>
|
||||
public string? Text { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Binary content (when MessageType is Binary)
|
||||
/// </summary>
|
||||
public byte[]? Bytes { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Indicates whether this is the final message
|
||||
/// </summary>
|
||||
public bool EndOfMessage { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Timestamp when the message was received
|
||||
/// </summary>
|
||||
public DateTime Timestamp { get; set; }
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
<PropertyGroup>
|
||||
<Description>Shared interfaces, models, enumerations and types.</Description>
|
||||
<Authors>Stef Heyenrath</Authors>
|
||||
<TargetFrameworks>net451;net452;net46;net461;netstandard1.3;netstandard2.0;netstandard2.1;netcoreapp3.1;net5.0;net6.0;net7.0;net8.0</TargetFrameworks>
|
||||
<TargetFrameworks>netstandard2.0;netstandard2.1;net8.0</TargetFrameworks>
|
||||
<GenerateDocumentationFile>true</GenerateDocumentationFile>
|
||||
<PackageTags>tdd;mock;http;wiremock;test;server;shared</PackageTags>
|
||||
<RootNamespace>WireMock</RootNamespace>
|
||||
@@ -16,10 +16,6 @@
|
||||
<PublicSign Condition=" '$(OS)' != 'Windows_NT' ">true</PublicSign>
|
||||
</PropertyGroup>
|
||||
|
||||
<!-- https://github.com/aspnet/RoslynCodeDomProvider/issues/51 -->
|
||||
<!-- This is needed else we cannot build net452 in Azure DevOps Pipeline -->
|
||||
<!--<Target Name="CheckIfShouldKillVBCSCompiler" />-->
|
||||
|
||||
<PropertyGroup Condition="'$(Configuration)' == 'Debug - Sonar'">
|
||||
<CodeAnalysisRuleSet>../WireMock.Net/WireMock.Net.ruleset</CodeAnalysisRuleSet>
|
||||
</PropertyGroup>
|
||||
@@ -29,28 +25,11 @@
|
||||
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup Condition="'$(TargetFramework)' == 'netstandard1.3' or '$(TargetFramework)' == 'netstandard2.0' or '$(TargetFramework)' == 'netstandard2.1'">
|
||||
<DefineConstants>$(DefineConstants);NETSTANDARD;USE_ASPNETCORE</DefineConstants>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup Condition="'$(TargetFramework)' == 'netcoreapp2.1' or '$(TargetFramework)' == 'netcoreapp2.2' or '$(TargetFramework)' == 'netcoreapp3.1' or '$(TargetFramework)' == 'net5.0' or '$(TargetFramework)' == 'net6.0' or '$(TargetFramework)' == 'net7.0' or '$(TargetFramework)' == 'net8.0'">
|
||||
<DefineConstants>$(DefineConstants);USE_ASPNETCORE</DefineConstants>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup Condition="'$(TargetFramework)' == 'net461'">
|
||||
<DefineConstants>$(DefineConstants);USE_ASPNETCORE;NET46</DefineConstants>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="PolySharp" Version="1.15.0">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Stef.Validation" Version="0.1.1" />
|
||||
<PackageReference Include="AnyOf" Version="0.4.0" />
|
||||
<!--<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />-->
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="1.1.0" />
|
||||
<!--<PackageReference Include="JsonConverter.Abstractions" Version="0.8.0" />-->
|
||||
<PackageReference Include="Microsoft.AspNetCore.Http" Version="2.3.9" />
|
||||
<PackageReference Include="Stef.Validation" Version="0.2.0" />
|
||||
<PackageReference Include="AnyOf" Version="0.5.0.1" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.2" />
|
||||
<PackageReference Include="JsonConverter.Newtonsoft.Json" Version="0.8.0" />
|
||||
</ItemGroup>
|
||||
|
||||
@@ -62,13 +41,25 @@
|
||||
<PackageReference Include="Handlebars.Net.Helpers.Random" Version="2.5.2" />
|
||||
<PackageReference Include="Handlebars.Net.Helpers.Xeger" Version="2.5.2" />
|
||||
<PackageReference Include="Handlebars.Net.Helpers.XPath" Version="2.5.2" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup Condition=" '$(TargetFramework)' == 'netstandard1.3' ">
|
||||
<PackageReference Include="System.Reflection.TypeExtensions" Version="4.7.0" />
|
||||
<PackageReference Include="Handlebars.Net.Helpers.Xslt" Version="2.5.2" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\WireMock.Net.Abstractions\WireMock.Net.Abstractions.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup Condition=" '$(TargetFramework)' == 'netstandard2.0' or '$(TargetFramework)' == 'netstandard2.1' ">
|
||||
<PackageReference Include="Required" Version="1.0.0">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="IsExternalInit" Version="1.0.3">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Nullable" Version="1.3.1">
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
</PackageReference>
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
Reference in New Issue
Block a user