From 1d36e239213dc63732c65f82fabb91657a60eb5b Mon Sep 17 00:00:00 2001 From: Tim MacDonald Date: Sat, 20 Jul 2024 00:14:13 +1000 Subject: [PATCH] Allow microsecond travel (#52190) --- .../Foundation/Testing/Wormhole.php | 24 +++++++++++++++++++ tests/Foundation/Testing/WormholeTest.php | 14 +++++++++++ 2 files changed, 38 insertions(+) diff --git a/src/Illuminate/Foundation/Testing/Wormhole.php b/src/Illuminate/Foundation/Testing/Wormhole.php index 54fe0fa0bb4c..beac013ab34c 100644 --- a/src/Illuminate/Foundation/Testing/Wormhole.php +++ b/src/Illuminate/Foundation/Testing/Wormhole.php @@ -24,6 +24,30 @@ public function __construct($value) $this->value = $value; } + /** + * Travel forward the given number of microseconds. + * + * @param callable|null $callback + * @return mixed + */ + public function microsecond($callback = null) + { + return $this->microseconds($callback); + } + + /** + * Travel forward the given number of microseconds. + * + * @param callable|null $callback + * @return mixed + */ + public function microseconds($callback = null) + { + Carbon::setTestNow(Carbon::now()->addMicroseconds($this->value)); + + return $this->handleCallback($callback); + } + /** * Travel forward the given number of milliseconds. * diff --git a/tests/Foundation/Testing/WormholeTest.php b/tests/Foundation/Testing/WormholeTest.php index e6fbfa13edcf..17f286d7e377 100644 --- a/tests/Foundation/Testing/WormholeTest.php +++ b/tests/Foundation/Testing/WormholeTest.php @@ -46,4 +46,18 @@ public function testCarbonImmutableCompatibility() // Restore the default Date Factory... Date::useDefault(); } + + public function testItCanTravelByMicroseconds() + { + Date::use(CarbonImmutable::class); + Date::setTestNow(Date::parse('2000-01-01 00:00:00')->startOfSecond()); + + (new Wormhole(1))->microsecond(); + $this->assertSame('2000-01-01 00:00:00.000001', Date::now()->format('Y-m-d H:i:s.u')); + + (new Wormhole(5))->microseconds(); + $this->assertSame('2000-01-01 00:00:00.000006', Date::now()->format('Y-m-d H:i:s.u')); + + Date::useDefault(); + } }