Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[10.x] Provide testing hooks #47228

Merged
merged 3 commits into from May 26, 2023
Merged

Conversation

timacdonald
Copy link
Member

This PR allows developers to register callbacks to execute when sleeping in tests.

Given the following implementation:

$timeout = now()->addMinute();

do {
    if (Work:attempt()) {
        return;
    }

    Sleep::for(100)->milliseconds();
} while (now()->isAfter($timeout));

When we "fake" sleeping in our tests, the loop will likely do millions of loops, as it doesn't actually pause the code. To test this code we need to be able to progress the now() value.

Introducing Sleep::whenFakingSleep($callback);

$this->freezeTime();
Sleep::fake();
Sleep::whenFakingSleep(fn (Interval $duration) => $this->travel(
    $duration->totalMilliseconds
)->milliseconds());

// run test code.

Sleep::assertSlept();

This solution is inspired by @michaeldyrynda's real-world use case.

@taylorotwell taylorotwell merged commit b44d9dc into laravel:10.x May 26, 2023
16 checks passed
@timacdonald timacdonald deleted the sleep-hook branch September 13, 2023 06:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants