AbstractFixerTestCase.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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. static::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. static::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. $samples = $definition->getCodeSamples();
  102. static::assertNotEmpty($samples, sprintf('[%s] Code samples are required.', $fixerName));
  103. $configSamplesProvided = [];
  104. $dummyFileInfo = new StdinFileInfo();
  105. foreach ($samples as $sampleCounter => $sample) {
  106. static::assertInstanceOf(CodeSampleInterface::class, $sample, sprintf('[%s] Sample #%d', $fixerName, $sampleCounter));
  107. static::assertIsInt($sampleCounter);
  108. $code = $sample->getCode();
  109. static::assertNotEmpty($code, sprintf('[%s] Sample #%d', $fixerName, $sampleCounter));
  110. if (!$this->fixer instanceof SingleBlankLineAtEofFixer) {
  111. static::assertStringEndsWith("\n", $code, sprintf('[%s] Sample #%d must end with linebreak', $fixerName, $sampleCounter));
  112. }
  113. $config = $sample->getConfiguration();
  114. if (null !== $config) {
  115. static::assertTrue($fixerIsConfigurable, sprintf('[%s] Sample #%d has configuration, but the fixer is not configurable.', $fixerName, $sampleCounter));
  116. $configSamplesProvided[$sampleCounter] = $config;
  117. } elseif ($fixerIsConfigurable) {
  118. if (!$sample instanceof VersionSpecificCodeSampleInterface) {
  119. static::assertArrayNotHasKey('default', $configSamplesProvided, sprintf('[%s] Multiple non-versioned samples with default configuration.', $fixerName));
  120. }
  121. $configSamplesProvided['default'] = true;
  122. }
  123. if ($sample instanceof VersionSpecificCodeSampleInterface && !$sample->isSuitableFor(\PHP_VERSION_ID)) {
  124. continue;
  125. }
  126. if ($fixerIsConfigurable) {
  127. // always re-configure as the fixer might have been configured with diff. configuration form previous sample
  128. $this->fixer->configure($config ?? []);
  129. }
  130. Tokens::clearCache();
  131. $tokens = Tokens::fromCode($code);
  132. $this->fixer->fix(
  133. $sample instanceof FileSpecificCodeSampleInterface ? $sample->getSplFileInfo() : $dummyFileInfo,
  134. $tokens
  135. );
  136. static::assertTrue($tokens->isChanged(), sprintf('[%s] Sample #%d is not changed during fixing.', $fixerName, $sampleCounter));
  137. $duplicatedCodeSample = array_search(
  138. $sample,
  139. \array_slice($samples, 0, $sampleCounter),
  140. false
  141. );
  142. static::assertFalse(
  143. $duplicatedCodeSample,
  144. sprintf('[%s] Sample #%d duplicates #%d.', $fixerName, $sampleCounter, $duplicatedCodeSample)
  145. );
  146. }
  147. if ($fixerIsConfigurable) {
  148. if (isset($configSamplesProvided['default'])) {
  149. reset($configSamplesProvided);
  150. static::assertSame('default', key($configSamplesProvided), sprintf('[%s] First sample must be for the default configuration.', $fixerName));
  151. } elseif (!isset($this->allowedFixersWithoutDefaultCodeSample[$fixerName])) {
  152. static::assertArrayHasKey($fixerName, $this->allowedRequiredOptions, sprintf('[%s] Has no sample for default configuration.', $fixerName));
  153. }
  154. if (\count($configSamplesProvided) < 2) {
  155. static::fail(sprintf('[%s] Configurable fixer only provides a default configuration sample and none for its configuration options.', $fixerName));
  156. }
  157. $options = $this->fixer->getConfigurationDefinition()->getOptions();
  158. foreach ($options as $option) {
  159. static::assertMatchesRegularExpression('/^[a-z_]+[a-z]$/', $option->getName(), sprintf('[%s] Option %s is not snake_case.', $fixerName, $option->getName()));
  160. }
  161. }
  162. static::assertIsInt($this->fixer->getPriority());
  163. }
  164. final public function testFixersAreFinal(): void
  165. {
  166. $reflection = new \ReflectionClass($this->fixer);
  167. static::assertTrue(
  168. $reflection->isFinal(),
  169. sprintf('Fixer "%s" must be declared "final".', $this->fixer->getName())
  170. );
  171. }
  172. final public function testDeprecatedFixersHaveCorrectSummary(): void
  173. {
  174. static::assertStringNotContainsString(
  175. 'DEPRECATED',
  176. $this->fixer->getDefinition()->getSummary(),
  177. 'Fixer cannot contain word "DEPRECATED" in summary'
  178. );
  179. $reflection = new \ReflectionClass($this->fixer);
  180. $comment = $reflection->getDocComment();
  181. if ($this->fixer instanceof DeprecatedFixerInterface) {
  182. static::assertIsString($comment, sprintf('Missing class PHPDoc for deprecated fixer "%s".', $this->fixer->getName()));
  183. static::assertStringContainsString('@deprecated', $comment);
  184. } elseif (\is_string($comment)) {
  185. static::assertStringNotContainsString('@deprecated', $comment);
  186. }
  187. }
  188. /**
  189. * Blur filter that find candidate fixer for performance optimization to use only `insertSlices` instead of multiple `insertAt` if there is no other collection manipulation.
  190. */
  191. public function testFixerUseInsertSlicesWhenOnlyInsertionsArePerformed(): void
  192. {
  193. $reflection = new \ReflectionClass($this->fixer);
  194. $tokens = Tokens::fromCode(file_get_contents($reflection->getFileName()));
  195. $sequences = $this->findAllTokenSequences($tokens, [[T_VARIABLE, '$tokens'], [T_OBJECT_OPERATOR], [T_STRING]]);
  196. $usedMethods = array_unique(array_map(static function (array $sequence): string {
  197. $last = end($sequence);
  198. return $last->getContent();
  199. }, $sequences));
  200. // if there is no `insertAt`, it's not a candidate
  201. if (!\in_array('insertAt', $usedMethods, true)) {
  202. $this->expectNotToPerformAssertions();
  203. return;
  204. }
  205. $usedMethods = array_filter($usedMethods, static function (string $method): bool {
  206. return 0 === Preg::match('/^(count|find|generate|get|is|rewind)/', $method);
  207. });
  208. $allowedMethods = ['insertAt'];
  209. $nonAllowedMethods = array_diff($usedMethods, $allowedMethods);
  210. if ([] === $nonAllowedMethods) {
  211. $fixerName = $this->fixer->getName();
  212. if (\in_array($fixerName, [
  213. // 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.
  214. // 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.
  215. 'blank_line_after_namespace',
  216. 'blank_line_after_opening_tag',
  217. 'blank_line_before_statement',
  218. 'class_attributes_separation',
  219. 'date_time_immutable',
  220. 'declare_strict_types',
  221. 'doctrine_annotation_braces',
  222. 'doctrine_annotation_spaces',
  223. 'final_internal_class',
  224. 'final_public_method_for_abstract_class',
  225. 'function_typehint_space',
  226. 'heredoc_indentation',
  227. 'method_chaining_indentation',
  228. 'native_constant_invocation',
  229. 'new_with_braces',
  230. 'no_short_echo_tag',
  231. 'not_operator_with_space',
  232. 'not_operator_with_successor_space',
  233. 'php_unit_internal_class',
  234. 'php_unit_no_expectation_annotation',
  235. 'php_unit_set_up_tear_down_visibility',
  236. 'php_unit_size_class',
  237. 'php_unit_test_annotation',
  238. 'php_unit_test_class_requires_covers',
  239. 'phpdoc_to_param_type',
  240. 'phpdoc_to_property_type',
  241. 'phpdoc_to_return_type',
  242. 'random_api_migration',
  243. 'semicolon_after_instruction',
  244. 'single_line_after_imports',
  245. 'static_lambda',
  246. 'strict_param',
  247. 'void_return',
  248. ], true)) {
  249. static::markTestIncomplete(sprintf('Fixer "%s" may be optimized to use `Tokens::insertSlices` instead of `%s`, please help and optimize it.', $fixerName, implode(', ', $allowedMethods)));
  250. }
  251. static::fail(sprintf('Fixer "%s" shall be optimized to use `Tokens::insertSlices` instead of `%s`.', $fixerName, implode(', ', $allowedMethods)));
  252. }
  253. $this->addToAssertionCount(1);
  254. }
  255. final public function testFixerConfigurationDefinitions(): void
  256. {
  257. if (!$this->fixer instanceof ConfigurableFixerInterface) {
  258. $this->expectNotToPerformAssertions(); // not applied to the fixer without configuration
  259. return;
  260. }
  261. $configurationDefinition = $this->fixer->getConfigurationDefinition();
  262. foreach ($configurationDefinition->getOptions() as $option) {
  263. static::assertInstanceOf(FixerOptionInterface::class, $option);
  264. static::assertNotEmpty($option->getDescription());
  265. static::assertSame(
  266. !isset($this->allowedRequiredOptions[$this->fixer->getName()][$option->getName()]),
  267. $option->hasDefault(),
  268. sprintf(
  269. $option->hasDefault()
  270. ? '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.'
  271. : 'Option `%s` of fixer `%s` shall not be required. If you want to introduce new required option please adjust `$allowedRequiredOptions` structure.',
  272. $option->getName(),
  273. $this->fixer->getName()
  274. )
  275. );
  276. static::assertStringNotContainsString(
  277. 'DEPRECATED',
  278. $option->getDescription(),
  279. 'Option description cannot contain word "DEPRECATED"'
  280. );
  281. }
  282. }
  283. protected function createFixer(): AbstractFixer
  284. {
  285. $fixerClassName = preg_replace('/^(PhpCsFixer)\\\\Tests(\\\\.+)Test$/', '$1$2', static::class);
  286. return new $fixerClassName();
  287. }
  288. protected function getTestFile(string $filename = __FILE__): \SplFileInfo
  289. {
  290. static $files = [];
  291. if (!isset($files[$filename])) {
  292. $files[$filename] = new \SplFileInfo($filename);
  293. }
  294. return $files[$filename];
  295. }
  296. /**
  297. * Tests if a fixer fixes a given string to match the expected result.
  298. *
  299. * It is used both if you want to test if something is fixed or if it is not touched by the fixer.
  300. * It also makes sure that the expected output does not change when run through the fixer. That means that you
  301. * do not need two test cases like [$expected] and [$expected, $input] (where $expected is the same in both cases)
  302. * as the latter covers both of them.
  303. * This method throws an exception if $expected and $input are equal to prevent test cases that accidentally do
  304. * not test anything.
  305. *
  306. * @param string $expected The expected fixer output
  307. * @param null|string $input The fixer input, or null if it should intentionally be equal to the output
  308. * @param null|\SplFileInfo $file The file to fix, or null if unneeded
  309. */
  310. protected function doTest(string $expected, ?string $input = null, ?\SplFileInfo $file = null): void
  311. {
  312. if ($expected === $input) {
  313. throw new \InvalidArgumentException('Input parameter must not be equal to expected parameter.');
  314. }
  315. $file ??= $this->getTestFile();
  316. $fileIsSupported = $this->fixer->supports($file);
  317. if (null !== $input) {
  318. static::assertNull($this->lintSource($input));
  319. Tokens::clearCache();
  320. $tokens = Tokens::fromCode($input);
  321. if ($fileIsSupported) {
  322. static::assertTrue($this->fixer->isCandidate($tokens), 'Fixer must be a candidate for input code.');
  323. static::assertFalse($tokens->isChanged(), 'Fixer must not touch Tokens on candidate check.');
  324. $this->fixer->fix($file, $tokens);
  325. }
  326. static::assertThat(
  327. $tokens->generateCode(),
  328. new IsIdenticalString($expected),
  329. 'Code build on input code must match expected code.'
  330. );
  331. static::assertTrue($tokens->isChanged(), 'Tokens collection built on input code must be marked as changed after fixing.');
  332. $tokens->clearEmptyTokens();
  333. static::assertSame(
  334. \count($tokens),
  335. \count(array_unique(array_map(static function (Token $token): string {
  336. return spl_object_hash($token);
  337. }, $tokens->toArray()))),
  338. 'Token items inside Tokens collection must be unique.'
  339. );
  340. Tokens::clearCache();
  341. $expectedTokens = Tokens::fromCode($expected);
  342. static::assertTokens($expectedTokens, $tokens);
  343. }
  344. static::assertNull($this->lintSource($expected));
  345. Tokens::clearCache();
  346. $tokens = Tokens::fromCode($expected);
  347. if ($fileIsSupported) {
  348. $this->fixer->fix($file, $tokens);
  349. }
  350. static::assertThat(
  351. $tokens->generateCode(),
  352. new IsIdenticalString($expected),
  353. 'Code build on expected code must not change.'
  354. );
  355. static::assertFalse($tokens->isChanged(), 'Tokens collection built on expected code must not be marked as changed after fixing.');
  356. }
  357. protected function lintSource(string $source): ?string
  358. {
  359. try {
  360. $this->linter->lintSource($source)->check();
  361. } catch (\Exception $e) {
  362. return $e->getMessage()."\n\nSource:\n{$source}";
  363. }
  364. return null;
  365. }
  366. private function getLinter(): LinterInterface
  367. {
  368. static $linter = null;
  369. if (null === $linter) {
  370. $linter = new CachingLinter(
  371. getenv('FAST_LINT_TEST_CASES') ? new Linter() : new ProcessLinter()
  372. );
  373. }
  374. return $linter;
  375. }
  376. private static function assertValidDescription(string $fixerName, string $descriptionType, string $description): void
  377. {
  378. static::assertMatchesRegularExpression('/^[A-Z`][^"]+\.$/', $description, sprintf('[%s] The %s must start with capital letter or a ` and end with dot.', $fixerName, $descriptionType));
  379. static::assertStringNotContainsString('phpdocs', $description, sprintf('[%s] `PHPDoc` must not be in the plural in %s.', $fixerName, $descriptionType));
  380. static::assertCorrectCasing($description, 'PHPDoc', sprintf('[%s] `PHPDoc` must be in correct casing in %s.', $fixerName, $descriptionType));
  381. static::assertCorrectCasing($description, 'PHPUnit', sprintf('[%s] `PHPUnit` must be in correct casing in %s.', $fixerName, $descriptionType));
  382. static::assertFalse(strpos($descriptionType, '``'), sprintf('[%s] The %s must no contain sequential backticks.', $fixerName, $descriptionType));
  383. }
  384. private static function assertCorrectCasing(string $needle, string $haystack, string $message): void
  385. {
  386. static::assertSame(substr_count(strtolower($haystack), strtolower($needle)), substr_count($haystack, $needle), $message);
  387. }
  388. /**
  389. * @param list<array{0: int, 1?: string}> $sequence
  390. *
  391. * @return list<array<int, Token>>
  392. */
  393. private function findAllTokenSequences(Tokens $tokens, array $sequence): array
  394. {
  395. $lastIndex = 0;
  396. $sequences = [];
  397. while ($found = $tokens->findSequence($sequence, $lastIndex)) {
  398. $keys = array_keys($found);
  399. $sequences[] = $found;
  400. $lastIndex = $keys[2];
  401. }
  402. return $sequences;
  403. }
  404. }