Skip to content

[10.x] Add ulid testing helpers#48276

Merged
taylorotwell merged 3 commits intolaravel:10.xfrom
Jasonej:ulid-testing-helpers
Sep 4, 2023
Merged

[10.x] Add ulid testing helpers#48276
taylorotwell merged 3 commits intolaravel:10.xfrom
Jasonej:ulid-testing-helpers

Conversation

@Jasonej
Copy link
Contributor

@Jasonej Jasonej commented Sep 2, 2023

This PR adds testing helpers to the generation of ULIDs to match what was introduced for UUIDs in #42619.

You can specify a ULID factory.

$ulid = Str::ulid();

Str::createUlidsUsing(fn() => $ulid);

Str::ulid() === $ulid; // true

You can freeze ULID generation which is equivalent to manually specifying a ULID factory as shown above, but doesn't require you to generate and capture a ULID first.

$ulid = Str::freezeUlids();

Str::ulid() === Str::ulid() === $ulid; // true

Str::createUlidsNormally();

When passing a closure it freezes only for the duration of that closure.

Str::freezeUlids(function ($ulid) {
    Str::ulid() === Str::ulid() === $ulid; // true
});

Str::ulid() === Str::ulid(); // false

You can also provide a sequence of ULIDs to return.

Str::createUlidsUsingSequence([
    $zeroth = Str::ulid(),
    $first = Str::ulid(),
]);

Str::ulid() === $zeroth;
Str::ulid() === $first;
Str::ulid(); // back to normally generated ULIDs.

You can skip indexes in a sequence to allow them to be normally generated.

Str::createUlidsUsingSequence([
    0 => ($zeroth = Str::ulid()),
    3 => ($third = Str::ulid()),
]);

Str::ulid() === $zeroth; // true
Str::ulid(); // normally generated
Str::ulid(); // normally generated
Str::ulid() === $third; // true

You can pass a closure to control what happens when there are no more ULIDs in the sequence.

Str::createUlidsUsingSequence([
    $zeroth = Str::ulid(),
    $first = Str::ulid(),
], fn() => throw new Exception('No more ULIDs in sequence'));

Str::ulid() === $zeroth; // true
Str::ulid() === $first; // true
Str::ulid(); // throws

This will impact skipped indexes as well though.

Str::createUlidsUsingSequence([
    0 => ($zeroth = Str::ulid()),
    3 => ($third = Str::ulid()),
], fn() => throw new Exception('No more ULIDs in sequence'));

Str::ulid() === $zeroth; // true
Str::ulid(); // throws

@Jasonej Jasonej force-pushed the ulid-testing-helpers branch from 5fdcd80 to 848ef47 Compare September 2, 2023 17:05
@taylorotwell taylorotwell merged commit c02a064 into laravel:10.x Sep 4, 2023
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