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

Fix failure description of count constraint for generators #4271

Closed
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
15 changes: 13 additions & 2 deletions src/Framework/Constraint/Count.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,15 @@ class Count extends Constraint
*/
private $expectedCount;

/**
* Cache the actual count value for use in the failure
* description for things like generators that cannot be
* cloned and can only be iterated once
*
* @var null|int
*/
private $actualCount;

public function __construct(int $expected)
{
$this->expectedCount = $expected;
Expand All @@ -41,7 +50,9 @@ public function toString(): string
*/
protected function matches($other): bool
{
return $this->expectedCount === $this->getCountOf($other);
$this->actualCount = $this->getCountOf($other);

return $this->expectedCount === $this->actualCount;
}

/**
Expand Down Expand Up @@ -116,7 +127,7 @@ protected function failureDescription($other): string
{
return \sprintf(
'actual size %d matches expected size %d',
$this->getCountOf($other),
$this->actualCount ?? 0,
$this->expectedCount
);
}
Expand Down
26 changes: 26 additions & 0 deletions tests/unit/Framework/Constraint/CountTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,32 @@ public function testCountEvaluateReturnsNullWithNonCountableAndNonTraversableOth
<<<EOF
Failed asserting that actual size 0 matches expected size 1.

EOF
,
TestFailure::exceptionToString($e)
);
}
}

public function testCachedActualCountFailureDescriptionForGenerators(): void
{
// Generators can only be iterated over once and cannot be cloned.
// Validate actual count is cached for failure message
$generator = static function () {
yield 1;

yield 2;

yield 3;
};

try {
$this->assertCount(4, $generator());
} catch (ExpectationFailedException $e) {
$this->assertEquals(
<<<EOF
Failed asserting that actual size 3 matches expected size 4.

EOF
,
TestFailure::exceptionToString($e)
Expand Down