1
0
mirror of https://github.com/danog/psalm.git synced 2024-12-12 17:27:28 +01:00
psalm/tests/UnusedCodeTest.php

539 lines
16 KiB
PHP
Raw Normal View History

<?php
namespace Psalm\Tests;
use Psalm\Config;
2017-07-25 23:04:58 +02:00
use Psalm\Context;
2019-03-23 19:27:54 +01:00
use Psalm\Internal\Analyzer\FileAnalyzer;
use Psalm\Tests\Internal\Provider;
class UnusedCodeTest extends TestCase
{
2018-11-06 03:57:36 +01:00
/** @var \Psalm\Internal\Analyzer\ProjectAnalyzer */
2018-11-11 18:01:14 +01:00
protected $project_analyzer;
/**
* @return void
*/
2019-05-17 00:36:36 +02:00
public function setUp() : void
{
2018-11-06 03:57:36 +01:00
FileAnalyzer::clearCache();
Refactor scanning and analysis, introducing multithreading (#191) * Add failing test * Add visitor to soup up classlike references * Move a whole bunch of code into the visitor * Move some methods back, move onto analysis stage * Use the getAliases method everywhere * Fix refs * Fix more refs * Fix some tests * Fix more tests * Fix include tests * Shift config class finding to project checker and fix bugs * Fix a few more tests * transition test to new syntax * Remove var_dump * Delete a bunch of code and fix mutation test * Remove unnecessary visitation * Transition to better mocked out file provider, breaking some cached statement loading * Use different scheme for naming anonymous classes * Fix anonymous class issues * Refactor file/statement loading * Add specific property types * Fix mapped property assignment * Improve how we deal with traits * Fix trait checking * Pass Psalm checks * Add multi-process support * Delay console output until the end * Remove PHP 7 syntax * Update file storage with classes * Fix scanning individual files and add reflection return types * Always turn XDebug off * Add quicker method of getting method mutations * Queue return types for crawling * Interpret all strings as possible classes once we see a `get_class` call * Check invalid return types again * Fix template namespacing issues * Default to class-insensitive file names for includes * Don’t overwrite existing issues data * Add var docblocks for scanning * Add null check * Fix loading of external classes in templates * Only try to populate class when we haven’t yet seen it’s not a class * Fix trait property accessibility * Only ever improve docblock param type * Make param replacement more robust * Fix static const missing inferred type * Fix a few more tests * Register constant definitions * Fix trait aliasing * Skip constant type tests for now * Fix linting issues * Make sure caching is off for tests * Remove unnecessary return * Use emulative parser if on PHP 5.6 * Cache parser for faster first-time parse * Fix constant resolution when scanning classes * Remove test that’s beyond a practical scope * Add back --diff support * Add --help for --threads * Remove unused vars
2017-07-25 22:11:02 +02:00
$this->file_provider = new Provider\FakeFileProvider();
2018-11-11 18:01:14 +01:00
$this->project_analyzer = new \Psalm\Internal\Analyzer\ProjectAnalyzer(
new TestConfig(),
2018-11-06 03:57:36 +01:00
new \Psalm\Internal\Provider\Providers(
$this->file_provider,
new Provider\FakeParserCacheProvider()
)
Refactor scanning and analysis, introducing multithreading (#191) * Add failing test * Add visitor to soup up classlike references * Move a whole bunch of code into the visitor * Move some methods back, move onto analysis stage * Use the getAliases method everywhere * Fix refs * Fix more refs * Fix some tests * Fix more tests * Fix include tests * Shift config class finding to project checker and fix bugs * Fix a few more tests * transition test to new syntax * Remove var_dump * Delete a bunch of code and fix mutation test * Remove unnecessary visitation * Transition to better mocked out file provider, breaking some cached statement loading * Use different scheme for naming anonymous classes * Fix anonymous class issues * Refactor file/statement loading * Add specific property types * Fix mapped property assignment * Improve how we deal with traits * Fix trait checking * Pass Psalm checks * Add multi-process support * Delay console output until the end * Remove PHP 7 syntax * Update file storage with classes * Fix scanning individual files and add reflection return types * Always turn XDebug off * Add quicker method of getting method mutations * Queue return types for crawling * Interpret all strings as possible classes once we see a `get_class` call * Check invalid return types again * Fix template namespacing issues * Default to class-insensitive file names for includes * Don’t overwrite existing issues data * Add var docblocks for scanning * Add null check * Fix loading of external classes in templates * Only try to populate class when we haven’t yet seen it’s not a class * Fix trait property accessibility * Only ever improve docblock param type * Make param replacement more robust * Fix static const missing inferred type * Fix a few more tests * Register constant definitions * Fix trait aliasing * Skip constant type tests for now * Fix linting issues * Make sure caching is off for tests * Remove unnecessary return * Use emulative parser if on PHP 5.6 * Cache parser for faster first-time parse * Fix constant resolution when scanning classes * Remove test that’s beyond a practical scope * Add back --diff support * Add --help for --threads * Remove unused vars
2017-07-25 22:11:02 +02:00
);
2018-11-11 18:01:14 +01:00
$this->project_analyzer->getCodebase()->reportUnusedCode();
2019-02-07 21:27:43 +01:00
$this->project_analyzer->setPhpVersion('7.3');
}
/**
2018-11-06 03:57:36 +01:00
* @dataProvider providerValidCodeParse
2017-07-25 23:04:58 +02:00
*
* @param string $code
* @param array<string> $error_levels
*
* @return void
*/
public function testValidCode($code, array $error_levels = [])
2017-07-25 23:04:58 +02:00
{
$test_name = $this->getTestName();
if (strpos($test_name, 'SKIPPED-') !== false) {
2017-07-25 23:04:58 +02:00
$this->markTestSkipped('Skipped due to a bug.');
}
$file_path = self::$src_dir_path . 'somefile.php';
2017-07-25 23:04:58 +02:00
$this->addFile(
$file_path,
2017-07-25 23:04:58 +02:00
$code
);
foreach ($error_levels as $error_level) {
2018-11-11 18:01:14 +01:00
$this->project_analyzer->getCodebase()->config->setCustomErrorLevel($error_level, Config::REPORT_SUPPRESS);
}
$context = new Context();
$context->collect_references = true;
$this->analyzeFile($file_path, $context);
2018-11-11 18:01:14 +01:00
$this->project_analyzer->checkClassReferences();
2017-07-25 23:04:58 +02:00
}
/**
2018-11-06 03:57:36 +01:00
* @dataProvider providerInvalidCodeParse
2017-05-27 02:16:18 +02:00
*
* @param string $code
* @param string $error_message
* @param array<string> $error_levels
2017-05-27 02:16:18 +02:00
*
* @return void
*/
public function testInvalidCode($code, $error_message, $error_levels = [])
{
if (strpos($this->getTestName(), 'SKIPPED-') !== false) {
2017-07-25 23:04:58 +02:00
$this->markTestSkipped();
}
2019-02-23 22:22:39 +01:00
$this->expectException(\Psalm\Exception\CodeException::class);
$this->expectExceptionMessageRegExp('/\b' . preg_quote($error_message, '/') . '\b/');
$file_path = self::$src_dir_path . 'somefile.php';
foreach ($error_levels as $error_level) {
2018-11-11 18:01:14 +01:00
$this->project_analyzer->getCodebase()->config->setCustomErrorLevel($error_level, Config::REPORT_SUPPRESS);
}
Refactor scanning and analysis, introducing multithreading (#191) * Add failing test * Add visitor to soup up classlike references * Move a whole bunch of code into the visitor * Move some methods back, move onto analysis stage * Use the getAliases method everywhere * Fix refs * Fix more refs * Fix some tests * Fix more tests * Fix include tests * Shift config class finding to project checker and fix bugs * Fix a few more tests * transition test to new syntax * Remove var_dump * Delete a bunch of code and fix mutation test * Remove unnecessary visitation * Transition to better mocked out file provider, breaking some cached statement loading * Use different scheme for naming anonymous classes * Fix anonymous class issues * Refactor file/statement loading * Add specific property types * Fix mapped property assignment * Improve how we deal with traits * Fix trait checking * Pass Psalm checks * Add multi-process support * Delay console output until the end * Remove PHP 7 syntax * Update file storage with classes * Fix scanning individual files and add reflection return types * Always turn XDebug off * Add quicker method of getting method mutations * Queue return types for crawling * Interpret all strings as possible classes once we see a `get_class` call * Check invalid return types again * Fix template namespacing issues * Default to class-insensitive file names for includes * Don’t overwrite existing issues data * Add var docblocks for scanning * Add null check * Fix loading of external classes in templates * Only try to populate class when we haven’t yet seen it’s not a class * Fix trait property accessibility * Only ever improve docblock param type * Make param replacement more robust * Fix static const missing inferred type * Fix a few more tests * Register constant definitions * Fix trait aliasing * Skip constant type tests for now * Fix linting issues * Make sure caching is off for tests * Remove unnecessary return * Use emulative parser if on PHP 5.6 * Cache parser for faster first-time parse * Fix constant resolution when scanning classes * Remove test that’s beyond a practical scope * Add back --diff support * Add --help for --threads * Remove unused vars
2017-07-25 22:11:02 +02:00
$this->addFile(
$file_path,
Refactor scanning and analysis, introducing multithreading (#191) * Add failing test * Add visitor to soup up classlike references * Move a whole bunch of code into the visitor * Move some methods back, move onto analysis stage * Use the getAliases method everywhere * Fix refs * Fix more refs * Fix some tests * Fix more tests * Fix include tests * Shift config class finding to project checker and fix bugs * Fix a few more tests * transition test to new syntax * Remove var_dump * Delete a bunch of code and fix mutation test * Remove unnecessary visitation * Transition to better mocked out file provider, breaking some cached statement loading * Use different scheme for naming anonymous classes * Fix anonymous class issues * Refactor file/statement loading * Add specific property types * Fix mapped property assignment * Improve how we deal with traits * Fix trait checking * Pass Psalm checks * Add multi-process support * Delay console output until the end * Remove PHP 7 syntax * Update file storage with classes * Fix scanning individual files and add reflection return types * Always turn XDebug off * Add quicker method of getting method mutations * Queue return types for crawling * Interpret all strings as possible classes once we see a `get_class` call * Check invalid return types again * Fix template namespacing issues * Default to class-insensitive file names for includes * Don’t overwrite existing issues data * Add var docblocks for scanning * Add null check * Fix loading of external classes in templates * Only try to populate class when we haven’t yet seen it’s not a class * Fix trait property accessibility * Only ever improve docblock param type * Make param replacement more robust * Fix static const missing inferred type * Fix a few more tests * Register constant definitions * Fix trait aliasing * Skip constant type tests for now * Fix linting issues * Make sure caching is off for tests * Remove unnecessary return * Use emulative parser if on PHP 5.6 * Cache parser for faster first-time parse * Fix constant resolution when scanning classes * Remove test that’s beyond a practical scope * Add back --diff support * Add --help for --threads * Remove unused vars
2017-07-25 22:11:02 +02:00
$code
);
$context = new Context();
$context->collect_references = true;
$this->analyzeFile($file_path, $context);
2018-11-11 18:01:14 +01:00
$this->project_analyzer->checkClassReferences();
}
/**
2019-02-23 22:22:39 +01:00
* @return array<string, array{string}>
*/
2018-11-06 03:57:36 +01:00
public function providerValidCodeParse()
{
return [
'magicCall' => [
'<?php
class A {
/** @var string */
private $value = "default";
/** @param string[] $args */
public function __call(string $name, array $args) {
if (count($args) == 1) {
$this->modify($name, $args[0]);
}
}
2018-01-11 21:50:45 +01:00
private function modify(string $name, string $value): void {
call_user_func([$this, "modify" . $name], $value);
}
2018-01-11 21:50:45 +01:00
public function modifyFoo(string $value): void {
$this->value = $value;
}
public function getFoo() : string {
return $this->value;
}
}
$m = new A();
$m->foo("value");
$m->modifyFoo("value2");
echo $m->getFoo();',
],
'usedTraitMethodWithExplicitCall' => [
2017-12-29 17:26:28 +01:00
'<?php
class A {
2018-01-11 21:50:45 +01:00
public function foo(): void {
2017-12-29 17:26:28 +01:00
echo "parent method";
}
}
trait T {
2018-01-11 21:50:45 +01:00
public function foo(): void {
2017-12-29 17:26:28 +01:00
echo "trait method";
}
}
class B extends A {
use T;
}
(new A)->foo();
(new B)->foo();',
],
'usedInterfaceMethod' => [
'<?php
interface I {
2018-01-11 21:50:45 +01:00
public function foo(): void;
}
class A implements I {
2018-01-11 21:50:45 +01:00
public function foo(): void {}
}
(new A)->foo();',
],
'constructorIsUsed' => [
'<?php
class A {
public function __construct() {
$this->foo();
}
private function foo() : void {}
}
$a = new A();
echo (bool) $a;',
],
'everythingUsed' => [
'<?php
interface I {
public function foo();
}
class B implements I {
public function foo() : void {}
}
class A
{
/**
* @var I
*/
private $i;
/**
* @param int[] $as
*/
public function __construct(array $as) {
$this->i = new B();
foreach ($as as $a) {
$this->a($a, 1);
}
}
private function a(int $a, int $b): self
{
$this->v($a, $b);
$this->i->foo();
return $this;
}
private function v(int $a, int $b): void
{
if ($a + $b > 0) {
throw new \RuntimeException("");
}
}
}
new A([1, 2, 3]);',
],
'unusedParamWithUnderscore' => [
'<?php
function foo(int $_) : void {}
foo(4);',
],
'unusedParamWithUnusedPrefix' => [
'<?php
function foo(int $unusedArg) : void {}
foo(4);',
],
'possiblyUnusedParamWithUnderscore' => [
'<?php
class A {
public static function foo(int $_ = null) : void {}
}
A::foo();',
],
'possiblyUnusedParamWithUnusedPrefix' => [
'<?php
class A {
public static function foo(int $unusedArg = null) : void {}
}
A::foo();',
],
'usedClass' => [
'<?php
class A { }
new A();',
],
'usedTraitMethodWithImplicitCall' => [
'<?php
class A {
public function foo() : void {}
}
trait T {
public function foo() : void {}
}
class B extends A {
use T;
}
function takesA(A $a) : void {
$a->foo();
}
2019-03-23 19:27:54 +01:00
takesA(new B);',
],
'usedMethodInTryCatch' => [
'<?php
class A {
protected function getC() : C {
return new C;
}
}
class C {
public function foo() : void {}
}
class B extends A {
public function bar() : void {
$c = $this->getC();
foreach ([1, 2, 3] as $_) {
try {
$c->foo();
} catch (Exception $e) {}
}
}
}
(new B)->bar();',
],
'suppressPrivateUnusedMethod' => [
'<?php
class A {
/**
* @psalm-suppress UnusedMethod
* @return void
*/
private function foo() {}
}
new A();',
],
'abstractMethodImplementerCoveredByParentCall' => [
'<?php
abstract class Foobar {
public function doIt(): void {
$this->inner();
}
abstract protected function inner(): void;
}
class MyFooBar extends Foobar {
protected function inner(): void {
// Do nothing
}
}
$myFooBar = new MyFooBar();
$myFooBar->doIt();',
],
2019-04-17 21:45:40 +02:00
'methodUsedAsCallable' => [
'<?php
class C {
public static function foo() : void {}
}
function takesCallable(callable $c) : void {
$c();
}
takesCallable([C::class, "foo"]);',
],
'propertyAndMethodOverriddenDownstream' => [
'<?php
class A {
/** @var string */
public $foo = "hello";
public function bar() : void {}
}
class B extends A {
/** @var string */
public $foo = "goodbye";
public function bar() : void {}
}
function foo(A $a) : void {
echo $a->foo;
$a->bar();
}
foo(new B());',
],
'protectedPropertyOverriddenDownstream' => [
'<?php
class C {
/** @var int */
protected $foo = 1;
public function bar() : int {
return $this->foo;
}
}
class D extends C {
protected $foo = 2;
}
(new D)->bar();'
],
];
}
/**
2019-02-23 22:22:39 +01:00
* @return array<string,array{string,error_message:string}>
*/
2018-11-06 03:57:36 +01:00
public function providerInvalidCodeParse()
{
return [
'unusedClass' => [
'<?php
class A { }',
2017-05-27 02:05:57 +02:00
'error_message' => 'UnusedClass',
],
'publicUnusedMethod' => [
'<?php
class A {
/** @return void */
public function foo() {}
}
new A();',
2017-05-27 02:05:57 +02:00
'error_message' => 'PossiblyUnusedMethod',
],
'possiblyUnusedParam' => [
'<?php
class A {
/** @return void */
public function foo(int $i) {}
}
(new A)->foo(4);',
2019-05-13 22:01:41 +02:00
'error_message' => 'PossiblyUnusedParam - src' . DIRECTORY_SEPARATOR
. 'somefile.php:4:49 - Param #1 is never referenced in this method',
],
'unusedParam' => [
'<?php
function foo(int $i) {}
foo(4);',
'error_message' => 'UnusedParam',
],
'possiblyUnusedProperty' => [
'<?php
class A {
/** @var string */
public $foo = "hello";
}
$a = new A();',
'error_message' => 'PossiblyUnusedProperty',
'error_levels' => ['UnusedVariable'],
],
'unusedProperty' => [
'<?php
class A {
/** @var string */
private $foo = "hello";
}
$a = new A();',
'error_message' => 'UnusedProperty',
'error_levels' => ['UnusedVariable'],
],
'privateUnusedMethod' => [
'<?php
class A {
/** @return void */
private function foo() {}
}
new A();',
2017-05-27 02:05:57 +02:00
'error_message' => 'UnusedMethod',
],
2017-12-30 16:54:01 +01:00
'unevaluatedCode' => [
'<?php
2018-01-11 21:50:45 +01:00
function foo(): void {
2017-12-30 16:54:01 +01:00
return;
$a = "foo";
}',
'error_message' => 'UnevaluatedCode',
],
'unusedTraitMethodInParent' => [
'<?php
class A {
public function foo() : void {}
}
trait T {
public function foo() : void {}
public function bar() : void {}
}
class B extends A {
use T;
}
function takesA(A $a) : void {
$a->foo();
}
takesA(new B);',
'error_message' => 'PossiblyUnusedMethod',
],
'unusedRecursivelyUsedMethod' => [
'<?php
class C {
public function foo() : void {
if (rand(0, 1)) {
$this->foo();
}
}
public function bar() : void {}
}
(new C)->bar();',
'error_message' => 'PossiblyUnusedMethod',
],
'unusedRecursivelyUsedStaticMethod' => [
'<?php
class C {
public static function foo() : void {
if (rand(0, 1)) {
self::foo();
}
}
public function bar() : void {}
}
(new C)->bar();',
'error_message' => 'PossiblyUnusedMethod',
],
'propertyOverriddenDownstreamAndNotUsed' => [
'<?php
class A {
/** @var string */
public $foo = "hello";
}
class B extends A {
/** @var string */
public $foo = "goodbye";
}
new B();',
'error_message' => 'PossiblyUnusedProperty',
],
];
}
}