Skip to content

Commit

Permalink
[10.x] Provide testing hooks (#47228)
Browse files Browse the repository at this point in the history
* Provide testing hooks

* Update Sleep.php

* Update Sleep.php

---------

Co-authored-by: Taylor Otwell <[email protected]>
  • Loading branch information
timacdonald and taylorotwell authored May 26, 2023
1 parent 4774fef commit b44d9dc
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/Illuminate/Support/Sleep.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,13 @@ class Sleep
{
use Macroable;

/**
* The fake sleep callbacks.
*
* @var array
*/
public static $fakeSleepCallbacks = [];

/**
* The total duration to sleep.
*
Expand Down Expand Up @@ -252,6 +259,10 @@ public function __destruct()
if (static::$fake) {
static::$sequence[] = $this->duration;

foreach (static::$fakeSleepCallbacks as $callback) {
$callback($this->duration);
}

return;
}

Expand Down Expand Up @@ -305,6 +316,7 @@ public static function fake($value = true)
static::$fake = $value;

static::$sequence = [];
static::$fakeSleepCallbacks = [];
}

/**
Expand Down Expand Up @@ -435,4 +447,15 @@ public function unless($condition)
{
return $this->when(! value($condition, $this));
}

/**
* Specify a callback that should be invoked when faking sleep within a test.
*
* @param callable $callback
* @return void
*/
public static function whenFakingSleep($callback)
{
static::$fakeSleepCallbacks[] = $callback;
}
}
36 changes: 36 additions & 0 deletions tests/Support/SleepTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Illuminate\Tests\Support;

use Carbon\CarbonInterval;
use Exception;
use Illuminate\Support\Carbon;
use Illuminate\Support\Sleep;
use PHPUnit\Framework\AssertionFailedError;
Expand Down Expand Up @@ -501,4 +502,39 @@ public function testItCanSleepConditionallyWhen()
Sleep::for(1)->second()->unless(fn () => false);
Sleep::assertSlept(fn () => true, 4);
}

public function testItCanRegisterCallbacksToRunInTests()
{
$countA = 0;
$countB = 0;
Sleep::fake();
Sleep::whenFakingSleep(function ($duration) use (&$countA) {
$countA += $duration->totalMilliseconds;
});
Sleep::whenFakingSleep(function ($duration) use (&$countB) {
$countB += $duration->totalMilliseconds;
});

Sleep::for(1)->millisecond();
Sleep::for(2)->millisecond();

Sleep::assertSequence([
Sleep::for(1)->millisecond(),
Sleep::for(2)->millisecond(),
]);

$this->assertSame(3, $countA);
$this->assertSame(3, $countB);
}

public function testItDoesntRunCallbacksWhenNotFaking()
{
Sleep::whenFakingSleep(function () {
throw new Exception('Should not run without faking.');
});

Sleep::for(1)->millisecond();

$this->assertTrue(true);
}
}

0 comments on commit b44d9dc

Please sign in to comment.