1
0
mirror of https://github.com/danog/psalm.git synced 2024-12-11 08:49:52 +01:00
psalm/tests/JsonOutputTest.php

154 lines
5.2 KiB
PHP
Raw Normal View History

2016-12-08 04:38:57 +01:00
<?php
2016-12-08 04:38:57 +01:00
namespace Psalm\Tests;
2019-03-23 19:27:54 +01:00
use Psalm\Context;
2018-11-06 03:57:36 +01:00
use Psalm\Internal\Analyzer\ProjectAnalyzer;
use Psalm\Internal\Provider\FakeFileProvider;
2021-12-03 20:11:20 +01:00
use Psalm\Internal\Provider\Providers;
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
use Psalm\Internal\RuntimeCaches;
2016-12-08 04:38:57 +01:00
use Psalm\IssueBuffer;
2021-12-03 20:11:20 +01:00
use Psalm\Report;
use Psalm\Report\ReportOptions;
2021-12-04 21:55:53 +01:00
use Psalm\Tests\Internal\Provider\FakeParserCacheProvider;
2021-06-08 04:55:21 +02:00
use function substr;
2016-12-08 04:38:57 +01:00
class JsonOutputTest extends TestCase
2016-12-08 04:38:57 +01:00
{
public function setUp(): void
2016-12-08 04:38:57 +01:00
{
2018-11-06 03:57:36 +01:00
// `TestCase::setUp()` creates its own ProjectAnalyzer and Config instance, but we don't want to do that in this
// case, so don't run a `parent::setUp()` call here.
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
RuntimeCaches::clearAll();
$this->file_provider = new FakeFileProvider();
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
$config = new TestConfig();
$config->throw_exception = false;
2021-12-03 20:11:20 +01:00
$stdout_report_options = new ReportOptions();
$stdout_report_options->format = Report::TYPE_JSON;
2018-11-11 18:01:14 +01:00
$this->project_analyzer = new ProjectAnalyzer(
$config,
2021-12-03 20:11:20 +01:00
new Providers(
$this->file_provider,
2022-12-18 17:15:15 +01:00
new FakeParserCacheProvider(),
),
2022-12-18 17:15:15 +01:00
$stdout_report_options,
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();
2016-12-08 04:38:57 +01:00
}
2017-01-13 20:07:23 +01:00
/**
* @dataProvider providerTestJsonOutputErrors
2017-01-13 20:07:23 +01:00
*/
2022-02-11 00:35:50 +01:00
public function testJsonOutputErrors(
string $code,
int $error_count,
string $message,
int $line_number,
string $error
): void {
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('somefile.php', $code);
$this->analyzeFile('somefile.php', new Context());
$all_issue_data = IssueBuffer::getIssuesData()['somefile.php'];
$this->assertCount($error_count, $all_issue_data);
$issue_data = $all_issue_data[0];
2016-12-08 22:23:07 +01:00
2020-02-17 00:24:40 +01:00
$this->assertSame('somefile.php', $issue_data->file_path);
$this->assertSame('error', $issue_data->severity);
$this->assertSame($message, $issue_data->message);
$this->assertSame($line_number, $issue_data->line_from);
2016-12-08 22:23:07 +01:00
$this->assertSame(
$error,
2022-12-18 17:15:15 +01:00
substr($code, $issue_data->from, $issue_data->to - $issue_data->from),
);
}
/**
* @return array<string,array{code:string,error_count:int,message:string,line:int,error:string}>
*/
public function providerTestJsonOutputErrors(): array
{
return [
'returnTypeError' => [
'code' => '<?php
2018-01-11 21:50:45 +01:00
function fooFoo(int $a): string {
return $a + 1;
}',
'error_count' => 2,
'message' => "The inferred type 'int' does not match the declared return type 'string' for fooFoo",
'line' => 3,
'error' => '$a + 1',
],
'undefinedVar' => [
'code' => '<?php
2018-01-11 21:50:45 +01:00
function fooFoo(int $a): int {
return $b + 1;
}',
'error_count' => 5,
'message' => 'Cannot find referenced variable $b',
'line' => 3,
2017-05-27 02:05:57 +02:00
'error' => '$b',
],
'unknownParamClass' => [
'code' => '<?php
2018-01-11 21:50:45 +01:00
function fooFoo(Badger\Bodger $a): Badger\Bodger {
return $a;
}',
'error_count' => 3,
'message' => 'Class, interface or enum named Badger\\Bodger does not exist',
'line' => 2,
2017-05-27 02:05:57 +02:00
'error' => 'Badger\\Bodger',
],
'missingReturnType' => [
'code' => '<?php
function fooFoo() {
return "hello";
}',
'error_count' => 1,
'message' => "Method fooFoo does not have a return type, expecting 'hello'",
'line' => 2,
2018-10-07 02:11:19 +02:00
'error' => 'fooFoo',
],
'wrongMultilineReturnType' => [
'code' => '<?php
/**
* @return int
*/
function fooFoo() {
return "hello";
}',
'error_count' => 2,
'message' => "The inferred type ''hello'' does not match the declared return type 'int' for fooFoo",
'line' => 6,
'error' => '"hello"',
2017-05-27 02:05:57 +02:00
],
'assertCancelsMixedAssignment' => [
'code' => '<?php
$a = $_GET["hello"];
2022-09-10 13:06:17 +02:00
assert(is_string($a));
if (is_string($a)) {}',
2022-10-16 14:39:34 +02:00
'error_count' => 1,
2022-09-10 13:06:17 +02:00
'message' => 'Docblock-defined type string for $a is always string',
'line' => 4,
2022-09-10 13:06:17 +02:00
'error' => 'is_string($a)',
],
'singleIssueForTypeDifference' => [
'code' => '<?php
function fooFoo(?string $a, ?string $b): void {
if ($a || $b) {
if ($a || $b) {}
}
}',
'error_count' => 1,
'message' => 'Operand of type non-falsy-string is always truthy',
'line' => 4,
'error' => '$b',
],
];
}
2016-12-08 04:38:57 +01:00
}