Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/WireMock.Net.Abstractions/IRequestMessage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public interface IRequestMessage
string? ProxyUrl { get; set; }

/// <summary>
/// Gets the DateTime.
/// The DateTime when this request was done.
/// </summary>
DateTime DateTime { get; }

Expand Down
2 changes: 1 addition & 1 deletion src/WireMock.Net.Abstractions/IResponseMessage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public interface IResponseMessage
object? StatusCode { get; set; }

/// <summary>
/// Gets the DateTime.
/// The DateTime when this response was sent.
/// </summary>
DateTime DateTime { get; }

Expand Down
14 changes: 14 additions & 0 deletions src/WireMock.Net.Minimal/Extensions/HttpContextExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// Copyright © WireMock.Net

using System.Diagnostics.CodeAnalysis;
using Microsoft.AspNetCore.Http;

namespace WireMock.Extensions;

internal static class HttpContextExtensions
{
internal static bool TryGet<T>(this HttpContext httpContext, [NotNullWhen(true)] out T? value)
{
return httpContext.Items.TryGetValue(nameof(T), out value);
}
}
4 changes: 2 additions & 2 deletions src/WireMock.Net.Minimal/Owin/Mappers/OwinRequestMapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ namespace WireMock.Owin.Mappers;
/// <summary>
/// OwinRequestMapper
/// </summary>
internal class OwinRequestMapper : IOwinRequestMapper
internal class OwinRequestMapper(IDateTimeUtils dateTimeUtils) : IOwinRequestMapper
{
/// <inheritdoc />
public async Task<RequestMessage> MapAsync(HttpContext context, IWireMockMiddlewareOptions options)
Expand Down Expand Up @@ -72,7 +72,7 @@ public async Task<RequestMessage> MapAsync(HttpContext context, IWireMockMiddlew
await request.HttpContext.Connection.GetClientCertificateAsync()
)
{
DateTime = DateTime.UtcNow
DateTime = dateTimeUtils.UtcNow
};
}

Expand Down
8 changes: 7 additions & 1 deletion src/WireMock.Net.Minimal/Owin/WireMockMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,12 @@ private async Task InvokeInternalAsync(HttpContext ctx)
}
finally
{
// Set the DateTime from the Response to the current DateTime
if (response is ResponseMessage responseMessage)
{
responseMessage.DateTime = dateTimeUtils.UtcNow;
}

logger.LogRequestAndResponse(logRequest, request, response, result.Match, result.Partial, activity);

try
Expand Down Expand Up @@ -255,4 +261,4 @@ private void UpdateScenarioState(IMapping mapping)
scenario.Finished = mapping.NextState == null;
});
}
}
}
6 changes: 3 additions & 3 deletions src/WireMock.Net.Minimal/Owin/WireMockMiddlewareLogger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -73,20 +73,20 @@ public void LogLogEntry(LogEntry entry, bool addRequest)
var logEntries = options.LogEntries.ToList();

foreach (var logEntry in logEntries
.OrderBy(le => le.RequestMessage?.DateTime ?? le.ResponseMessage?.DateTime)
.OrderBy(le => le.RequestMessage?.DateTime)
.Take(logEntries.Count - options.MaxRequestLogCount.Value))
{
TryRemoveLogEntry(logEntry);
}
}

