AbstractFixerTestCase.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. <?php
  2. /*
  3. * This file is part of PHP CS Fixer.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. * Dariusz Rumiński <dariusz.ruminski@gmail.com>
  7. *
  8. * This source file is subject to the MIT license that is bundled
  9. * with this source code in the file LICENSE.
  10. */
  11. namespace PhpCsFixer\Tests\Test;
  12. use PhpCsFixer\AbstractFixer;
  13. use PhpCsFixer\AbstractProxyFixer;
  14. use PhpCsFixer\Fixer\Comment\HeaderCommentFixer;
  15. use PhpCsFixer\Fixer\ConfigurationDefinitionFixerInterface;
  16. use PhpCsFixer\Fixer\DefinedFixerInterface;
  17. use PhpCsFixer\Fixer\DeprecatedFixerInterface;
  18. use PhpCsFixer\Fixer\Whitespace\SingleBlankLineAtEofFixer;
  19. use PhpCsFixer\FixerConfiguration\FixerConfigurationResolverInterface;
  20. use PhpCsFixer\FixerConfiguration\FixerOptionInterface;
  21. use PhpCsFixer\FixerDefinition\CodeSampleInterface;
  22. use PhpCsFixer\FixerDefinition\FileSpecificCodeSampleInterface;
  23. use PhpCsFixer\FixerDefinition\VersionSpecificCodeSampleInterface;
  24. use PhpCsFixer\Linter\CachingLinter;
  25. use PhpCsFixer\Linter\Linter;
  26. use PhpCsFixer\Linter\LinterInterface;
  27. use PhpCsFixer\Linter\ProcessLinter;
  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. use Prophecy\Argument;
  34. /**
  35. * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
  36. *
  37. * @internal
  38. */
  39. abstract class AbstractFixerTestCase extends TestCase
  40. {
  41. use AssertTokensTrait;
  42. use IsIdenticalConstraint;
  43. /**
  44. * @var null|LinterInterface
  45. */
  46. protected $linter;
  47. /**
  48. * @var null|AbstractFixer
  49. */
  50. protected $fixer;
  51. // do not modify this structure without prior discussion
  52. private $allowedRequiredOptions = [
  53. 'header_comment' => ['header' => true],
  54. ];
  55. // do not modify this structure without prior discussion
  56. private $allowedFixersWithoutDefaultCodeSample = [
  57. 'general_phpdoc_annotation_remove' => true,
  58. ];
  59. protected function doSetUp()
  60. {
  61. parent::doSetUp();
  62. $this->linter = $this->getLinter();
  63. $this->fixer = $this->createFixer();
  64. // @todo remove at 3.0 together with env var itself
  65. if (getenv('PHP_CS_FIXER_TEST_USE_LEGACY_TOKENIZER')) {
  66. Tokens::setLegacyMode(true);
  67. }
  68. }
  69. protected function doTearDown()
  70. {
  71. parent::doTearDown();
  72. $this->linter = null;
  73. $this->fixer = null;
  74. // @todo remove at 3.0
  75. Tokens::setLegacyMode(false);
  76. }
  77. final public function testIsRisky()
  78. {
  79. static::assertIsBool($this->fixer->isRisky(), sprintf('Return type for ::isRisky of "%s" is invalid.', $this->fixer->getName()));
  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()
  96. {
  97. static::assertInstanceOf(DefinedFixerInterface::class, $this->fixer);
  98. $fixerName = $this->fixer->getName();
  99. $definition = $this->fixer->getDefinition();
  100. $fixerIsConfigurable = $this->fixer instanceof ConfigurationDefinitionFixerInterface;
  101. self::assertValidDescription($fixerName, 'summary', $definition->getSummary());
  102. $samples = $definition->getCodeSamples();
  103. static::assertNotEmpty($samples, sprintf('[%s] Code samples are required.', $fixerName));
  104. $configSamplesProvided = [];
  105. $dummyFileInfo = new StdinFileInfo();
  106. foreach ($samples as $sampleCounter => $sample) {
  107. static::assertInstanceOf(CodeSampleInterface::class, $sample, sprintf('[%s] Sample #%d', $fixerName, $sampleCounter));
  108. static::assertIsInt($sampleCounter);
  109. $code = $sample->getCode();
  110. static::assertIsString($code, sprintf('[%s] Sample #%d', $fixerName, $sampleCounter));
  111. static::assertNotEmpty($code, sprintf('[%s] Sample #%d', $fixerName, $sampleCounter));
  112. if (!($this->fixer instanceof SingleBlankLineAtEofFixer)) {
  113. static::assertSame("\n", substr($code, -1), sprintf('[%s] Sample #%d must end with linebreak', $fixerName, $sampleCounter));
  114. }
  115. $config = $sample->getConfiguration();
  116. if (null !== $config) {
  117. static::assertTrue($fixerIsConfigurable, sprintf('[%s] Sample #%d has configuration, but the fixer is not configurable.', $fixerName, $sampleCounter));
  118. static::assertIsArray($config, sprintf('[%s] Sample #%d configuration must be an array or null.', $fixerName, $sampleCounter));
  119. $configSamplesProvided[$sampleCounter] = $config;
  120. } elseif ($fixerIsConfigurable) {
  121. if (!$sample instanceof VersionSpecificCodeSampleInterface) {
  122. static::assertArrayNotHasKey('default', $configSamplesProvided, sprintf('[%s] Multiple non-versioned samples with default configuration.', $fixerName));
  123. }
  124. $configSamplesProvided['default'] = true;
  125. }
  126. if ($sample instanceof VersionSpecificCodeSampleInterface && !$sample->isSuitableFor(\PHP_VERSION_ID)) {
  127. continue;
  128. }
  129. if ($fixerIsConfigurable) {
  130. // always re-configure as the fixer might have been configured with diff. configuration form previous sample
  131. $this->fixer->configure(null === $config ? [] : $config);
  132. }
  133. Tokens::clearCache();
  134. $tokens = Tokens::fromCode($code);
  135. $this->fixer->fix(
  136. $sample instanceof FileSpecificCodeSampleInterface ? $sample->getSplFileInfo() : $dummyFileInfo,
  137. $tokens
  138. );
  139. static::assertTrue($tokens->isChanged(), sprintf('[%s] Sample #%d is not changed during fixing.', $fixerName, $sampleCounter));
  140. $duplicatedCodeSample = array_search(
  141. $sample,
  142. \array_slice($samples, 0, $sampleCounter),
  143. false
  144. );
  145. static::assertFalse(
  146. $duplicatedCodeSample,
  147. sprintf('[%s] Sample #%d duplicates #%d.', $fixerName, $sampleCounter, $duplicatedCodeSample)
  148. );
  149. }
  150. if ($fixerIsConfigurable) {
  151. if (isset($configSamplesProvided['default'])) {
  152. reset($configSamplesProvided);
  153. static::assertSame('default', key($configSamplesProvided), sprintf('[%s] First sample must be for the default configuration.', $fixerName));
  154. } elseif (!isset($this->allowedFixersWithoutDefaultCodeSample[$fixerName])) {
  155. static::assertArrayHasKey($fixerName, $this->allowedRequiredOptions, sprintf('[%s] Has no sample for default configuration.', $fixerName));
  156. }
  157. // It may only shrink, never add anything to it.
  158. $fixerNamesWithKnownMissingSamplesWithConfig = [ // @TODO 3.0 - remove this
  159. 'is_null', // has only one option which is deprecated
  160. ];
  161. if (\count($configSamplesProvided) < 2) {
  162. if (\in_array($fixerName, $fixerNamesWithKnownMissingSamplesWithConfig, true)) {
  163. static::markTestIncomplete(sprintf('[%s] Configurable fixer only provides a default configuration sample and none for its configuration options, please help and add it.', $fixerName));
  164. }
  165. static::fail(sprintf('[%s] Configurable fixer only provides a default configuration sample and none for its configuration options.', $fixerName));
  166. } elseif (\in_array($fixerName, $fixerNamesWithKnownMissingSamplesWithConfig, true)) {
  167. static::fail(sprintf('[%s] Invalid listed as missing code samples, please update the list.', $fixerName));
  168. }
  169. $options = $this->fixer->getConfigurationDefinition()->getOptions();
  170. foreach ($options as $option) {
  171. // @TODO 2.17 adjust fixers to use new casing and deprecate old one
  172. if (\in_array($fixerName, [
  173. 'final_internal_class',
  174. 'ordered_class_elements',
  175. ], true)) {
  176. static::markTestIncomplete(sprintf('Rule "%s" is not following new option casing yet, please help.', $fixerName));
  177. }
  178. static::assertMatchesRegularExpression('/^[a-z_]+[a-z]$/', $option->getName(), sprintf('[%s] Option %s is not snake_case.', $fixerName, $option->getName()));
  179. }
  180. }
  181. }
  182. /**
  183. * @group legacy
  184. * @expectedDeprecation PhpCsFixer\FixerDefinition\FixerDefinition::getConfigurationDescription is deprecated and will be removed in 3.0.
  185. * @expectedDeprecation PhpCsFixer\FixerDefinition\FixerDefinition::getDefaultConfiguration is deprecated and will be removed in 3.0.
  186. */
  187. final public function testLegacyFixerDefinitions()
  188. {
  189. $definition = $this->fixer->getDefinition();
  190. static::assertNull($definition->getConfigurationDescription(), sprintf('[%s] No configuration description expected.', $this->fixer->getName()));
  191. static::assertNull($definition->getDefaultConfiguration(), sprintf('[%s] No default configuration expected.', $this->fixer->getName()));
  192. }
  193. final public function testFixersAreFinal()
  194. {
  195. $reflection = new \ReflectionClass($this->fixer);
  196. static::assertTrue(
  197. $reflection->isFinal(),
  198. sprintf('Fixer "%s" must be declared "final".', $this->fixer->getName())
  199. );
  200. }
  201. final public function testFixersAreDefined()
  202. {
  203. static::assertInstanceOf(DefinedFixerInterface::class, $this->fixer);
  204. }
  205. final public function testDeprecatedFixersHaveCorrectSummary()
  206. {
  207. $reflection = new \ReflectionClass($this->fixer);
  208. $comment = $reflection->getDocComment();
  209. static::assertStringNotContainsString(
  210. 'DEPRECATED',
  211. $this->fixer->getDefinition()->getSummary(),
  212. 'Fixer cannot contain word "DEPRECATED" in summary'
  213. );
  214. if ($this->fixer instanceof DeprecatedFixerInterface) {
  215. static::assertStringContainsString('@deprecated', $comment);
  216. } elseif (\is_string($comment)) {
  217. static::assertStringNotContainsString('@deprecated', $comment);
  218. }
  219. }
  220. final public function testFixerConfigurationDefinitions()
  221. {
  222. if (!$this->fixer instanceof ConfigurationDefinitionFixerInterface) {
  223. $this->addToAssertionCount(1); // not applied to the fixer without configuration
  224. return;
  225. }
  226. $configurationDefinition = $this->fixer->getConfigurationDefinition();
  227. static::assertInstanceOf(FixerConfigurationResolverInterface::class, $configurationDefinition);
  228. foreach ($configurationDefinition->getOptions() as $option) {
  229. static::assertInstanceOf(FixerOptionInterface::class, $option);
  230. static::assertNotEmpty($option->getDescription());
  231. static::assertSame(
  232. !isset($this->allowedRequiredOptions[$this->fixer->getName()][$option->getName()]),
  233. $option->hasDefault(),
  234. sprintf(
  235. $option->hasDefault()
  236. ? '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.'
  237. : 'Option `%s` of fixer `%s` shall not be required. If you want to introduce new required option please adjust `$allowedRequiredOptions` structure.',
  238. $option->getName(),
  239. $this->fixer->getName()
  240. )
  241. );
  242. static::assertStringNotContainsString(
  243. 'DEPRECATED',
  244. $option->getDescription(),
  245. 'Option description cannot contain word "DEPRECATED"'
  246. );
  247. }
  248. }
  249. final public function testFixersReturnTypes()
  250. {
  251. $tokens = Tokens::fromCode('<?php ');
  252. $emptyTokens = new Tokens();
  253. static::assertIsInt($this->fixer->getPriority(), sprintf('Return type for ::getPriority of "%s" is invalid.', $this->fixer->getName()));
  254. static::assertIsBool($this->fixer->supports(new \SplFileInfo(__FILE__)), sprintf('Return type for ::supports of "%s" is invalid.', $this->fixer->getName()));
  255. static::assertIsBool($this->fixer->isCandidate($emptyTokens), sprintf('Return type for ::isCandidate with empty tokens of "%s" is invalid.', $this->fixer->getName()));
  256. static::assertFalse($emptyTokens->isChanged());
  257. static::assertIsBool($this->fixer->isCandidate($tokens), sprintf('Return type for ::isCandidate of "%s" is invalid.', $this->fixer->getName()));
  258. static::assertFalse($tokens->isChanged());
  259. if ($this->fixer instanceof HeaderCommentFixer) {
  260. $this->fixer->configure(['header' => 'a']);
  261. }
  262. static::assertNull($this->fixer->fix(new \SplFileInfo(__FILE__), $emptyTokens), sprintf('Return type for ::fix with empty tokens of "%s" is invalid.', $this->fixer->getName()));
  263. static::assertFalse($emptyTokens->isChanged());
  264. static::assertNull($this->fixer->fix(new \SplFileInfo(__FILE__), $tokens), sprintf('Return type for ::fix of "%s" is invalid.', $this->fixer->getName()));
  265. }
  266. /**
  267. * @return AbstractFixer
  268. */
  269. protected function createFixer()
  270. {
  271. $fixerClassName = preg_replace('/^(PhpCsFixer)\\\\Tests(\\\\.+)Test$/', '$1$2', static::class);
  272. return new $fixerClassName();
  273. }
  274. /**
  275. * @param string $filename
  276. *
  277. * @return \SplFileInfo
  278. */
  279. protected function getTestFile($filename = __FILE__)
  280. {
  281. static $files = [];
  282. if (!isset($files[$filename])) {
  283. $files[$filename] = new \SplFileInfo($filename);
  284. }
  285. return $files[$filename];
  286. }
  287. /**
  288. * Tests if a fixer fixes a given string to match the expected result.
  289. *
  290. * It is used both if you want to test if something is fixed or if it is not touched by the fixer.
  291. * It also makes sure that the expected output does not change when run through the fixer. That means that you
  292. * do not need two test cases like [$expected] and [$expected, $input] (where $expected is the same in both cases)
  293. * as the latter covers both of them.
  294. * This method throws an exception if $expected and $input are equal to prevent test cases that accidentally do
  295. * not test anything.
  296. *
  297. * @param string $expected The expected fixer output
  298. * @param null|string $input The fixer input, or null if it should intentionally be equal to the output
  299. * @param null|\SplFileInfo $file The file to fix, or null if unneeded
  300. */
  301. protected function doTest($expected, $input = null, \SplFileInfo $file = null)
  302. {
  303. if ($expected === $input) {
  304. throw new \InvalidArgumentException('Input parameter must not be equal to expected parameter.');
  305. }
  306. $file = $file ?: $this->getTestFile();
  307. $fileIsSupported = $this->fixer->supports($file);
  308. if (null !== $input) {
  309. static::assertNull($this->lintSource($input));
  310. Tokens::clearCache();
  311. $tokens = Tokens::fromCode($input);
  312. if ($fileIsSupported) {
  313. static::assertTrue($this->fixer->isCandidate($tokens), 'Fixer must be a candidate for input code.');
  314. static::assertFalse($tokens->isChanged(), 'Fixer must not touch Tokens on candidate check.');
  315. $fixResult = $this->fixer->fix($file, $tokens);
  316. static::assertNull($fixResult, '->fix method must return null.');
  317. }
  318. static::assertThat(
  319. $tokens->generateCode(),
  320. self::createIsIdenticalStringConstraint($expected),
  321. 'Code build on input code must match expected code.'
  322. );
  323. static::assertTrue($tokens->isChanged(), 'Tokens collection built on input code must be marked as changed after fixing.');
  324. $tokens->clearEmptyTokens();
  325. static::assertSame(
  326. \count($tokens),
  327. \count(array_unique(array_map(static function (Token $token) {
  328. return spl_object_hash($token);
  329. }, $tokens->toArray()))),
  330. 'Token items inside Tokens collection must be unique.'
  331. );
  332. Tokens::clearCache();
  333. $expectedTokens = Tokens::fromCode($expected);
  334. static::assertTokens($expectedTokens, $tokens);
  335. }
  336. static::assertNull($this->lintSource($expected));
  337. Tokens::clearCache();
  338. $tokens = Tokens::fromCode($expected);
  339. if ($fileIsSupported) {
  340. $fixResult = $this->fixer->fix($file, $tokens);
  341. static::assertNull($fixResult, '->fix method must return null.');
  342. }
  343. static::assertThat(
  344. $tokens->generateCode(),
  345. self::createIsIdenticalStringConstraint($expected),
  346. 'Code build on expected code must not change.'
  347. );
  348. static::assertFalse($tokens->isChanged(), 'Tokens collection built on expected code must not be marked as changed after fixing.');
  349. }
  350. /**
  351. * @param string $source
  352. *
  353. * @return null|string
  354. */
  355. protected function lintSource($source)
  356. {
  357. try {
  358. $this->linter->lintSource($source)->check();
  359. } catch (\Exception $e) {
  360. return $e->getMessage()."\n\nSource:\n{$source}";
  361. }
  362. return null;
  363. }
  364. /**
  365. * @return LinterInterface
  366. */
  367. private function getLinter()
  368. {
  369. static $linter = null;
  370. if (null === $linter) {
  371. if (getenv('SKIP_LINT_TEST_CASES')) {
  372. $linterProphecy = $this->prophesize(\PhpCsFixer\Linter\LinterInterface::class);
  373. $linterProphecy
  374. ->lintSource(Argument::type('string'))
  375. ->willReturn($this->prophesize(\PhpCsFixer\Linter\LintingResultInterface::class)->reveal())
  376. ;
  377. $linter = $linterProphecy->reveal();
  378. } else {
  379. $linter = new CachingLinter(
  380. getenv('FAST_LINT_TEST_CASES') ? new Linter() : new ProcessLinter()
  381. );
  382. }
  383. }
  384. return $linter;
  385. }
  386. /**
  387. * @param string $fixerName
  388. * @param string $descriptionType
  389. * @param mixed $description
  390. */
  391. private static function assertValidDescription($fixerName, $descriptionType, $description)
  392. {
  393. static::assertIsString($description);
  394. static::assertMatchesRegularExpression('/^[A-Z`][^"]+\.$/', $description, sprintf('[%s] The %s must start with capital letter or a ` and end with dot.', $fixerName, $descriptionType));
  395. static::assertStringNotContainsString('phpdocs', $description, sprintf('[%s] `PHPDoc` must not be in the plural in %s.', $fixerName, $descriptionType));
  396. static::assertCorrectCasing($description, 'PHPDoc', sprintf('[%s] `PHPDoc` must be in correct casing in %s.', $fixerName, $descriptionType));
  397. static::assertCorrectCasing($description, 'PHPUnit', sprintf('[%s] `PHPUnit` must be in correct casing in %s.', $fixerName, $descriptionType));
  398. static::assertFalse(strpos($descriptionType, '``'), sprintf('[%s] The %s must no contain sequential backticks.', $fixerName, $descriptionType));
  399. }
  400. /**
  401. * @param string $needle
  402. * @param string $haystack
  403. * @param string $message
  404. */
  405. private static function assertCorrectCasing($needle, $haystack, $message)
  406. {
  407. static::assertSame(substr_count(strtolower($haystack), strtolower($needle)), substr_count($haystack, $needle), $message);
  408. }
  409. }