AbstractFixerTestCase.php 20 KB

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