Skip to content

[Tests] RotatingStreamWriterTests — DateTime.UtcNow used twice per test, midnight-boundary flake #737

@Christophe-Rogiers

Description

@Christophe-Rogiers

Severity: Info
File: tests/Servy.Core.UnitTests/IO/RotatingStreamWriterTests.cs lines 272, 572, 629, 647

Description:
Four tests take the form:

// … rotation happens here …
Assert.Contains(DateTime.UtcNow.ToString("yyyyMMdd"), rotatedFiles[0]);

The timestamp on the assertion is the value of DateTime.UtcNow at assertion time, not the value at the time the rotated filename was computed by production code. When a test run crosses a UTC midnight boundary between the rotation step and the assertion step, these tests will fail even though the production code is behaving correctly — the expected date simply differs from the one used by the SUT by one day.

This is a low-probability-but-deterministic flake: it surfaces only around 00:00 UTC and makes the test red in a way that is hard to reproduce later when the developer looks at the CI log in the morning.

Suggested fix:
Capture the expected date once at the start of each test (and, where possible, inject a clock into RotatingStreamWriter so tests can pin the time):

var expectedDate = DateTime.UtcNow.ToString("yyyyMMdd");
// … rotation happens here …
Assert.Contains(expectedDate, rotatedFiles[0]);

A further improvement is to extract an IClock / Func<DateTime> seam into RotatingStreamWriter so tests can freeze time. The same seam would close the handful of DateTime.UtcNow call sites that currently appear in production code without a test double.

Metadata

Metadata

Assignees

Labels

testsChanges to test code and coverage

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions