diff --git a/src/Servers/Kestrel/shared/test/MockSystemClock.cs b/src/Servers/Kestrel/shared/test/MockSystemClock.cs index 5ec904aad0..61a3d6e123 100644 --- a/src/Servers/Kestrel/shared/test/MockSystemClock.cs +++ b/src/Servers/Kestrel/shared/test/MockSystemClock.cs @@ -9,7 +9,16 @@ namespace Microsoft.AspNetCore.Testing { public class MockSystemClock : ISystemClock { - private long _utcNowTicks = DateTimeOffset.UtcNow.Ticks; + private static Random _random = new Random(); + + private long _utcNowTicks; + + public MockSystemClock() + { + // Use a random DateTimeOffset to ensure tests that incorrectly use the current DateTimeOffset fail always instead of only rarely. + // Pick a date between the min DateTimeOffset and a day before the max DateTimeOffset so there's room to advance the clock. + _utcNowTicks = NextLong(DateTimeOffset.MinValue.Ticks, DateTimeOffset.MaxValue.Ticks - TimeSpan.FromDays(1).Ticks); + } public DateTimeOffset UtcNow { @@ -29,5 +38,10 @@ namespace Microsoft.AspNetCore.Testing public DateTimeOffset UtcNowUnsynchronized => UtcNow; public int UtcNowCalled { get; private set; } + + private long NextLong(long minValue, long maxValue) + { + return (long)(_random.NextDouble() * (maxValue - minValue) + minValue); + } } } diff --git a/src/Servers/Kestrel/test/InMemory.FunctionalTests/RequestTests.cs b/src/Servers/Kestrel/test/InMemory.FunctionalTests/RequestTests.cs index a89f552696..b2be3c2db8 100644 --- a/src/Servers/Kestrel/test/InMemory.FunctionalTests/RequestTests.cs +++ b/src/Servers/Kestrel/test/InMemory.FunctionalTests/RequestTests.cs @@ -130,7 +130,6 @@ namespace Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests [Fact] public async Task CanUpgradeRequestWithConnectionKeepAliveUpgradeHeader() { - var testContext = new TestServiceContext(); var dataRead = false; using (var server = new TestServer(async context => @@ -154,7 +153,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.InMemory.FunctionalTests await connection.ReceiveEnd( "HTTP/1.1 101 Switching Protocols", "Connection: Upgrade", - $"Date: {testContext.DateHeaderValue}", + $"Date: {server.Context.DateHeaderValue}", "", ""); }