cleanup + fix tests for net8

This commit is contained in:
Stef Heyenrath
2025-08-31 11:39:03 +02:00
parent bb561c94d0
commit b111b019bc
20 changed files with 93 additions and 294 deletions

View File

@@ -1,28 +0,0 @@
// Copyright © WireMock.Net
#if NETSTANDARD1_3
// ReSharper disable once CheckNamespace
namespace System.Net;
internal class WebProxy : IWebProxy
{
private readonly string _proxy;
public ICredentials? Credentials { get; set; }
public WebProxy(string proxy)
{
_proxy = proxy;
}
public Uri GetProxy(Uri destination)
{
return new Uri(_proxy);
}
public bool IsBypassed(Uri host)
{
return true;
}
}
#endif

View File

@@ -1,5 +1,6 @@
// Copyright © WireMock.Net
#if NET5_0_OR_GREATER
#if NET8_0_OR_GREATER
using System;
using System.Net.Http;
using WireMock.Server;

View File

@@ -43,11 +43,11 @@ internal static class CertificateLoader
}
finally
{
#if NETSTANDARD || NET46
//#if NETSTANDARD || NET48
certStore.Dispose();
#else
//#else
certStore.Close();
#endif
//#endif
}
}
@@ -56,7 +56,7 @@ internal static class CertificateLoader
if (options.X509CertificateFilePath.EndsWith(ExtensionPem, StringComparison.OrdinalIgnoreCase))
{
// PEM logic based on: https://www.scottbrady91.com/c-sharp/pem-loading-in-dotnet-core-and-dotnet
#if NET5_0_OR_GREATER
#if NET8_0_OR_GREATER
if (!string.IsNullOrEmpty(options.X509CertificatePassword))
{
var certPem = File.ReadAllText(options.X509CertificateFilePath);
@@ -66,18 +66,8 @@ internal static class CertificateLoader
return new X509Certificate2(cert.Export(X509ContentType.Pfx, defaultPasswordPem), defaultPasswordPem);
}
return X509Certificate2.CreateFromPemFile(options.X509CertificateFilePath);
#elif NETCOREAPP3_1
var cert = new X509Certificate2(options.X509CertificateFilePath);
if (!string.IsNullOrEmpty(options.X509CertificatePassword))
{
var key = System.Security.Cryptography.ECDsa.Create()!;
key.ImportECPrivateKey(System.Text.Encoding.UTF8.GetBytes(options.X509CertificatePassword), out _);
return cert.CopyWithPrivateKey(key);
}
return cert;
#else
throw new InvalidOperationException("Loading a PEM Certificate is only supported for .NET Core App 3.1, .NET 5.0 and higher.");
throw new InvalidOperationException("Loading a PEM Certificate is only supported for .NET 8.0 and higher.");
#endif
}
@@ -123,11 +113,11 @@ internal static class CertificateLoader
}
finally
{
#if NETSTANDARD || NET46
//#if NETSTANDARD || NET46
certStore.Dispose();
#else
//#else
certStore.Close();
#endif
//#endif
}
}
}

View File

