1
0
mirror of https://github.com/danog/psalm.git synced 2024-11-26 20:34:47 +01:00
psalm/tests/BinaryOperationTest.php

422 lines
12 KiB
PHP
Raw Normal View History

2016-12-24 00:52:34 +01:00
<?php
namespace Psalm\Tests;
use function class_exists;
use const DIRECTORY_SEPARATOR;
class BinaryOperationTest extends TestCase
2016-12-24 00:52:34 +01:00
{
2018-11-06 03:57:36 +01:00
use Traits\InvalidCodeAnalysisTestTrait;
use Traits\ValidCodeAnalysisTestTrait;
2016-12-24 00:52:34 +01:00
/**
* @return void
*/
public function testGMPOperations()
{
if (class_exists('GMP') === false) {
$this->markTestSkipped('Cannot run test, base class "GMP" does not exist!');
return;
}
$this->addFile(
'somefile.php',
'<?php
$a = gmp_init(2);
$b = gmp_init(4);
$c = $a + $b;
$d = $c + 3;
echo $d;
$f = $a / $b;
$g = $a ** $b;
$h = $a % $b;
$i = 6 + $b;
$j = 6 - $b;
$k = 6 * $b;
$l = 6 / $b;
$m = 6 ** $b;
$n = 6 % $b;
$o = $a + 6;
$p = $a - 6;
$q = $a * 6;
$r = $a / 6;
$s = $a ** 6;
$t = $a % 6;'
);
$assertions = [
'$a' => 'GMP',
'$b' => 'GMP',
'$c' => 'GMP',
'$d' => 'GMP',
'$f' => 'GMP',
'$g' => 'GMP',
'$h' => 'GMP',
'$i' => 'GMP',
'$j' => 'GMP',
'$k' => 'GMP',
'$l' => 'GMP',
'$m' => 'GMP',
'$n' => 'GMP',
'$o' => 'GMP',
'$p' => 'GMP',
'$q' => 'GMP',
'$r' => 'GMP',
'$s' => 'GMP',
'$t' => 'GMP',
];
$context = new \Psalm\Context();
$this->analyzeFile('somefile.php', $context);
$actual_vars = [];
foreach ($assertions as $var => $_) {
if (isset($context->vars_in_scope[$var])) {
$actual_vars[$var] = (string)$context->vars_in_scope[$var];
}
}
$this->assertSame($assertions, $actual_vars);
}
/**
* @return void
*/
public function testStrictTrueEquivalence()
{
$config = \Psalm\Config::getInstance();
$config->strict_binary_operands = true;
$this->addFile(
'somefile.php',
'<?php
function returnsABool(): bool {
return rand(1, 2) === 1;
}
if (returnsABool() === true) {
echo "hi!";
}'
);
$this->expectException(\Psalm\Exception\CodeException::class);
$this->expectExceptionMessage('RedundantIdentityWithTrue');
$this->analyzeFile('somefile.php', new \Psalm\Context());
}
2016-12-24 00:52:34 +01:00
/**
2019-03-01 21:55:20 +01:00
* @return iterable<string,array{string,assertions?:array<string,string>,error_levels?:string[]}>
2016-12-24 00:52:34 +01:00
*/
2018-11-06 03:57:36 +01:00
public function providerValidCodeParse()
2016-12-24 00:52:34 +01:00
{
return [
'regularAddition' => [
'<?php
2017-05-27 02:05:57 +02:00
$a = 5 + 4;',
'assertions' => [
'$a' => 'int',
],
],
'differingNumericTypesAdditionInWeakMode' => [
'<?php
2017-05-27 02:05:57 +02:00
$a = 5 + 4.1;',
'assertions' => [
'$a' => 'float',
],
],
'modulo' => [
'<?php
$a = 25 % 2;
$b = 25.4 % 2;
$c = 25 % 2.5;
$d = 25.5 % 2.5;',
'assertions' => [
'$a' => 'int',
'$b' => 'int',
'$c' => 'int',
'$d' => 'int',
],
],
'numericAddition' => [
'<?php
$a = "5";
if (is_numeric($a)) {
$b = $a + 4;
2017-05-27 02:05:57 +02:00
}',
],
'concatenation' => [
'<?php
2017-05-27 02:05:57 +02:00
$a = "Hey " . "Jude,";',
],
'concatenationWithNumberInWeakMode' => [
'<?php
2017-05-27 02:05:57 +02:00
$a = "hi" . 5;',
],
'possiblyInvalidAdditionOnBothSides' => [
'<?php
function foo(string $s) : int {
return strpos($s, "a") + strpos($s, "b");
}',
'assertions' => [],
'error_levels' => ['PossiblyFalseOperand'],
],
'bitwiseoperations' => [
'<?php
$a = 4 & 5;
$b = 2 | 3;
$c = 4 ^ 3;
$d = 1 << 2;
2018-04-17 00:19:18 +02:00
$e = 15 >> 2;
$f = "a" & "b";',
'assertions' => [
'$a' => 'int',
'$b' => 'int',
'$c' => 'int',
'$d' => 'int',
'$e' => 'int',
2018-04-17 00:19:18 +02:00
'$f' => 'string',
],
],
'booleanXor' => [
'<?php
$a = true ^ false;
$b = false ^ false;
$c = (true xor false);
$d = (false xor false);',
'assertions' => [
'$a' => 'int',
'$b' => 'int',
'$c' => 'bool',
'$d' => 'bool',
],
],
'ternaryAssignment' => [
'<?php
rand(0, 1) ? $a = 1 : $a = 2;
echo $a;',
],
'assignmentInRHS' => [
'<?php
2018-09-17 18:15:45 +02:00
$name = rand(0, 1) ? "hello" : null;
if ($name !== null || ($name = rand(0, 1) ? "hello" : null) !== null) {}',
],
'floatIncrement' => [
'<?php
$a = 1.1;
$a++;
$b = 1.1;
$b += 1;',
'assertions' => [
'$a' => 'float',
'$b' => 'float',
],
],
'exponent' => [
'<?php
$a = "x" ^ "y";
$b = 4 ^ 5;',
'assertions' => [
'$a' => 'string',
'$b' => 'int',
],
],
2019-04-13 16:11:25 +02:00
'bitwiseNot' => [
'<?php
$a = ~4;
$b = ~4.0;
$c = ~4.4;
$d = ~"a";',
'assertions' => [
'$a' => 'int',
'$b' => 'int',
'$c' => 'int',
'$d' => 'string',
],
],
'stringIncrementSuppressed' => [
'<?php
$a = "hello";
/** @psalm-suppress StringIncrement */
$a++;',
'assertions' => [
'$a' => 'string',
],
],
'nullCoalescingAssignment' => [
'<?php
function foo(?string $s): string {
$s ??= "Hello";
return $s;
Test parallelization (#4045) * Run tests in random order Being able to run tests in any order is a pre-requisite for being able to run them in parallel. * Reset type coverage between tests, fix affected tests * Reset parser and lexer between test runs and on php version change Previously lexer was reset, but parser kept the reference to the old one, and reference to the parser was kept by StatementsProvider. This resulted in order-dependent tests - if the parser was first initialized with phpVersion set to 7.4 then arrow functions worked fine, but were failing when the parser was initially constructed with settings for 7.3 This can be demonstrated on current master by upgrading to nikic/php-parser:4.9 and running: ``` vendor/bin/phpunit --no-coverage --filter="inferredArgArrowFunction" tests/ClosureTest.php ``` Now all tests using PHP 7.4 features must set the PHP version accordingly. * Marked more tests using 7.4 syntax * Reset newline-between-annotation flag between tests * Resolve real paths before passing them to checkPaths When checkPaths is called from psalm.php the paths are resolved, so we just mimicking SUT behaviour here. * Restore newline-between-annotations in DocCommentTest * Tweak Appveyor caches * Tweak TravisCI caches * Tweak CircleCI caches * Run tests in parallel Use `vendor/bin/paratest` instead of `vendor/bin/phpunit` * Use default paratest runner on Windows WrapperRunner is not supported on Windows. * TRAVIS_TAG could be empty * Restore appveyor conditional caching
2020-08-23 16:32:07 +02:00
}',
'assertions' => [],
'error_levels' => [],
'7.4',
],
'nullCoalescingArrayAssignment' => [
'<?php
/**
* @param array<string> $arr
*/
function foo(array $arr) : void {
$b = [];
foreach ($arr as $a) {
$b[0] ??= $a;
}
Test parallelization (#4045) * Run tests in random order Being able to run tests in any order is a pre-requisite for being able to run them in parallel. * Reset type coverage between tests, fix affected tests * Reset parser and lexer between test runs and on php version change Previously lexer was reset, but parser kept the reference to the old one, and reference to the parser was kept by StatementsProvider. This resulted in order-dependent tests - if the parser was first initialized with phpVersion set to 7.4 then arrow functions worked fine, but were failing when the parser was initially constructed with settings for 7.3 This can be demonstrated on current master by upgrading to nikic/php-parser:4.9 and running: ``` vendor/bin/phpunit --no-coverage --filter="inferredArgArrowFunction" tests/ClosureTest.php ``` Now all tests using PHP 7.4 features must set the PHP version accordingly. * Marked more tests using 7.4 syntax * Reset newline-between-annotation flag between tests * Resolve real paths before passing them to checkPaths When checkPaths is called from psalm.php the paths are resolved, so we just mimicking SUT behaviour here. * Restore newline-between-annotations in DocCommentTest * Tweak Appveyor caches * Tweak TravisCI caches * Tweak CircleCI caches * Run tests in parallel Use `vendor/bin/paratest` instead of `vendor/bin/phpunit` * Use default paratest runner on Windows WrapperRunner is not supported on Windows. * TRAVIS_TAG could be empty * Restore appveyor conditional caching
2020-08-23 16:32:07 +02:00
}',
'assertions' => [],
'error_levels' => [],
'7.4',
],
'addArrays' => [
'<?php
/**
* @param array{host?:string} $opts
* @return array{host:string|int}
*/
function a(array $opts): array {
return $opts + ["host" => 5];
}'
],
'addIntToZero' => [
'<?php
$tick = 0;
test($tick + 1);
$tick++;
test($tick);
/**
* @psalm-param positive-int $tickedTimes
*/
function test(int $tickedTimes): void {}'
],
];
2016-12-24 00:52:34 +01:00
}
2017-01-13 20:07:23 +01:00
/**
2019-03-01 21:55:20 +01:00
* @return iterable<string,array{string,error_message:string,2?:string[],3?:bool,4?:string}>
2017-01-13 20:07:23 +01:00
*/
2018-11-06 03:57:36 +01:00
public function providerInvalidCodeParse()
2016-12-24 00:52:34 +01:00
{
return [
'badAddition' => [
'<?php
$a = "b" + 5;',
2017-05-27 02:05:57 +02:00
'error_message' => 'InvalidOperand',
],
'differingNumericTypesAdditionInStrictMode' => [
'<?php
$a = 5 + 4.1;',
'error_message' => 'InvalidOperand',
'error_levels' => [],
2017-05-27 02:05:57 +02:00
'strict_mode' => true,
],
'concatenationWithNumberInStrictMode' => [
'<?php
$a = "hi" . 5;',
'error_message' => 'InvalidOperand',
'error_levels' => [],
2017-05-27 02:05:57 +02:00
'strict_mode' => true,
],
'addArrayToNumber' => [
'<?php
$a = [1] + 1;',
'error_message' => 'InvalidOperand',
'error_levels' => [],
2017-05-27 02:05:57 +02:00
'strict_mode' => true,
],
'additionWithClassInWeakMode' => [
'<?php
$a = "hi" + (new stdClass);',
'error_message' => 'InvalidOperand',
],
'possiblyInvalidOperand' => [
'<?php
$b = rand(0, 1) ? [] : 4;
echo $b + 5;',
'error_message' => 'PossiblyInvalidOperand',
],
'possiblyInvalidConcat' => [
'<?php
$b = rand(0, 1) ? [] : "hello";
echo $b . "goodbye";',
'error_message' => 'PossiblyInvalidOperand',
],
2018-05-05 18:59:30 +02:00
'invalidGMPOperation' => [
'<?php
$a = gmp_init(2);
$b = "a" + $a;',
2019-02-27 22:00:44 +01:00
'error_message' => 'InvalidOperand - src' . DIRECTORY_SEPARATOR . 'somefile.php:3:26 - Cannot add GMP to non-numeric type',
2018-05-05 18:59:30 +02:00
],
'stringIncrement' => [
'<?php
$a = "hello";
$a++;',
'error_message' => 'StringIncrement',
],
'falseIncrement' => [
'<?php
$a = false;
$a++;',
'error_message' => 'FalseOperand',
],
'trueIncrement' => [
'<?php
$a = true;
$a++;',
'error_message' => 'InvalidOperand',
],
'possiblyDivByZero' => [
'<?php
$a = 5 / (rand(0, 1) ? 2 : null);',
'error_message' => 'PossiblyNullOperand',
],
'invalidExponent' => [
'<?php
$a = "x" ^ 1;',
'error_message' => 'InvalidOperand',
],
'invalidBitwiseOr' => [
'<?php
$a = "x" | new stdClass;',
'error_message' => 'InvalidOperand',
],
2019-04-13 16:11:25 +02:00
'invalidBitwiseNot' => [
'<?php
$a = ~new stdClass;',
'error_message' => 'InvalidOperand',
],
'possiblyInvalidBitwiseNot' => [
'<?php
$a = ~(rand(0, 1) ? 2 : null);',
'error_message' => 'PossiblyInvalidOperand',
],
'invalidBooleanBitwiseNot' => [
'<?php
$a = ~true;',
'error_message' => 'InvalidOperand',
],
'substrImpossible' => [
'<?php
class HelloWorld
{
public function sayHello(string $s): void
{
if (substr($s, 0, 6) === "abc") {}
}
}',
'error_message' => 'TypeDoesNotContainType',
],
];
2016-12-24 00:52:34 +01:00
}
}