AbstractFixerTestCase.php 19 KB

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