// In case RequestLogExpirationDuration has a value greater than 0, try to delete existing request logs based on the date.
// In case RequestLogExpirationDuration has a value greater than 0, try to delete existing request logs based on the RequestMessage date.
if (options.RequestLogExpirationDuration is > 0)
{
var logEntries = options.LogEntries.ToList();

var checkTime = dateTimeUtils.UtcNow.AddHours(-options.RequestLogExpirationDuration.Value);
foreach (var logEntry in logEntries.Where(le => le.RequestMessage?.DateTime < checkTime || le.ResponseMessage?.DateTime < checkTime))
foreach (var logEntry in logEntries.Where(le => le.RequestMessage?.DateTime < checkTime))
{
TryRemoveLogEntry(logEntry);
}
Expand Down
2 changes: 1 addition & 1 deletion src/WireMock.Net.Minimal/ResponseBuilders/Response.cs
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ public static IResponseBuilder Create(ResponseMessage? responseMessage = null)
{
var message = responseMessage ?? new ResponseMessage
{
DateTime = DateTime.UtcNow // We set it here to the current time.
DateTime = DateTime.UtcNow // Initially, this is set to the current time, but will be updated to the real time once the response has been sent.
};

return new Response(message);
Expand Down
1 change: 0 additions & 1 deletion src/WireMock.Net.Minimal/ResponseMessage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

// 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.Linq;
using Stef.Validation;
using WireMock.ResponseBuilders;
using WireMock.Types;
Expand Down
29 changes: 29 additions & 0 deletions test/WireMock.Net.Tests/Facts/RunOnDockerFact.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// Copyright © WireMock.Net
#if NET6_0_OR_GREATER
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using WireMock.Net.Testcontainers.Utils;

namespace WireMock.Net.Tests.Facts;

[ExcludeFromCodeCoverage]
public sealed class RunOnDockerFact : FactAttribute
{
public RunOnDockerFact(
[CallerFilePath] string? sourceFilePath = null,
[CallerLineNumber] int sourceLineNumber = -1) : base(sourceFilePath, sourceLineNumber)
{

OSPlatform currentPlatform;
try
{
currentPlatform = TestcontainersUtils.GetImageOSAsync.Value.Result;
}
catch
{
Skip = $"Only run test when Docker is installed.";
}
}
}
#endif
14 changes: 13 additions & 1 deletion test/WireMock.Net.Tests/Facts/RunOnDockerPlatformFact.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,19 @@ public RunOnDockerPlatformFact(
[CallerFilePath] string? sourceFilePath = null,
[CallerLineNumber] int sourceLineNumber = -1) : base(sourceFilePath, sourceLineNumber)
{
if (TestcontainersUtils.GetImageOSAsync.Value.Result != OSPlatform.Create(platform))

OSPlatform currentPlatform;
try
{
currentPlatform = TestcontainersUtils.GetImageOSAsync.Value.Result;
}
catch
{
Skip = $"Only run test when Docker is installed.";
return;
}

if (currentPlatform != OSPlatform.Create(platform))
{
Skip = $"Only run test when Docker OS Platform {platform} is used.";
}
Expand Down
11 changes: 10 additions & 1 deletion test/WireMock.Net.Tests/Owin/WireMockMiddlewareTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,15 @@ public WireMockMiddlewareTests()
[Fact]
public async Task WireMockMiddleware_Invoke_NoMatch()
{
// Arrange
var inititalDateTime = new DateTime(2027, 1, 1, 0, 0, 0, DateTimeKind.Utc);
var responseDateTime = new DateTime(2027, 1, 1, 0, 0, 42, DateTimeKind.Utc);

_dateTimeUtilsMock.Reset();
_dateTimeUtilsMock.SetupSequence(d => d.UtcNow)
.Returns(inititalDateTime)
.Returns(responseDateTime);

// Act
await _sut.Invoke(_contextMock.Object);

Expand All @@ -115,7 +124,7 @@ public async Task WireMockMiddleware_Invoke_NoMatch()
Expression<Func<ResponseMessage, bool>> match = r =>
(int)r.StatusCode! == 404 &&
((StatusModel)r.BodyData!.BodyAsJson!).Status == "No matching mapping found" &&
r.DateTime == UtcNow;
r.DateTime == responseDateTime;
_responseMapperMock.Verify(m => m.MapAsync(It.Is(match), It.IsAny<HttpResponse>()), Times.Once);
}

Expand Down
6 changes: 3 additions & 3 deletions test/WireMock.Net.Tests/Testcontainers/TestcontainersTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public class TestcontainersTests(ITestOutputHelper testOutputHelper)
TimestampFormat = "yyy-MM-dd HH:mm:ss.fff"
});

[Fact]
[RunOnDockerFact]
public async Task WireMockContainer_Build_And_StartAsync_and_StopAsync()
{
// Act
Expand Down Expand Up @@ -57,7 +57,7 @@ public async Task WireMockContainer_Build_WithNetwork_And_StartAsync_and_StopAsy
await StopAsync(wireMockContainer);
}

[Fact]
[RunOnDockerFact]
public async Task WireMockContainer_Build_WithImage_And_StartAsync_and_StopAsync()
{
// Arrange
Expand All @@ -83,7 +83,7 @@ public async Task WireMockContainer_Build_WithImage_And_StartAsync_and_StopAsync
await StopAsync(wireMockContainer);
}

[Fact]
[RunOnDockerFact]
public async Task WireMockContainer_Build_WithImageAsText_And_StartAsync_and_StopAsync()
{
// Arrange
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
using Microsoft.Extensions.Logging;
using WireMock.Constants;
using WireMock.Net.Testcontainers;
using WireMock.Net.Tests.Facts;
using WireMock.Util;

namespace WireMock.Net.Tests.Testcontainers;
Expand All @@ -25,7 +26,7 @@ public class TestcontainersTestsGrpc(ITestOutputHelper testOutputHelper)
TimestampFormat = "yyy-MM-dd HH:mm:ss.fff"
});