@@ -9,6 +9,8 @@ namespace WireMock.Owin;
internal partial class AspNetCoreSelfHost
{
private const string CorsPolicyName = "WireMock.Net - Policy";
public void AddCors(IServiceCollection services)
{
if (_wireMockMiddlewareOptions.CorsPolicyOptions > CorsPolicyOptions.None)

View File

@@ -1,57 +0,0 @@
// Copyright © WireMock.Net
//#if USE_ASPNETCORE && NETSTANDARD1_3
//using System.Collections.Generic;
//using Microsoft.AspNetCore.Hosting;
//using Microsoft.AspNetCore.Server.Kestrel;
//using Microsoft.AspNetCore.Server.Kestrel.Https;
//using Microsoft.Extensions.Configuration;
//using Microsoft.Extensions.DependencyInjection;
//using WireMock.HttpsCertificate;
//namespace WireMock.Owin;
//internal partial class AspNetCoreSelfHost
//{
// private static void SetKestrelOptionsLimits(KestrelServerOptions options)
// {
// options.Limits.MaxRequestBufferSize = null;
// options.Limits.MaxRequestHeaderCount = 100;
// options.Limits.MaxResponseBufferSize = null;
// }
// private static void SetHttpsAndUrls(KestrelServerOptions options, IWireMockMiddlewareOptions wireMockMiddlewareOptions, IEnumerable<HostUrlDetails> urlDetails)
// {
// foreach (var urlDetail in urlDetails)
// {
// if (urlDetail.IsHttps)
// {
// options.UseHttps(new HttpsConnectionFilterOptions
// {
// ServerCertificate = wireMockMiddlewareOptions.CustomCertificateDefined ? CertificateLoader.LoadCertificate(wireMockMiddlewareOptions, urlDetail.Host) : PublicCertificateHelper.GetX509Certificate2(),
// ClientCertificateMode = (ClientCertificateMode) wireMockMiddlewareOptions.ClientCertificateMode,
// ClientCertificateValidation = wireMockMiddlewareOptions.AcceptAnyClientCertificate ? (_, _, _) => true : null
// });
// }
// }
// }
//}
//internal static class IWebHostBuilderExtensions
//{
// internal static IWebHostBuilder ConfigureAppConfigurationUsingEnvironmentVariables(this IWebHostBuilder builder) => builder;
// internal static IWebHostBuilder ConfigureKestrelServerOptions(this IWebHostBuilder builder)
// {
// var configuration = new ConfigurationBuilder()
// .AddEnvironmentVariables()
// .Build();
// return builder.ConfigureServices(services =>
// {
// services.Configure<KestrelServerOptions>(configuration.GetSection("Kestrel"));
// });
// }
//}
//#endif

View File

@@ -19,8 +19,6 @@ namespace WireMock.Owin;
internal partial class AspNetCoreSelfHost : IOwinSelfHost
{
private const string CorsPolicyName = "WireMock.Net - Policy";
private readonly CancellationTokenSource _cts = new();
private readonly IWireMockMiddlewareOptions _wireMockMiddlewareOptions;
private readonly IWireMockLogger _logger;
@@ -99,36 +97,36 @@ internal partial class AspNetCoreSelfHost : IOwinSelfHost
})
.ConfigureKestrelServerOptions()
//#if NETSTANDARD1_3
// .UseUrls(_urlOptions.GetDetails().Select(u => u.Url).ToArray())
//#endif
//#if NETSTANDARD1_3
// .UseUrls(_urlOptions.GetDetails().Select(u => u.Url).ToArray())
//#endif
.Build();
return RunHost(_cts.Token);
}
private Task RunHost(CancellationToken token)
private Task RunHost(CancellationToken token)
{
try
{
try
{
#if NET8_0_OR_GREATER
var appLifetime = _host.Services.GetRequiredService<Microsoft.Extensions.Hosting.IHostApplicationLifetime>();
var appLifetime = _host.Services.GetRequiredService<Microsoft.Extensions.Hosting.IHostApplicationLifetime>();
#else
var appLifetime = _host.Services.GetRequiredService<IApplicationLifetime>();
var appLifetime = _host.Services.GetRequiredService<IApplicationLifetime>();
#endif
appLifetime.ApplicationStarted.Register(() =>
appLifetime.ApplicationStarted.Register(() =>
{
var addresses = _host.ServerFeatures
.Get<Microsoft.AspNetCore.Hosting.Server.Features.IServerAddressesFeature>()!
.Addresses;
foreach (var address in addresses)
{
var addresses = _host.ServerFeatures
.Get<Microsoft.AspNetCore.Hosting.Server.Features.IServerAddressesFeature>()!
.Addresses;
Urls.Add(address.Replace("0.0.0.0", "localhost").Replace("[::]", "localhost"));
foreach (var address in addresses)
{
Urls.Add(address.Replace("0.0.0.0", "localhost").Replace("[::]", "localhost"));
PortUtils.TryExtract(address, out _, out _, out _, out _, out var port);
Ports.Add(port);
}
PortUtils.TryExtract(address, out _, out _, out _, out _, out var port);
Ports.Add(port);
}
IsStarted = true;
});
@@ -139,14 +137,14 @@ internal partial class AspNetCoreSelfHost : IOwinSelfHost
_logger.Info("Server using .NET Framework 4.8");
#endif
//#if NETSTANDARD1_3
// return Task.Run(() =>
// {
// _host.Run(token);
// });
//#else
//#if NETSTANDARD1_3
// return Task.Run(() =>
// {
// _host.Run(token);
// });
//#else
return _host.RunAsync(token);
//#endif
//#endif
}
catch (Exception e)
{
@@ -164,11 +162,11 @@ internal partial class AspNetCoreSelfHost : IOwinSelfHost
_cts.Cancel();
IsStarted = false;
//#if NETSTANDARD1_3
// return Task.CompletedTask;
//#else
//#if NETSTANDARD1_3
// return Task.CompletedTask;
//#else
return _host.StopAsync();
//#endif
//#endif
}
}
//#endif

View File

@@ -55,10 +55,10 @@ internal class HostUrlOptions
private static int FindFreeTcpPort()
{
#if USE_ASPNETCORE || NETSTANDARD2_0 || NETSTANDARD2_1
//#if USE_ASPNETCORE || NETSTANDARD2_0 || NETSTANDARD2_1
return 0;
#else
return PortUtils.FindFreeTcpPort();
#endif
//#else
//return PortUtils.FindFreeTcpPort();
//#endif
}
}

View File

@@ -75,10 +75,10 @@ internal class OwinRequestMapper : IOwinRequestMapper
body,
headers,
cookies,
httpVersion
#if USE_ASPNETCORE
, await request.HttpContext.Connection.GetClientCertificateAsync()
#endif
httpVersion,
//#if USE_ASPNETCORE
await request.HttpContext.Connection.GetClientCertificateAsync()
//#endif
)
{
DateTime = DateTime.UtcNow

View File

@@ -1,112 +0,0 @@
// Copyright © WireMock.Net
//using Microsoft.Owin.Hosting;
//using Owin;
//using System;
//using System.Collections.Generic;
//using System.Threading;
//using System.Threading.Tasks;
//using JetBrains.Annotations;
//using WireMock.Logging;
//using WireMock.Owin.Mappers;
//using Stef.Validation;
//using WireMock.Services;
//using WireMock.Util;
//namespace WireMock.Owin;
//internal class OwinSelfHost : IOwinSelfHost
//{
// private readonly IWireMockMiddlewareOptions _options;
// private readonly CancellationTokenSource _cts = new();
// private readonly IWireMockLogger _logger;
// private Exception? _runningException;
// public OwinSelfHost(IWireMockMiddlewareOptions options, HostUrlOptions urlOptions)
// {
// Guard.NotNull(urlOptions);
// _options = Guard.NotNull(options);
// _logger = options.Logger ?? new WireMockConsoleLogger();
// foreach (var detail in urlOptions.GetDetails())
// {
// Urls.Add(detail.Url);
// Ports.Add(detail.Port);
// }
// }
// public bool IsStarted { get; private set; }
// public List<string> Urls { get; } = new();
// public List<int> Ports { get; } = new();
// public Exception? RunningException => _runningException;
// [PublicAPI]
// public Task StartAsync()
// {
// return Task.Run(StartServers, _cts.Token);
// }
// [PublicAPI]
// public Task StopAsync()
// {
// _cts.Cancel();
// return Task.FromResult(true);
// }
// private void StartServers()
// {
//#if NET46
// _logger.Info("Server using .net 4.6");
//#else
// _logger.Info("Server using .net 4.5.x");
//#endif
// var servers = new List<IDisposable>();
// try
// {
// var requestMapper = new OwinRequestMapper();
// var responseMapper = new OwinResponseMapper(_options);
// var matcher = new MappingMatcher(_options, new RandomizerDoubleBetween0And1());
// var guidUtils = new GuidUtils();
// Action<IAppBuilder> startup = app =>
// {
// app.Use<GlobalExceptionMiddleware>(_options, responseMapper);
// _options.PreWireMockMiddlewareInit?.Invoke(app);
// app.Use<WireMockMiddleware>(_options, requestMapper, responseMapper, matcher, guidUtils);
// _options.PostWireMockMiddlewareInit?.Invoke(app);
// };
// foreach (var url in Urls)
// {
// servers.Add(WebApp.Start(url, startup));
// }
// IsStarted = true;
// // WaitHandle is signaled when the token is cancelled,
// // which will be more efficient than Thread.Sleep in while loop
// _cts.Token.WaitHandle.WaitOne();
// }
// catch (Exception e)
// {
// // Expose exception of starting host, otherwise it's hard to be troubleshooting if keeping quiet
// // For example, WebApp.Start will fail with System.MissingMemberException if Microsoft.Owin.Host.HttpListener.dll is being located
// // https://stackoverflow.com/questions/25090211/owin-httplistener-not-located/31369857
// _runningException = e;
// _logger.Error(e.ToString());
// }
// finally
// {
// IsStarted = false;
// // Dispose all servers in finally block to make sure clean up allocated resource on error happening
// servers.ForEach(s => s.Dispose());
// }
// }
//}

View File

@@ -183,12 +183,12 @@ public class RequestMessage : IRequestMessage
ClientCertificate = clientCertificate;
//#endif
#if MIMEKIT
//#if MIMEKIT
if (TypeLoader.TryLoadStaticInstance<IMimeKitUtils>(out var mimeKitUtils) && mimeKitUtils.TryGetMimeMessage(this, out var mimeMessage))
{
BodyAsMimeMessage = mimeMessage;
}
#endif
//#endif
}
/// <inheritdoc />

