AbstractFixerTestCase.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. <?php
  2. declare(strict_types=1);
  3. /*
  4. * This file is part of PHP CS Fixer.
  5. *
  6. * (c) Fabien Potencier <fabien@symfony.com>
  7. * Dariusz Rumiński <dariusz.ruminski@gmail.com>
  8. *
  9. * This source file is subject to the MIT license that is bundled
  10. * with this source code in the file LICENSE.
  11. */
  12. namespace PhpCsFixer\Tests\Test;
  13. use PhpCsFixer\AbstractFixer;
  14. use PhpCsFixer\AbstractProxyFixer;
  15. use PhpCsFixer\Fixer\ConfigurableFixerInterface;
  16. use PhpCsFixer\Fixer\DeprecatedFixerInterface;
  17. use PhpCsFixer\Fixer\Whitespace\SingleBlankLineAtEofFixer;
  18. use PhpCsFixer\FixerConfiguration\FixerOptionInterface;
  19. use PhpCsFixer\FixerDefinition\CodeSampleInterface;
  20. use PhpCsFixer\FixerDefinition\FileSpecificCodeSampleInterface;
  21. use PhpCsFixer\FixerDefinition\VersionSpecificCodeSampleInterface;
  22. use PhpCsFixer\Linter\CachingLinter;
  23. use PhpCsFixer\Linter\Linter;
  24. use PhpCsFixer\Linter\LinterInterface;
  25. use PhpCsFixer\Linter\ProcessLinter;
  26. use PhpCsFixer\PhpunitConstraintIsIdenticalString\Constraint\IsIdenticalString;
  27. use PhpCsFixer\Preg;
  28. use PhpCsFixer\StdinFileInfo;
  29. use PhpCsFixer\Tests\Test\Assert\AssertTokensTrait;
  30. use PhpCsFixer\Tests\TestCase;
  31. use PhpCsFixer\Tokenizer\Token;
  32. use PhpCsFixer\Tokenizer\Tokens;
  33. /**
  34. * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
  35. *
  36. * @internal
  37. */
  38. abstract class AbstractFixerTestCase extends TestCase
  39. {
  40. use AssertTokensTrait;
  41. /**
  42. * @var null|LinterInterface
  43. */
  44. protected $linter;
  45. /**
  46. * @var null|AbstractFixer
  47. */
  48. protected $fixer;
  49. /**
  50. * do not modify this structure without prior discussion.
  51. *
  52. * @var array<string, array<string, bool>>
  53. */
  54. private array $allowedRequiredOptions = [
  55. 'header_comment' => ['header' => true],
  56. ];
  57. /**
  58. * do not modify this structure without prior discussion.
  59. *
  60. * @var array<string,bool>
  61. */
  62. private array $allowedFixersWithoutDefaultCodeSample = [
  63. 'general_phpdoc_annotation_remove' => true,
  64. 'general_phpdoc_tag_rename' => true,
  65. ];
  66. protected function setUp(): void
  67. {
  68. parent::setUp();
  69. $this->linter = $this->getLinter();
  70. $this->fixer = $this->createFixer();
  71. }
  72. protected function tearDown(): void
  73. {
  74. parent::tearDown();
  75. $this->linter = null;
  76. $this->fixer = null;
  77. }
  78. final public function testIsRisky(): void
  79. {
  80. if ($this->fixer->isRisky()) {
  81. self::assertValidDescription($this->fixer->getName(), 'risky description', $this->fixer->getDefinition()->getRiskyDescription());
  82. } else {
  83. self::assertNull($this->fixer->getDefinition()->getRiskyDescription(), sprintf('[%s] Fixer is not risky so no description of it expected.', $this->fixer->getName()));
  84. }
  85. if ($this->fixer instanceof AbstractProxyFixer) {
  86. return;
  87. }
  88. $reflection = new \ReflectionMethod($this->fixer, 'isRisky');
  89. // If fixer is not risky then the method `isRisky` from `AbstractFixer` must be used
  90. self::assertSame(
  91. !$this->fixer->isRisky(),
  92. AbstractFixer::class === $reflection->getDeclaringClass()->getName()
  93. );
  94. }
  95. final public function testFixerDefinitions(): void
  96. {
  97. $fixerName = $this->fixer->getName();
  98. $definition = $this->fixer->getDefinition();
  99. $fixerIsConfigurable = $this->fixer instanceof ConfigurableFixerInterface;
  100. self::assertValidDescription($fixerName, 'summary', $definition->getSummary());
  101. if (null !== $definition->getDescription()) {
  102. self::assertValidDescription($fixerName, 'description', $definition->getDescription());
  103. }
  104. $samples = $definition->getCodeSamples();
  105. self::assertNotEmpty($samples, sprintf('[%s] Code samples are required.', $fixerName));
  106. $configSamplesProvided = [];
  107. $dummyFileInfo = new StdinFileInfo();
  108. foreach ($samples as $sampleCounter => $sample) {
  109. self::assertInstanceOf(CodeSampleInterface::class, $sample, sprintf('[%s] Sample #%d', $fixerName, $sampleCounter));
  110. self::assertIsInt($sampleCounter);
  111. $code = $sample->getCode();
  112. self::assertNotEmpty($code, sprintf('[%s] Sample #%d', $fixerName, $sampleCounter));
  113. self::assertStringStartsNotWith("\n", $code, sprintf('[%s] Sample #%d must not start with linebreak', $fixerName, $sampleCounter));
  114. if (!$this->fixer instanceof SingleBlankLineAtEofFixer) {
  115. self::assertStringEndsWith("\n", $code, sprintf('[%s] Sample #%d must end with linebreak', $fixerName, $sampleCounter));
  116. }
  117. $config = $sample->getConfiguration();
  118. if (null !== $config) {
  119. self::assertTrue($fixerIsConfigurable, sprintf('[%s] Sample #%d has configuration, but the fixer is not configurable.', $fixerName, $sampleCounter));
  120. $configSamplesProvided[$sampleCounter] = $config;
  121. } elseif ($fixerIsConfigurable) {
  122. if (!$sample instanceof VersionSpecificCodeSampleInterface) {
  123. self::assertArrayNotHasKey('default', $configSamplesProvided, sprintf('[%s] Multiple non-versioned samples with default configuration.', $fixerName));
  124. }
  125. $configSamplesProvided['default'] = true;
  126. }
  127. if ($sample instanceof VersionSpecificCodeSampleInterface) {
  128. $supportedPhpVersions = [7_04_00, 8_00_00, 8_01_00, 8_02_00];
  129. $hasSuitableSupportedVersion = false;
  130. foreach ($supportedPhpVersions as $version) {
  131. if ($sample->isSuitableFor($version)) {
  132. $hasSuitableSupportedVersion = true;
  133. }
  134. }
  135. self::assertTrue($hasSuitableSupportedVersion, 'Version specific code sample must be suitable for at least 1 supported PHP version.');
  136. $hasUnsuitableSupportedVersion = false;
  137. foreach ($supportedPhpVersions as $version) {
  138. if (!$sample->isSuitableFor($version)) {
  139. $hasUnsuitableSupportedVersion = true;
  140. }
  141. }
  142. self::assertTrue($hasUnsuitableSupportedVersion, 'Version specific code sample must be unsuitable for at least 1 supported PHP version.');
  143. if (!$sample->isSuitableFor(\PHP_VERSION_ID)) {
  144. continue;
  145. }
  146. }
  147. if ($fixerIsConfigurable) {
  148. // always re-configure as the fixer might have been configured with diff. configuration form previous sample
  149. $this->fixer->configure($config ?? []);
  150. }
  151. Tokens::clearCache();
  152. $tokens = Tokens::fromCode($code);
  153. $this->fixer->fix(
  154. $sample instanceof FileSpecificCodeSampleInterface ? $sample->getSplFileInfo() : $dummyFileInfo,
  155. $tokens
  156. );
  157. self::assertTrue($tokens->isChanged(), sprintf('[%s] Sample #%d is not changed during fixing.', $fixerName, $sampleCounter));
  158. $duplicatedCodeSample = array_search(
  159. $sample,
  160. \array_slice($samples, 0, $sampleCounter),
  161. true
  162. );
  163. self::assertFalse(
  164. $duplicatedCodeSample,
  165. sprintf('[%s] Sample #%d duplicates #%d.', $fixerName, $sampleCounter, $duplicatedCodeSample)
  166. );
  167. }
  168. if ($fixerIsConfigurable) {
  169. if (isset($configSamplesProvided['default'])) {
  170. reset($configSamplesProvided);
  171. self::assertSame('default', key($configSamplesProvided), sprintf('[%s] First sample must be for the default configuration.', $fixerName));
  172. } elseif (!isset($this->allowedFixersWithoutDefaultCodeSample[$fixerName])) {
  173. self::assertArrayHasKey($fixerName, $this->allowedRequiredOptions, sprintf('[%s] Has no sample for default configuration.', $fixerName));
  174. }
  175. if (\count($configSamplesProvided) < 2) {
  176. self::fail(sprintf('[%s] Configurable fixer only provides a default configuration sample and none for its configuration options.', $fixerName));
  177. }
  178. $options = $this->fixer->getConfigurationDefinition()->getOptions();
  179. foreach ($options as $option) {
  180. self::assertMatchesRegularExpression('/^[a-z_]+[a-z]$/', $option->getName(), sprintf('[%s] Option %s is not snake_case.', $fixerName, $option->getName()));
  181. self::assertMatchesRegularExpression(
  182. '/^[A-Z].+\.$/s',
  183. $option->getDescription(),
  184. sprintf('[%s] Description of option "%s" must start with capital letter and end with dot.', $fixerName, $option->getName())
  185. );
  186. }
  187. }
  188. self::assertIsInt($this->fixer->getPriority());
  189. }
  190. final public function testFixersAreFinal(): void
  191. {
  192. $reflection = new \ReflectionClass($this->fixer);
  193. self::assertTrue(
  194. $reflection->isFinal(),
  195. sprintf('Fixer "%s" must be declared "final".', $this->fixer->getName())
  196. );
  197. }
  198. final public function testDeprecatedFixersHaveCorrectSummary(): void
  199. {
  200. self::assertStringNotContainsString(
  201. 'DEPRECATED',
  202. $this->fixer->getDefinition()->getSummary(),
  203. 'Fixer cannot contain word "DEPRECATED" in summary'
  204. );
  205. $reflection = new \ReflectionClass($this->fixer);
  206. $comment = $reflection->getDocComment();
  207. if ($this->fixer instanceof DeprecatedFixerInterface) {
  208. self::assertIsString($comment, sprintf('Missing class PHPDoc for deprecated fixer "%s".', $this->fixer->getName()));
  209. self::assertStringContainsString('@deprecated', $comment);
  210. } elseif (\is_string($comment)) {
  211. self::assertStringNotContainsString('@deprecated', $comment);
  212. }
  213. }
  214. /**
  215. * Blur filter that find candidate fixer for performance optimization to use only `insertSlices` instead of multiple `insertAt` if there is no other collection manipulation.
  216. */
  217. public function testFixerUseInsertSlicesWhenOnlyInsertionsArePerformed(): void
  218. {
  219. $reflection = new \ReflectionClass($this->fixer);
  220. $tokens = Tokens::fromCode(file_get_contents($reflection->getFileName()));
  221. $sequences = $this->findAllTokenSequences($tokens, [[T_VARIABLE, '$tokens'], [T_OBJECT_OPERATOR], [T_STRING]]);
  222. $usedMethods = array_unique(array_map(static function (array $sequence): string {
  223. $last = end($sequence);
  224. return $last->getContent();
  225. }, $sequences));
  226. // if there is no `insertAt`, it's not a candidate
  227. if (!\in_array('insertAt', $usedMethods, true)) {
  228. $this->expectNotToPerformAssertions();
  229. return;
  230. }
  231. $usedMethods = array_filter($usedMethods, static fn (string $method): bool => !Preg::match('/^(count|find|generate|get|is|rewind)/', $method));
  232. $allowedMethods = ['insertAt'];
  233. $nonAllowedMethods = array_diff($usedMethods, $allowedMethods);
  234. if ([] === $nonAllowedMethods) {
  235. $fixerName = $this->fixer->getName();
  236. if (\in_array($fixerName, [
  237. // DO NOT add anything to this list at ease, align with core contributors whether it makes sense to insert tokens individually or by bulk for your case.
  238. // The original list of the fixers being exceptions and insert tokens individually came from legacy reasons when it was the only available methods to insert tokens.
  239. 'blank_line_after_namespace',
  240. 'blank_line_after_opening_tag',
  241. 'blank_line_before_statement',
  242. 'class_attributes_separation',
  243. 'date_time_immutable',
  244. 'declare_strict_types',
  245. 'doctrine_annotation_braces',
  246. 'doctrine_annotation_spaces',
  247. 'final_internal_class',
  248. 'final_public_method_for_abstract_class',
  249. 'function_typehint_space',
  250. 'heredoc_indentation',
  251. 'method_chaining_indentation',
  252. 'native_constant_invocation',
  253. 'new_with_braces',
  254. 'no_short_echo_tag',
  255. 'not_operator_with_space',
  256. 'not_operator_with_successor_space',
  257. 'php_unit_internal_class',
  258. 'php_unit_no_expectation_annotation',
  259. 'php_unit_set_up_tear_down_visibility',
  260. 'php_unit_size_class',
  261. 'php_unit_test_annotation',
  262. 'php_unit_test_class_requires_covers',
  263. 'phpdoc_to_param_type',
  264. 'phpdoc_to_property_type',
  265. 'phpdoc_to_return_type',
  266. 'random_api_migration',
  267. 'semicolon_after_instruction',
  268. 'single_line_after_imports',
  269. 'static_lambda',
  270. 'strict_param',
  271. 'void_return',
  272. ], true)) {
  273. self::markTestIncomplete(sprintf('Fixer "%s" may be optimized to use `Tokens::insertSlices` instead of `%s`, please help and optimize it.', $fixerName, implode(', ', $allowedMethods)));
  274. }
  275. self::fail(sprintf('Fixer "%s" shall be optimized to use `Tokens::insertSlices` instead of `%s`.', $fixerName, implode(', ', $allowedMethods)));
  276. }
  277. $this->addToAssertionCount(1);
  278. }
  279. final public function testFixerConfigurationDefinitions(): void
  280. {
  281. if (!$this->fixer instanceof ConfigurableFixerInterface) {
  282. $this->expectNotToPerformAssertions(); // not applied to the fixer without configuration
  283. return;
  284. }
  285. $configurationDefinition = $this->fixer->getConfigurationDefinition();
  286. foreach ($configurationDefinition->getOptions() as $option) {
  287. self::assertInstanceOf(FixerOptionInterface::class, $option);
  288. self::assertNotEmpty($option->getDescription());
  289. self::assertSame(
  290. !isset($this->allowedRequiredOptions[$this->fixer->getName()][$option->getName()]),
  291. $option->hasDefault(),
  292. sprintf(
  293. $option->hasDefault()
  294. ? 'Option `%s` of fixer `%s` is wrongly listed in `$allowedRequiredOptions` structure, as it is not required. If you just changed that option to not be required anymore, please adjust mentioned structure.'
  295. : 'Option `%s` of fixer `%s` shall not be required. If you want to introduce new required option please adjust `$allowedRequiredOptions` structure.',
  296. $option->getName(),
  297. $this->fixer->getName()
  298. )
  299. );
  300. self::assertStringNotContainsString(
  301. 'DEPRECATED',
  302. $option->getDescription(),
  303. 'Option description cannot contain word "DEPRECATED"'
  304. );
  305. }
  306. }
  307. protected function createFixer(): AbstractFixer
  308. {
  309. $fixerClassName = preg_replace('/^(PhpCsFixer)\\\\Tests(\\\\.+)Test$/', '$1$2', static::class);
  310. return new $fixerClassName();
  311. }
  312. final protected static function getTestFile(string $filename = __FILE__): \SplFileInfo
  313. {
  314. static $files = [];
  315. return $files[$filename] ?? $files[$filename] = new \SplFileInfo($filename);
  316. }
  317. /**
  318. * Tests if a fixer fixes a given string to match the expected result.
  319. *
  320. * It is used both if you want to test if something is fixed or if it is not touched by the fixer.
  321. * It also makes sure that the expected output does not change when run through the fixer. That means that you
  322. * do not need two test cases like [$expected] and [$expected, $input] (where $expected is the same in both cases)
  323. * as the latter covers both of them.
  324. * This method throws an exception if $expected and $input are equal to prevent test cases that accidentally do
  325. * not test anything.
  326. *
  327. * @param string $expected The expected fixer output
  328. * @param null|string $input The fixer input, or null if it should intentionally be equal to the output
  329. * @param null|\SplFileInfo $file The file to fix, or null if unneeded
  330. */
  331. protected function doTest(string $expected, ?string $input = null, ?\SplFileInfo $file = null): void
  332. {
  333. if ($expected === $input) {
  334. throw new \InvalidArgumentException('Input parameter must not be equal to expected parameter.');
  335. }
  336. $file ??= self::getTestFile();
  337. $fileIsSupported = $this->fixer->supports($file);
  338. if (null !== $input) {
  339. self::assertNull($this->lintSource($input));
  340. Tokens::clearCache();
  341. $tokens = Tokens::fromCode($input);
  342. if ($fileIsSupported) {
  343. self::assertTrue($this->fixer->isCandidate($tokens), 'Fixer must be a candidate for input code.');
  344. self::assertFalse($tokens->isChanged(), 'Fixer must not touch Tokens on candidate check.');
  345. $this->fixer->fix($file, $tokens);
  346. }
  347. self::assertThat(
  348. $tokens->generateCode(),
  349. new IsIdenticalString($expected),
  350. 'Code build on input code must match expected code.'
  351. );
  352. self::assertTrue($tokens->isChanged(), 'Tokens collection built on input code must be marked as changed after fixing.');
  353. $tokens->clearEmptyTokens();
  354. self::assertSameSize(
  355. $tokens,
  356. array_unique(array_map(static fn (Token $token): string => spl_object_hash($token), $tokens->toArray())),
  357. 'Token items inside Tokens collection must be unique.'
  358. );
  359. Tokens::clearCache();
  360. $expectedTokens = Tokens::fromCode($expected);
  361. self::assertTokens($expectedTokens, $tokens);
  362. }
  363. self::assertNull($this->lintSource($expected));
  364. Tokens::clearCache();
  365. $tokens = Tokens::fromCode($expected);
  366. if ($fileIsSupported) {
  367. $this->fixer->fix($file, $tokens);
  368. }
  369. self::assertThat(
  370. $tokens->generateCode(),
  371. new IsIdenticalString($expected),
  372. 'Code build on expected code must not change.'
  373. );
  374. self::assertFalse($tokens->isChanged(), 'Tokens collection built on expected code must not be marked as changed after fixing.');
  375. }
  376. protected function lintSource(string $source): ?string
  377. {
  378. try {
  379. $this->linter->lintSource($source)->check();
  380. } catch (\Exception $e) {
  381. return $e->getMessage()."\n\nSource:\n{$source}";
  382. }
  383. return null;
  384. }
  385. protected static function assertCorrectCasing(string $needle, string $haystack, string $message): void
  386. {
  387. self::assertSame(substr_count(strtolower($haystack), strtolower($needle)), substr_count($haystack, $needle), $message);
  388. }
  389. private function getLinter(): LinterInterface
  390. {
  391. static $linter = null;
  392. if (null === $linter) {
  393. $linter = new CachingLinter(
  394. getenv('FAST_LINT_TEST_CASES') ? new Linter() : new ProcessLinter()
  395. );
  396. }
  397. return $linter;
  398. }
  399. private static function assertValidDescription(string $fixerName, string $descriptionType, string $description): void
  400. {
  401. self::assertMatchesRegularExpression('/^[A-Z`].+\.$/s', $description, sprintf('[%s] The %s must start with capital letter or a ` and end with dot.', $fixerName, $descriptionType));
  402. self::assertStringNotContainsString('phpdocs', $description, sprintf('[%s] `PHPDoc` must not be in the plural in %s.', $fixerName, $descriptionType));
  403. self::assertCorrectCasing($description, 'PHPDoc', sprintf('[%s] `PHPDoc` must be in correct casing in %s.', $fixerName, $descriptionType));
  404. self::assertCorrectCasing($description, 'PHPUnit', sprintf('[%s] `PHPUnit` must be in correct casing in %s.', $fixerName, $descriptionType));
  405. self::assertFalse(strpos($descriptionType, '``'), sprintf('[%s] The %s must no contain sequential backticks.', $fixerName, $descriptionType));
  406. }
  407. /**
  408. * @param list<array{0: int, 1?: string}> $sequence
  409. *
  410. * @return list<array<int, Token>>
  411. */
  412. private function findAllTokenSequences(Tokens $tokens, array $sequence): array
  413. {
  414. $lastIndex = 0;
  415. $sequences = [];
  416. while ($found = $tokens->findSequence($sequence, $lastIndex)) {
  417. $keys = array_keys($found);
  418. $sequences[] = $found;
  419. $lastIndex = $keys[2];
  420. }
  421. return $sequences;
  422. }
  423. }