AbstractFixerTestCase.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  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 setUp()
  60. {
  61. parent::setUp();
  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 tearDown()
  70. {
  71. parent::tearDown();
  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::assertInternalType('bool', $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::assertInternalType('int', $sampleCounter);
  109. $code = $sample->getCode();
  110. static::assertInternalType('string', $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::assertInternalType('array', $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. 'php_unit_dedicate_assert_internal_type',
  161. ];
  162. if (\count($configSamplesProvided) < 2) {
  163. if (\in_array($fixerName, $fixerNamesWithKnownMissingSamplesWithConfig, true)) {
  164. static::markTestIncomplete(sprintf('[%s] Configurable fixer only provides a default configuration sample and none for its configuration options, please help and add it.', $fixerName));
  165. }
  166. static::fail(sprintf('[%s] Configurable fixer only provides a default configuration sample and none for its configuration options.', $fixerName));
  167. } elseif (\in_array($fixerName, $fixerNamesWithKnownMissingSamplesWithConfig, true)) {
  168. static::fail(sprintf('[%s] Invalid listed as missing code samples, please update the list.', $fixerName));
  169. }
  170. $options = $this->fixer->getConfigurationDefinition()->getOptions();
  171. foreach ($options as $option) {
  172. // @TODO 2.17 adjust fixers to use new casing and deprecate old one
  173. if (\in_array($fixerName, [
  174. 'final_internal_class',
  175. 'ordered_class_elements',
  176. ], true)) {
  177. static::markTestIncomplete(sprintf('Rule "%s" is not following new option casing yet, please help.', $fixerName));
  178. }
  179. static::assertRegExp('/^[a-z_]+[a-z]$/', $option->getName(), sprintf('[%s] Option %s is not snake_case.', $fixerName, $option->getName()));
  180. }
  181. }
  182. }
  183. /**
  184. * @group legacy
  185. * @expectedDeprecation PhpCsFixer\FixerDefinition\FixerDefinition::getConfigurationDescription is deprecated and will be removed in 3.0.
  186. * @expectedDeprecation PhpCsFixer\FixerDefinition\FixerDefinition::getDefaultConfiguration is deprecated and will be removed in 3.0.
  187. */
  188. final public function testLegacyFixerDefinitions()
  189. {
  190. $definition = $this->fixer->getDefinition();
  191. static::assertNull($definition->getConfigurationDescription(), sprintf('[%s] No configuration description expected.', $this->fixer->getName()));
  192. static::assertNull($definition->getDefaultConfiguration(), sprintf('[%s] No default configuration expected.', $this->fixer->getName()));
  193. }
  194. final public function testFixersAreFinal()
  195. {
  196. $reflection = new \ReflectionClass($this->fixer);
  197. static::assertTrue(
  198. $reflection->isFinal(),
  199. sprintf('Fixer "%s" must be declared "final".', $this->fixer->getName())
  200. );
  201. }
  202. final public function testFixersAreDefined()
  203. {
  204. static::assertInstanceOf(DefinedFixerInterface::class, $this->fixer);
  205. }
  206. final public function testDeprecatedFixersHaveCorrectSummary()
  207. {
  208. $reflection = new \ReflectionClass($this->fixer);
  209. $comment = $reflection->getDocComment();
  210. static::assertNotContains(
  211. 'DEPRECATED',
  212. $this->fixer->getDefinition()->getSummary(),
  213. 'Fixer cannot contain word "DEPRECATED" in summary'
  214. );
  215. if ($this->fixer instanceof DeprecatedFixerInterface) {
  216. static::assertContains('@deprecated', $comment);
  217. } elseif (\is_string($comment)) {
  218. static::assertNotContains('@deprecated', $comment);
  219. }
  220. }
  221. final public function testFixerConfigurationDefinitions()
  222. {
  223. if (!$this->fixer instanceof ConfigurationDefinitionFixerInterface) {
  224. $this->addToAssertionCount(1); // not applied to the fixer without configuration
  225. return;
  226. }
  227. $configurationDefinition = $this->fixer->getConfigurationDefinition();
  228. static::assertInstanceOf(FixerConfigurationResolverInterface::class, $configurationDefinition);
  229. foreach ($configurationDefinition->getOptions() as $option) {
  230. static::assertInstanceOf(FixerOptionInterface::class, $option);
  231. static::assertNotEmpty($option->getDescription());
  232. static::assertSame(
  233. !isset($this->allowedRequiredOptions[$this->fixer->getName()][$option->getName()]),
  234. $option->hasDefault(),
  235. sprintf(
  236. $option->hasDefault()
  237. ? '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.'
  238. : 'Option `%s` of fixer `%s` shall not be required. If you want to introduce new required option please adjust `$allowedRequiredOptions` structure.',
  239. $option->getName(),
  240. $this->fixer->getName()
  241. )
  242. );
  243. static::assertNotContains(
  244. 'DEPRECATED',
  245. $option->getDescription(),
  246. 'Option description cannot contain word "DEPRECATED"'
  247. );
  248. }
  249. }
  250. final public function testFixersReturnTypes()
  251. {
  252. $tokens = Tokens::fromCode('<?php ');
  253. $emptyTokens = new Tokens();
  254. static::assertInternalType('int', $this->fixer->getPriority(), sprintf('Return type for ::getPriority of "%s" is invalid.', $this->fixer->getName()));
  255. static::assertInternalType('bool', $this->fixer->supports(new \SplFileInfo(__FILE__)), sprintf('Return type for ::supports of "%s" is invalid.', $this->fixer->getName()));
  256. static::assertInternalType('bool', $this->fixer->isCandidate($emptyTokens), sprintf('Return type for ::isCandidate with empty tokens of "%s" is invalid.', $this->fixer->getName()));
  257. static::assertFalse($emptyTokens->isChanged());
  258. static::assertInternalType('bool', $this->fixer->isCandidate($tokens), sprintf('Return type for ::isCandidate of "%s" is invalid.', $this->fixer->getName()));
  259. static::assertFalse($tokens->isChanged());
  260. if ($this->fixer instanceof HeaderCommentFixer) {
  261. $this->fixer->configure(['header' => 'a']);
  262. }
  263. static::assertNull($this->fixer->fix(new \SplFileInfo(__FILE__), $emptyTokens), sprintf('Return type for ::fix with empty tokens of "%s" is invalid.', $this->fixer->getName()));
  264. static::assertFalse($emptyTokens->isChanged());
  265. static::assertNull($this->fixer->fix(new \SplFileInfo(__FILE__), $tokens), sprintf('Return type for ::fix of "%s" is invalid.', $this->fixer->getName()));
  266. }
  267. /**
  268. * @return AbstractFixer
  269. */
  270. protected function createFixer()
  271. {
  272. $fixerClassName = preg_replace('/^(PhpCsFixer)\\\\Tests(\\\\.+)Test$/', '$1$2', static::class);
  273. return new $fixerClassName();
  274. }
  275. /**
  276. * @param string $filename
  277. *
  278. * @return \SplFileInfo
  279. */
  280. protected function getTestFile($filename = __FILE__)
  281. {
  282. static $files = [];
  283. if (!isset($files[$filename])) {
  284. $files[$filename] = new \SplFileInfo($filename);
  285. }
  286. return $files[$filename];
  287. }
  288. /**
  289. * Tests if a fixer fixes a given string to match the expected result.
  290. *
  291. * It is used both if you want to test if something is fixed or if it is not touched by the fixer.
  292. * It also makes sure that the expected output does not change when run through the fixer. That means that you
  293. * do not need two test cases like [$expected] and [$expected, $input] (where $expected is the same in both cases)
  294. * as the latter covers both of them.
  295. * This method throws an exception if $expected and $input are equal to prevent test cases that accidentally do
  296. * not test anything.
  297. *
  298. * @param string $expected The expected fixer output
  299. * @param null|string $input The fixer input, or null if it should intentionally be equal to the output
  300. * @param null|\SplFileInfo $file The file to fix, or null if unneeded
  301. */
  302. protected function doTest($expected, $input = null, \SplFileInfo $file = null)
  303. {
  304. if ($expected === $input) {
  305. throw new \InvalidArgumentException('Input parameter must not be equal to expected parameter.');
  306. }
  307. $file = $file ?: $this->getTestFile();
  308. $fileIsSupported = $this->fixer->supports($file);
  309. if (null !== $input) {
  310. static::assertNull($this->lintSource($input));
  311. Tokens::clearCache();
  312. $tokens = Tokens::fromCode($input);
  313. if ($fileIsSupported) {
  314. static::assertTrue($this->fixer->isCandidate($tokens), 'Fixer must be a candidate for input code.');
  315. static::assertFalse($tokens->isChanged(), 'Fixer must not touch Tokens on candidate check.');
  316. $fixResult = $this->fixer->fix($file, $tokens);
  317. static::assertNull($fixResult, '->fix method must return null.');
  318. }
  319. static::assertThat(
  320. $tokens->generateCode(),
  321. self::createIsIdenticalStringConstraint($expected),
  322. 'Code build on input code must match expected code.'
  323. );
  324. static::assertTrue($tokens->isChanged(), 'Tokens collection built on input code must be marked as changed after fixing.');
  325. $tokens->clearEmptyTokens();
  326. static::assertSame(
  327. \count($tokens),
  328. \count(array_unique(array_map(static function (Token $token) {
  329. return spl_object_hash($token);
  330. }, $tokens->toArray()))),
  331. 'Token items inside Tokens collection must be unique.'
  332. );
  333. Tokens::clearCache();
  334. $expectedTokens = Tokens::fromCode($expected);
  335. static::assertTokens($expectedTokens, $tokens);
  336. }
  337. static::assertNull($this->lintSource($expected));
  338. Tokens::clearCache();
  339. $tokens = Tokens::fromCode($expected);
  340. if ($fileIsSupported) {
  341. $fixResult = $this->fixer->fix($file, $tokens);
  342. static::assertNull($fixResult, '->fix method must return null.');
  343. }
  344. static::assertThat(
  345. $tokens->generateCode(),
  346. self::createIsIdenticalStringConstraint($expected),
  347. 'Code build on expected code must not change.'
  348. );
  349. static::assertFalse($tokens->isChanged(), 'Tokens collection built on expected code must not be marked as changed after fixing.');
  350. }
  351. /**
  352. * @param string $source
  353. *
  354. * @return null|string
  355. */
  356. protected function lintSource($source)
  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. /**
  366. * @return LinterInterface
  367. */
  368. private function getLinter()
  369. {
  370. static $linter = null;
  371. if (null === $linter) {
  372. if (getenv('SKIP_LINT_TEST_CASES')) {
  373. $linterProphecy = $this->prophesize(\PhpCsFixer\Linter\LinterInterface::class);
  374. $linterProphecy
  375. ->lintSource(Argument::type('string'))
  376. ->willReturn($this->prophesize(\PhpCsFixer\Linter\LintingResultInterface::class)->reveal())
  377. ;
  378. $linter = $linterProphecy->reveal();
  379. } else {
  380. $linter = new CachingLinter(
  381. getenv('FAST_LINT_TEST_CASES') ? new Linter() : new ProcessLinter()
  382. );
  383. }
  384. }
  385. return $linter;
  386. }
  387. /**
  388. * @param string $fixerName
  389. * @param string $descriptionType
  390. * @param mixed $description
  391. */
  392. private static function assertValidDescription($fixerName, $descriptionType, $description)
  393. {
  394. static::assertInternalType('string', $description);
  395. static::assertRegExp('/^[A-Z`][^"]+\.$/', $description, sprintf('[%s] The %s must start with capital letter or a ` and end with dot.', $fixerName, $descriptionType));
  396. static::assertNotContains('phpdocs', $description, sprintf('[%s] `PHPDoc` must not be in the plural in %s.', $fixerName, $descriptionType), true);
  397. static::assertCorrectCasing($description, 'PHPDoc', sprintf('[%s] `PHPDoc` must be in correct casing in %s.', $fixerName, $descriptionType));
  398. static::assertCorrectCasing($description, 'PHPUnit', sprintf('[%s] `PHPUnit` must be in correct casing in %s.', $fixerName, $descriptionType));
  399. static::assertFalse(strpos($descriptionType, '``'), sprintf('[%s] The %s must no contain sequential backticks.', $fixerName, $descriptionType));
  400. }
  401. /**
  402. * @param string $needle
  403. * @param string $haystack
  404. * @param string $message
  405. */
  406. private static function assertCorrectCasing($needle, $haystack, $message)
  407. {
  408. static::assertSame(substr_count(strtolower($haystack), strtolower($needle)), substr_count($haystack, $needle), $message);
  409. }
  410. }