1
0
mirror of https://github.com/danog/psalm.git synced 2024-11-30 04:39:00 +01:00
psalm/tests/DocumentationTest.php

297 lines
9.0 KiB
PHP
Raw Normal View History

<?php
namespace Psalm\Tests;
2019-07-05 22:24:00 +02:00
use function array_keys;
use function count;
use const DIRECTORY_SEPARATOR;
use const LIBXML_NONET;
2019-07-05 22:24:00 +02:00
use function dirname;
use function explode;
use function file_exists;
use function file_get_contents;
use function implode;
use function preg_quote;
use Psalm\Config;
use Psalm\Context;
use Psalm\Tests\Internal\Provider;
use function sort;
use function strpos;
2019-07-05 22:24:00 +02:00
use function substr;
use function trim;
2020-03-19 17:42:41 +01:00
use function glob;
use function str_replace;
use function array_shift;
use DOMDocument;
use DOMXPath;
use DOMAttr;
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;
use function array_filter;
use function var_export;
class DocumentationTest 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 array<string, array<int, string>>
*/
private static function getCodeBlocksFromDocs(): array
{
2020-03-19 17:32:49 +01:00
$issues_dir = dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'docs' . DIRECTORY_SEPARATOR . 'running_psalm' . DIRECTORY_SEPARATOR . 'issues';
2020-03-19 17:32:49 +01:00
if (!file_exists($issues_dir)) {
throw new \UnexpectedValueException('docs not found');
}
$issue_code = [];
2020-03-19 17:32:49 +01:00
foreach (glob($issues_dir . '/*.md') as $file_path) {
$file_contents = file_get_contents($file_path);
2020-03-19 17:32:49 +01:00
$file_lines = explode("\n", $file_contents);
2020-03-19 17:32:49 +01:00
$current_issue = str_replace('# ', '', array_shift($file_lines));
2020-03-19 17:32:49 +01:00
for ($i = 0, $j = count($file_lines); $i < $j; ++$i) {
$current_line = $file_lines[$i];
2020-03-19 17:32:49 +01:00
if (substr($current_line, 0, 6) === '```php' && $current_issue) {
$current_block = '';
++$i;
2020-03-19 17:32:49 +01:00
do {
$current_block .= $file_lines[$i] . "\n";
++$i;
} while (substr($file_lines[$i], 0, 3) !== '```' && $i < $j);
$issue_code[$current_issue][] = trim($current_block);
continue 2;
}
}
}
return $issue_code;
}
2019-05-17 00:36:36 +02:00
public function setUp() : void
{
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 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()
)
);
2019-02-07 21:27:43 +01:00
2020-09-01 04:59:47 +02:00
$this->project_analyzer->setPhpVersion('8.0');
}
public function testAllIssuesCoveredInConfigSchema(): void
{
$all_issues = \Psalm\Config\IssueHandler::getAllIssueTypes();
$all_issues[] = 'PluginIssue'; // not an ordinary issue
sort($all_issues);
$schema = new DOMDocument();
$schema->load(__DIR__ . '/../config.xsd', LIBXML_NONET);
$xpath = new DOMXPath($schema);
$xpath->registerNamespace('xs', 'http://www.w3.org/2001/XMLSchema');
/** @var iterable<mixed, DOMAttr> $handlers */
$handlers = $xpath->query('//xs:complexType[@name="IssueHandlersType"]/xs:choice/xs:element/@name');
$handler_types = [];
foreach ($handlers as $handler) {
$handler_types[] = $handler->value;
}
sort($handler_types);
$this->assertSame(implode("\n", $all_issues), implode("\n", $handler_types));
}
public function testAllIssuesCovered(): void
{
2019-05-03 21:29:44 +02:00
$all_issues = \Psalm\Config\IssueHandler::getAllIssueTypes();
$all_issues[] = 'ParseError';
$all_issues[] = 'PluginIssue';
sort($all_issues);
$code_blocks = self::getCodeBlocksFromDocs();
// these cannot have code
$code_blocks['UnrecognizedExpression'] = true;
$code_blocks['UnrecognizedStatement'] = true;
$code_blocks['PluginIssue'] = true;
$code_blocks['TaintedInput'] = true;
$code_blocks['TaintedCustom'] = true;
$documented_issues = array_keys($code_blocks);
sort($documented_issues);
$this->assertSame(implode("\n", $all_issues), implode("\n", $documented_issues));
}
/**
2018-11-06 03:57:36 +01:00
* @dataProvider providerInvalidCodeParse
* @small
*
* @param string $code
* @param string $error_message
* @param array<string> $error_levels
* @param bool $check_references
*
*/
public function testInvalidCode($code, $error_message, $error_levels = [], $check_references = false): void
{
if (strpos($this->getTestName(), 'SKIPPED-') !== false) {
$this->markTestSkipped();
}
2018-02-04 00:52:35 +01:00
if ($check_references) {
2018-11-11 18:01:14 +01:00
$this->project_analyzer->getCodebase()->reportUnusedCode();
2019-08-18 20:27:50 +02:00
$this->project_analyzer->trackUnusedSuppressions();
2018-02-04 00:52:35 +01:00
}
$is_taint_test = strpos($error_message, 'Tainted') !== false;
$is_array_offset_test = strpos($error_message, 'ArrayOffset') && strpos($error_message, 'PossiblyUndefined') !== false;
$this->project_analyzer->getConfig()->ensure_array_string_offsets_exist = $is_array_offset_test;
$this->project_analyzer->getConfig()->ensure_array_int_offsets_exist = $is_array_offset_test;
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);
}
2019-02-23 22:22:39 +01:00
$this->expectException(\Psalm\Exception\CodeException::class);
$this->expectExceptionMessageRegExp('/\b' . preg_quote($error_message, '/') . '\b/');
$codebase = $this->project_analyzer->getCodebase();
$codebase->config->visitPreloadedStubFiles($codebase);
$file_path = self::$src_dir_path . 'somefile.php';
$this->addFile($file_path, $code);
if ($is_taint_test) {
$this->project_analyzer->trackTaintedInputs();
}
$this->analyzeFile($file_path, new Context());
if ($check_references) {
$this->project_analyzer->consolidateAnalyzedData();
}
}
/**
2019-02-23 22:22:39 +01:00
* @return array<string,array{string,string,string[],bool}>
*/
public function providerInvalidCodeParse(): array
{
$invalid_code_data = [];
foreach (self::getCodeBlocksFromDocs() as $issue_name => $blocks) {
switch ($issue_name) {
case 'MissingThrowsDocblock':
continue 2;
case 'UncaughtThrowInGlobalScope':
continue 2;
case 'InvalidStringClass':
continue 2;
case 'ForbiddenEcho':
continue 2;
case 'PluginClass':
continue 2;
case 'RedundantIdentityWithTrue':
continue 2;
2020-10-04 05:22:26 +02:00
case 'TraitMethodSignatureMismatch':
continue 2;
case 'InvalidFalsableReturnType':
$ignored_issues = ['FalsableReturnStatement'];
break;
case 'InvalidNullableReturnType':
$ignored_issues = ['NullableReturnStatement'];
break;
case 'InvalidReturnType':
$ignored_issues = ['InvalidReturnStatement'];
break;
case 'MixedInferredReturnType':
$ignored_issues = ['MixedReturnStatement'];
break;
case 'MixedStringOffsetAssignment':
$ignored_issues = ['MixedAssignment'];
break;
2018-05-08 22:34:08 +02:00
case 'ParadoxicalCondition':
$ignored_issues = ['MissingParamType'];
break;
case 'UnusedClass':
case 'UnusedMethod':
$ignored_issues = ['UnusedVariable'];
break;
default:
$ignored_issues = [];
}
$invalid_code_data[$issue_name] = [
2020-03-21 00:15:06 +01:00
$blocks[0],
$issue_name,
$ignored_issues,
strpos($issue_name, 'Unused') !== false
|| strpos($issue_name, 'Unevaluated') !== false
|| strpos($issue_name, 'Unnecessary') !== false,
];
}
return $invalid_code_data;
}
public function testShortcodesAreUnique(): void
{
$all_issues = \Psalm\Config\IssueHandler::getAllIssueTypes();
$all_shortcodes = [];
foreach ($all_issues as $issue_type) {
$issue_class = '\\Psalm\\Issue\\' . $issue_type;
/** @var int $shortcode */
$shortcode = $issue_class::SHORTCODE;
$all_shortcodes[$shortcode][] = $issue_type;
}
$duplicate_shortcodes = array_filter(
$all_shortcodes,
function ($issues): bool {
return count($issues) > 1;
}
);
$this->assertEquals(
[],
$duplicate_shortcodes,
"Duplicate shortcodes found: \n" . var_export($duplicate_shortcodes, true)
);
}
}