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

feat: add toBeOneOf() expectation #1290

Open
wants to merge 1 commit into
base: 3.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions src/Expectation.php
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
use Pest\Support\ExpectationPipeline;
use Pest\Support\Reflection;
use PHPUnit\Architecture\Elements\ObjectDescription;
use PHPUnit\Framework\AssertionFailedError;
use PHPUnit\Framework\ExpectationFailedException;
use ReflectionEnum;
use ReflectionMethod;
Expand Down Expand Up @@ -324,6 +325,41 @@ public function when(callable|bool $condition, callable $callback): self
return $this;
}

/**
* Asserts that only one of the given tests pass with the given expectation target.
*
* @param (\Closure(self<TValue>): (mixed|void)) ...$tests
* @return self<TValue>
*/
public function toBeOneOf(Closure ...$tests): self
{
if ($tests === []) {
return $this;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In my opinion this should throw

}

$matches = [];
$exceptions = [];

foreach ($tests as $key => $test) {
try {
$test(new Expectation($this->value));
$matches[] = $key;
} catch (AssertionFailedError) {
$exceptions[] = $key;
}
}

if (count($matches) === 1) {
return $this;
}

if (count($matches) > 1) {
throw new ExpectationFailedException('Failed asserting value matches exactly one expectation (matches: '.implode(', ', $matches).').');
Copy link

@KorvinSzanto KorvinSzanto Oct 7, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rather than outputting the keys, I'd just output a count of passes and fails for a few reasons:

  • Keys are limited to ints, or variable names due to using the splat operator rather than accepting an iterable, for example: ->toBeOneOf(thisIsTheOnlyWayToNameAnExpectation: fn($e) => ..., spaces_are_not_allowed: fn($e) => ...)
  • If you were accepting an iterable rather than using a splat, array keys aren't guaranteed to be unique
  • There could be a ton of expectations passed to this function, causing a failure to output a huge error
  • Just counting passes and failures reduces the memory overhead

You can also output the total count of assertions ran by checking the delta of Assert::getCount() before and after.

}

throw new ExpectationFailedException('Failed asserting value matches any expectations.');
}

/**
* Dynamically calls methods on the class or creates a new higher order expectation.
*
Expand Down
40 changes: 40 additions & 0 deletions tests/Features/Expect/toBeOneOf.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

use PHPUnit\Framework\ExpectationFailedException;

expect(true)->toBeTrue()->and(false)->toBeFalse();

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
expect(true)->toBeTrue()->and(false)->toBeFalse();


test('risky with no assertions', function () {
expect(1)->toBeOneOf();
})->throwsNoExceptions();

test('to be one of', function () {
expect(1)->toBeOneOf(fn ($e) => $e->toBe(1), fn ($e) => $e->toBe(2), fn ($e) => $e->toBe(3));
});

test('it does not short-circuit', function () {
$executed = 0;
expect(1)->toBeOneOf(function ($e) use (&$executed) {
$executed++;

return $e->toBe(1);
}, function ($e) use (&$executed) {
$executed++;

return $e->toBe(2);
}, function ($e) use (&$executed) {
$executed++;

return $e->toBe(3);
});

expect($executed)->toBe(3);
});

test('failure with multiple matches', function () {
expect(1)->toBeOneOf(fn ($e) => $e->toBe(1), fn ($e) => $e->toBe(1));
})->throws(ExpectationFailedException::class, 'Failed asserting value matches exactly one expectation (matches: 0, 1).');

test('failure with no matches', function () {
expect(1)->toBeOneOf(fn ($e) => $e->toBe(2), fn ($e) => $e->toBe(2));
})->throws(ExpectationFailedException::class, 'Failed asserting value matches any expectations.');