Skip to content

Add custom sleep handler for testability - #557

Merged
Sammyjo20 merged 2 commits into
saloonphp:v4from
mariomka:config-sleep-handler
Oct 2, 2026
Merged

Sammyjo20 merged 2 commits into
saloonphp:v4from
mariomka:config-sleep-handler

Conversation

@mariomka

Copy link
Copy Markdown
Contributor

Saloon sleeps with a raw usleep() in two places: the retry loop in SendsRequests and DelayMiddleware. These run even when requests are mocked with MockClient, so any test covering retries or delays pays real wall-clock time and there's no seam to avoid it. In one of our apps, a test file went from 9.5s to 4.4s once sleeps were skipped.

This PR adds a sleep seam on Config, mirroring Config::setSenderResolver():

// In a test bootstrap for skipping all sleeps
Config::sleepUsing(fn () => null);

// Restore the default behaviour
Config::sleepUsing(null);

Both call sites now route through Config::sleep($microseconds), which falls back to usleep() when no handler is set.

As a follow-up, the Laravel plugin could bind the handler to Illuminate\Support\Sleep so Sleep::fake() works out of the box, happy to open that PR too.

I have considered some alternatives but I went with a closure on Config because it mirrors setSenderResolver(), but happy to rework it if you prefer another shape:

  • A Sleeper contract resolved like the sender, for an object-based seam instead of a closure.
  • A standalone helper (e.g. Saloon\Helpers\Sleep::for($microseconds)) with a static test override, keeping Config untouched.

@Sammyjo20

Copy link
Copy Markdown
Member

Amazing PR @mariomka thank you!

@Sammyjo20
Sammyjo20 merged commit 31d077c into saloonphp:v4 Oct 2, 2026
18 checks passed
@mariomka

mariomka commented Oct 3, 2026

Copy link
Copy Markdown
Contributor Author

@Sammyjo20 would you be interested in a follow鈥憉p PR for the Laravel plugin to use Illuminate\Support\Sleep for sleeping, so that Sleep::fake() works out of the box?

@Sammyjo20

Copy link
Copy Markdown
Member

Absolutely @mariomka yes please! Does this mean that anyone using the Laravel plugin will automatically get access to Sleep::fake() etc?

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.

2 participants