View File

@@ -218,7 +218,7 @@ internal class MatcherMapper
model.ContentTypeMatcher = Map(mimePartMatcher.ContentTypeMatcher);
break;
#if PROTOBUF
//#if PROTOBUF
case IProtoBufMatcher protoBufMatcher:
protoBufMatcher.ProtoDefinition().Value(id => model.Pattern = id, texts =>
{
@@ -235,7 +235,7 @@ internal class MatcherMapper
model.ProtoBufMessageType = protoBufMatcher.MessageType;
model.ContentMatcher = Map(protoBufMatcher.Matcher);
break;
#endif
//#endif
}
afterMap?.Invoke(model);

View File

@@ -1,11 +1,11 @@
// Copyright © WireMock.Net
using System.Net;
#if OPENAPIPARSER
//#if OPENAPIPARSER
using System;
using System.Linq;
using WireMock.Net.OpenApiParser;
#endif
//#endif
namespace WireMock.Server;
@@ -13,7 +13,7 @@ public partial class WireMockServer
{
private IResponseMessage OpenApiConvertToMappings(IRequestMessage requestMessage)
{
#if OPENAPIPARSER
//#if OPENAPIPARSER
try
{
var mappingModels = new WireMockOpenApiParser().FromText(requestMessage.Body!, out var diagnostic);
@@ -24,14 +24,14 @@ public partial class WireMockServer
_settings.Logger.Error("HttpStatusCode set to {0} {1}", HttpStatusCode.BadRequest, e);
return ResponseMessageBuilder.Create(HttpStatusCode.BadRequest, e.Message);
}
#else
return ResponseMessageBuilder.Create(HttpStatusCode.BadRequest, "Not supported for .NETStandard 1.3 and .NET 4.6.x or lower.");
#endif
//#else
// return ResponseMessageBuilder.Create(HttpStatusCode.BadRequest, "Not supported for .NETStandard 1.3 and .NET 4.6.x or lower.");
//#endif
}
private IResponseMessage OpenApiSaveToMappings(IRequestMessage requestMessage)
{
#if OPENAPIPARSER
//#if OPENAPIPARSER
try
{
var mappingModels = new WireMockOpenApiParser().FromText(requestMessage.Body!, out var diagnostic);
@@ -49,8 +49,8 @@ public partial class WireMockServer
_settings.Logger.Error("HttpStatusCode set to {0} {1}", HttpStatusCode.BadRequest, e);
return ResponseMessageBuilder.Create(HttpStatusCode.BadRequest, e.Message);
}
#else
return ResponseMessageBuilder.Create(HttpStatusCode.BadRequest, "Not supported for .NETStandard 1.3 and .NET 4.6.x or lower.");
#endif
//#else
// return ResponseMessageBuilder.Create(HttpStatusCode.BadRequest, "Not supported for .NETStandard 1.3 and .NET 4.6.x or lower.");
//#endif
}
}

View File

@@ -14,6 +14,11 @@
<PackageLicenseExpression>MIT</PackageLicenseExpression>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)' == 'Debug'">
<SignAssembly>true</SignAssembly>
<AssemblyOriginatorKeyFile>../WireMock.Net/WireMock.Net.snk</AssemblyOriginatorKeyFile>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)' == 'Debug - Sonar'">
<CodeAnalysisRuleSet>../WireMock.Net/WireMock.Net.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>

