Skip to content

Commit 9e0088f

Browse files
bug #62346 [Clock] Align MockClock::sleep() behavior with NativeClock for negative values (yoeunes)
This PR was merged into the 6.4 branch. Discussion ---------- [Clock] Align MockClock::sleep() behavior with NativeClock for negative values | Q | A | ------------- | --- | Branch? | 6.4 | Bug fix? | yes | New feature? | no | Deprecations? | no | Issues | - | License | MIT This PR fixes a behavioral inconsistency between `NativeClock` and `MockClock` when handling negative sleep durations. **The Problem:** * `NativeClock::sleep(-10)`: Silently does nothing. The time does not change. * `MockClock::sleep(-10)`: **Travels backward in time** by 10 seconds. This inconsistency can lead to unreliable tests, as the mock does not accurately represent the real implementation's behavior for this edge case. **The Fix:** This fix adds a guard clause to `MockClock::sleep()` to ignore any duration less than or equal to zero, perfectly matching the behavior of `NativeClock`. **Before (The Bug):** ```php $clock = new MockClock('2000-01-01 12:00:00'); $clock->sleep(-10); // $clock->now() is '2000-01-01 11:59:50' ``` **After (The Fix):** ```php $clock = new MockClock('2000-01-01 12:00:00'); $clock->sleep(-10); // $clock->now() is '2000-01-01 12:00:00' ``` Commits ------- 87ec08d [Clock] Align MockClock::sleep() behavior with NativeClock for negative values
2 parents b0d77ad + 87ec08d commit 9e0088f

File tree

2 files changed

+14
-0
lines changed

2 files changed

+14
-0
lines changed

src/Symfony/Component/Clock/MockClock.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,10 @@ public function now(): DatePoint
5454

5555
public function sleep(float|int $seconds): void
5656
{
57+
if (0 >= $seconds) {
58+
return;
59+
}
60+
5761
$now = (float) $this->now->format('Uu') + $seconds * 1e6;
5862
$now = substr_replace(\sprintf('@%07.0F', $now), '.', -6, 0);
5963
$timezone = $this->now->getTimezone();

src/Symfony/Component/Clock/Tests/MockClockTest.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,4 +117,14 @@ public function testWithTimeZone()
117117
$this->assertNotSame($clock, $utcClock);
118118
$this->assertSame('UTC', $utcClock->now()->getTimezone()->getName());
119119
}
120+
121+
public function testSleepWithNegativeValueDoesNothing()
122+
{
123+
$initialTime = new \DateTimeImmutable('2000-01-01 12:00:00 UTC');
124+
125+
$clock = new MockClock($initialTime);
126+
$clock->sleep(-10.5);
127+
128+
$this->assertEquals($initialTime, $clock->now());
129+
}
120130
}

0 commit comments

Comments
 (0)