[Fact]
[RunOnDockerFact]
public async Task WireMockContainer_Build_Grpc_TestPortsAndUrls1()
{
// Arrange
Expand Down Expand Up @@ -82,7 +83,7 @@ public async Task WireMockContainer_Build_Grpc_TestPortsAndUrls1()
}
}

[Fact]
[RunOnDockerFact]
public async Task WireMockContainer_Build_Grpc_TestPortsAndUrls2()
{
// Arrange
Expand Down Expand Up @@ -136,7 +137,7 @@ public async Task WireMockContainer_Build_Grpc_TestPortsAndUrls2()
}
}

[Fact]
[RunOnDockerFact]
public async Task WireMockContainer_Build_Grpc_ProtoDefinitionFromJson_UsingGrpcGeneratedClient()
{
var wireMockContainer = await Given_WireMockContainerIsStartedForHttpAndGrpcAsync();
Expand All @@ -150,7 +151,7 @@ public async Task WireMockContainer_Build_Grpc_ProtoDefinitionFromJson_UsingGrpc
await StopAsync(wireMockContainer);
}

[Fact]
[RunOnDockerFact]
public async Task WireMockContainer_Build_Grpc_ProtoDefinitionAtServerLevel_UsingGrpcGeneratedClient()
{
var wireMockContainer = await Given_WireMockContainerWithProtoDefinitionAtServerLevelIsStartedForHttpAndGrpcAsync();
Expand All @@ -164,7 +165,7 @@ public async Task WireMockContainer_Build_Grpc_ProtoDefinitionAtServerLevel_Usin
await StopAsync(wireMockContainer);
}