View File

@@ -1,6 +1,6 @@
// Copyright © WireMock.Net
#if GRAPHQL
//#if GRAPHQL
using System;
using System.Collections.Generic;
using FluentAssertions;
@@ -233,4 +233,4 @@ public class GraphQLMatcherTests
action.Should().Throw<GraphQLSyntaxErrorException>();
}
}
#endif
//#endif

View File

@@ -1,6 +1,6 @@
// Copyright © WireMock.Net
#if PROTOBUF
//#if PROTOBUF
using System;
using System.Threading.Tasks;
using FluentAssertions;
@@ -108,4 +108,4 @@ message HelloReply {
result.Exception.Should().BeOfType<ArgumentException>();
}
}
#endif
//#endif

View File

@@ -1,6 +1,6 @@
// Copyright © WireMock.Net
#if GRAPHQL
//#if GRAPHQL
using System.Collections.Generic;
using FluentAssertions;
using GraphQL.Types;
@@ -70,4 +70,4 @@ public class RequestBuilderWithGraphQLSchemaTests
((RequestMessageGraphQLMatcher)matchers[0]).Matchers.Should().ContainItemsAssignableTo<GraphQLMatcher>();
}
}
#endif
//#endif

View File

@@ -1,6 +1,6 @@
// Copyright © WireMock.Net
#if PROTOBUF
//#if PROTOBUF
using System.Collections.Generic;
using FluentAssertions;
using WireMock.Matchers;
@@ -64,4 +64,4 @@ message HelloReply {
protoBufMatcher.Matcher.Should().BeOfType<JsonMatcher>();
}
}
#endif
//#endif

