Skip to content

Commit

Permalink
AssertTypeSpecifyingExtensionHelper: rootExpr with unknown variable t…
Browse files Browse the repository at this point in the history
…o avoid always-true false positives (#197)
  • Loading branch information
janedbal authored and ondrejmirtes committed Oct 9, 2023
1 parent 614acc1 commit 70ecacc
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
13 changes: 12 additions & 1 deletion src/Type/PHPUnit/Assert/AssertTypeSpecifyingExtensionHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
use ReflectionObject;
use function array_key_exists;
use function count;
use function in_array;
use function strlen;
use function strpos;
use function substr;
Expand All @@ -33,6 +34,12 @@ class AssertTypeSpecifyingExtensionHelper
/** @var Closure[] */
private static $resolvers;

/**
* Those can specify types correctly, but would produce always-true issue
* @var string[]
*/
private static $resolversCausingAlwaysTrue = ['ContainsOnlyInstancesOf', 'ContainsEquals', 'Contains'];

/**
* @param Arg[] $args
*/
Expand Down Expand Up @@ -87,10 +94,14 @@ public static function specifyTypes(
if ($expression === null) {
return new SpecifiedTypes([], []);
}

$bypassAlwaysTrueIssue = in_array(self::trimName($name), self::$resolversCausingAlwaysTrue, true);

return $typeSpecifier->specifyTypesInCondition(
$scope,
$expression,
TypeSpecifierContext::createTruthy()
TypeSpecifierContext::createTruthy(),
$bypassAlwaysTrueIssue ? new Expr\BinaryOp\BooleanAnd($expression, new Expr\Variable('nonsense')) : null
);
}

Expand Down
7 changes: 7 additions & 0 deletions tests/Rules/PHPUnit/data/assert-same.php
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,13 @@ public function testOther()
$foo->assertSame();
}

public function testAssertContains()
{
$this->assertContains('not in the list', new \ArrayObject([1]));
$this->assertContainsEquals('not in the list', new \ArrayObject([1]));
$this->assertNotContains('not in the list', new \ArrayObject([1]));
}

public function testStaticMethodReturnWithSameTypeIsNotReported()
{
$this->assertSame(self::createSomething('foo'), self::createSomething('foo'));
Expand Down

0 comments on commit 70ecacc

Please sign in to comment.