[Fact]
[RunOnDockerFact]
public async Task WireMockContainer_Build_Grpc_ProtoDefinitionAtServerLevel_UsingGrpcGeneratedClient_AndWithWatchStaticMappings()
{
var wireMockContainer = await Given_WireMockContainerWithProtoDefinitionAtServerLevelWithWatchStaticMappingsIsStartedForHttpAndGrpcAsync();
Expand Down
1 change: 1 addition & 0 deletions test/WireMock.Net.Tests/WireMockServer.Proxy.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

namespace WireMock.Net.Tests;

[Collection(nameof(WireMockServerProxyTests))]
public class WireMockServerProxyTests
{
private readonly CancellationToken _ct = TestContext.Current.CancellationToken;
Expand Down Expand Up @@ -388,7 +389,7 @@

// Assert
var receivedRequest = serverForProxyForwarding.LogEntries.First().RequestMessage;
receivedRequest.BodyData.BodyAsString.Should().Be("stringContent");

Check warning on line 392 in test/WireMock.Net.Tests/WireMockServer.Proxy.cs

View workflow job for this annotation

GitHub Actions / Run Tests on Linux

Dereference of a possibly null reference.

Check warning on line 392 in test/WireMock.Net.Tests/WireMockServer.Proxy.cs

View workflow job for this annotation

GitHub Actions / Run Tests on Linux

Dereference of a possibly null reference.

Check warning on line 392 in test/WireMock.Net.Tests/WireMockServer.Proxy.cs

View workflow job for this annotation

GitHub Actions / Run Tests on Windows

Dereference of a possibly null reference.

Check warning on line 392 in test/WireMock.Net.Tests/WireMockServer.Proxy.cs

View workflow job for this annotation

GitHub Actions / Run Tests on Windows

Dereference of a possibly null reference.
receivedRequest.Headers.Should().ContainKey("Content-Type");
receivedRequest.Headers["Content-Type"].First().Should().Contain("text/plain");
receivedRequest.Headers.Should().ContainKey("bbb");
Expand Down Expand Up @@ -440,7 +441,7 @@
(await result.Content.ReadAsStringAsync(cancellationToken)).Should().Be("BASIC test-A");

var receivedRequest = serverForProxyForwarding.LogEntries.First().RequestMessage;
receivedRequest.Headers!["Authorization"].ToString().Should().Be("BASIC test-A");

Check warning on line 444 in test/WireMock.Net.Tests/WireMockServer.Proxy.cs

View workflow job for this annotation

GitHub Actions / Run Tests on Linux

Dereference of a possibly null reference.

Check warning on line 444 in test/WireMock.Net.Tests/WireMockServer.Proxy.cs

View workflow job for this annotation

GitHub Actions / Run Tests on Windows

Dereference of a possibly null reference.

server.Mappings.Should().HaveCount(2);
var authorizationRequestMessageHeaderMatcher = ((Request)server.Mappings.Single(m => !m.IsAdminInterface).RequestMatcher)
Expand Down Expand Up @@ -658,7 +659,7 @@

// Assert
var receivedRequest = serverForProxyForwarding.LogEntries.First().RequestMessage;
receivedRequest.BodyData.BodyAsString.Should().Be("");

Check warning on line 662 in test/WireMock.Net.Tests/WireMockServer.Proxy.cs

View workflow job for this annotation

GitHub Actions / Run Tests on Linux

Dereference of a possibly null reference.

Check warning on line 662 in test/WireMock.Net.Tests/WireMockServer.Proxy.cs

View workflow job for this annotation

GitHub Actions / Run Tests on Linux

Dereference of a possibly null reference.

Check warning on line 662 in test/WireMock.Net.Tests/WireMockServer.Proxy.cs

View workflow job for this annotation

GitHub Actions / Run Tests on Windows

Dereference of a possibly null reference.

Check warning on line 662 in test/WireMock.Net.Tests/WireMockServer.Proxy.cs

View workflow job for this annotation

GitHub Actions / Run Tests on Windows

Dereference of a possibly null reference.
receivedRequest.Headers.Should().ContainKey("Content-Type");
receivedRequest.Headers["Content-Type"].First().Should().Contain("text/plain");
}
Expand Down Expand Up @@ -760,7 +761,7 @@

// then
var receivedRequest = serverForProxyForwarding.LogEntries.First().RequestMessage;
receivedRequest.Cookies.Should().NotBeNull();

Check warning on line 764 in test/WireMock.Net.Tests/WireMockServer.Proxy.cs

View workflow job for this annotation

GitHub Actions / Run Tests on Linux

Dereference of a possibly null reference.

Check warning on line 764 in test/WireMock.Net.Tests/WireMockServer.Proxy.cs

View workflow job for this annotation

GitHub Actions / Run Tests on Windows

Dereference of a possibly null reference.
receivedRequest.Cookies.Should().ContainKey("name").And.ContainValue("value");
}

Expand Down
4 changes: 1 addition & 3 deletions test/WireMock.Net.Tests/WireMockServer.Proxy2.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,4 @@ public async Task WireMockServer_ProxyAndRecordSettings_ShouldProxy()
server.Dispose();
serverAsProxy.Dispose();
}
}


}
Loading