View File

@@ -1,6 +1,6 @@
// Copyright © WireMock.Net
#if GRAPHQL
//#if GRAPHQL
using System.Linq;
using FluentAssertions;
using Moq;
@@ -193,4 +193,4 @@ public class RequestMessageGraphQLMatcherTests
stringMatcherMock.Verify(m => m.IsMatch(It.IsAny<string>()), Times.Never);
}
}
#endif
//#endif

View File

@@ -1,6 +1,6 @@
// Copyright © WireMock.Net
#if !(NET452 || NET461 || NETCOREAPP3_1)
//#if !(NET452 || NET461 || NETCOREAPP3_1)
using System;
using System.Collections.Generic;
using System.Threading;
@@ -531,7 +531,7 @@ message HelloReply {
return Verifier.Verify(model);
}
#if GRAPHQL
//#if GRAPHQL
[Fact]
public Task ToMappingModel_Request_WithBodyAsGraphQLSchema_ReturnsCorrectModel()
{
@@ -562,9 +562,9 @@ message HelloReply {
// Verify
return Verifier.Verify(model);
}
#endif
//#endif
#if PROTOBUF
//#if PROTOBUF
[Fact]
public Task ToMappingModel_Request_WithBodyAsProtoBuf_ReturnsCorrectModel()
{
@@ -651,6 +651,6 @@ message HelloReply {
// Verify
return Verifier.Verify(model);
}
#endif
//#endif
}
#endif
//#endif

View File

@@ -171,7 +171,7 @@ public class MatcherMapperTests
model.XmlNamespaceMap.Should().BeEquivalentTo(xmlNamespaceMap);
}
#if GRAPHQL
//#if GRAPHQL
[Fact]
public void MatcherMapper_Map_Matcher_GraphQLMatcher()
{
@@ -199,9 +199,9 @@ public class MatcherMapperTests
model.Pattern.Should().Be(testSchema);
model.CustomScalars.Should().BeEquivalentTo(customScalars);
}
#endif
//#endif
#if PROTOBUF
//#if PROTOBUF
[Fact]
public void MatcherMapper_Map_Matcher_ProtoBufMatcher()
{
@@ -280,7 +280,7 @@ message HelloReply {
model.ContentMatcher?.Name.Should().Be("JsonMatcher");
model.ContentMatcher?.Pattern.Should().Be(jsonPattern);
}
#endif
//#endif
[Fact]
public void MatcherMapper_Map_MatcherModel_Null()
@@ -1050,7 +1050,7 @@ message HelloReply {
}
}
#if GRAPHQL
//#if GRAPHQL
[Fact]
public void MatcherMapper_Map_MatcherModel_GraphQLMatcher()
{
@@ -1083,9 +1083,9 @@ message HelloReply {
matcher.Name.Should().Be(nameof(GraphQLMatcher));
matcher.CustomScalars.Should().BeEquivalentTo(customScalars);
}
#endif
//#endif
#if PROTOBUF
//#if PROTOBUF
[Fact]
public void MatcherMapper_Map_MatcherModel_ProtoBufMatcher()
{
@@ -1132,5 +1132,5 @@ message HelloReply {
matcher.MessageType.Should().Be(messageType);
matcher.Matcher?.Value.Should().Be(jsonMatcherPattern);
}
#endif
//#endif
}