Skip to content

Commit

Permalink
Respect AutoAdvance for GetTimestamp in FakeTimeProvider (#5783)
Browse files Browse the repository at this point in the history
* Respect AutoAdvance for GetTimestamp in FakeTimeProvider
  • Loading branch information
amadeuszl authored Jan 10, 2025
1 parent e98606a commit 045aaab
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,8 @@ public override long GetTimestamp()
#pragma warning disable S3236 // Caller information arguments should not be provided explicitly
Debug.Assert(TimestampFrequency == TimeSpan.TicksPerSecond, "Assuming frequency equals ticks per second");
#pragma warning restore S3236 // Caller information arguments should not be provided explicitly
return _now.Ticks;

return GetUtcNow().Ticks;
}

/// <inheritdoc />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,63 @@ public void Constructor_DefaultInitialization_SetsExpectedValues()
Assert.Equal(timestamp, timestamp2);
}

[Fact]
public void GetTimestamp_WithoutAutoAdvance_DoesNotAdvance()
{
var nowOffset = new DateTimeOffset(2000, 1, 1, 0, 0, 0, 0, TimeSpan.Zero);
var timeProvider = new FakeTimeProvider(nowOffset);

var timestamp1 = timeProvider.GetTimestamp();
var timestamp2 = timeProvider.GetTimestamp();

Assert.Equal(nowOffset, new DateTimeOffset(timestamp1, TimeSpan.Zero));
Assert.Equal(nowOffset, new DateTimeOffset(timestamp2, TimeSpan.Zero));
}

[Fact]
public void GetTimestamp_WithAutoAdvance_AdvancesProperly()
{
var msToElapse = 100;
var nowOffset = new DateTimeOffset(2000, 1, 1, 0, 0, 0, 0, TimeSpan.Zero);
var timeProvider = new FakeTimeProvider(nowOffset)
{
AutoAdvanceAmount = TimeSpan.FromMilliseconds(msToElapse)
};

var timestamp1 = timeProvider.GetTimestamp();
var timestamp2 = timeProvider.GetTimestamp();

Assert.Equal(nowOffset, new DateTimeOffset(timestamp1, TimeSpan.Zero));
Assert.Equal(nowOffset.AddMilliseconds(msToElapse), new DateTimeOffset(timestamp2, TimeSpan.Zero));
}

[Fact]
public void GetElapsedTime_CallsGetTimestamp()
{
var timeProvider = new FakeTimeProvider();
var st = timeProvider.GetTimestamp();
timeProvider.Advance(TimeSpan.FromSeconds(1));
var t = timeProvider.GetElapsedTime(st);

Assert.Equal(TimeSpan.FromSeconds(1), t);
}

[Fact]
public void GetElapsedTime_WithAutoAdvance_AdvancesProperly()
{
var timeProvider = new FakeTimeProvider
{
AutoAdvanceAmount = TimeSpan.FromSeconds(1)
};

var st = timeProvider.GetTimestamp();
var elapsedTime = timeProvider.GetElapsedTime(st);
var elapsedTime2 = timeProvider.GetElapsedTime(st);

Assert.Equal(TimeSpan.FromSeconds(1), elapsedTime);
Assert.Equal(TimeSpan.FromSeconds(2), elapsedTime2);
}

[Fact]
public void Constructor_InitializesWithCustomDateTimeOffset_AdvancesCorrectly()
{
Expand Down

0 comments on commit 045aaab

Please sign in to comment.