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

Conversation

dshafik
Copy link

@dshafik dshafik commented Oct 6, 2024

What:

  • Bug Fix
  • New Feature

Description:

Adds a toBeOneOf expectation that allows you to ensure that a value matches only one of a set of assertions. This is complimentary to #1286.

@dshafik dshafik force-pushed the feature/toBeOneOf branch from 8319e3d to d87bd72 Compare October 6, 2024 03:58
@dshafik dshafik force-pushed the feature/toBeOneOf branch from d87bd72 to ae40c0f Compare October 6, 2024 05:15
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

}

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.


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();

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