AbstractFixerTestCase.php 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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 GeckoPackages\PHPUnit\Constraints\SameStringsConstraint;
  13. use PhpCsFixer\Fixer\ConfigurableFixerInterface;
  14. use PhpCsFixer\Fixer\FixerInterface;
  15. use PhpCsFixer\FixerFactory;
  16. use PhpCsFixer\Linter\Linter;
  17. use PhpCsFixer\Linter\LinterInterface;
  18. use PhpCsFixer\RuleSet;
  19. use PhpCsFixer\Tests\Test\Assert\AssertTokensTrait;
  20. use PhpCsFixer\Tests\TestCase;
  21. use PhpCsFixer\Tokenizer\Token;
  22. use PhpCsFixer\Tokenizer\Tokens;
  23. use PhpCsFixer\Utils;
  24. use Prophecy\Argument;
  25. /**
  26. * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
  27. *
  28. * @internal
  29. */
  30. abstract class AbstractFixerTestCase extends TestCase
  31. {
  32. use AssertTokensTrait;
  33. /**
  34. * @var LinterInterface
  35. */
  36. protected $linter;
  37. /**
  38. * @var null|ConfigurableFixerInterface|FixerInterface
  39. */
  40. protected $fixer;
  41. /**
  42. * @var null|string
  43. */
  44. private $fixerClassName;
  45. protected function setUp()
  46. {
  47. parent::setUp();
  48. $this->linter = $this->getLinter();
  49. $this->fixer = $this->createFixer();
  50. // @todo remove at 3.0 together with env var itself
  51. if (getenv('PHP_CS_FIXER_TEST_USE_LEGACY_TOKENIZER')) {
  52. Tokens::setLegacyMode(true);
  53. }
  54. }
  55. protected function tearDown()
  56. {
  57. parent::tearDown();
  58. // @todo remove at 3.0
  59. Tokens::setLegacyMode(false);
  60. }
  61. /**
  62. * @return FixerInterface
  63. */
  64. protected function createFixer()
  65. {
  66. $fixerClassName = $this->getFixerClassName();
  67. return new $fixerClassName();
  68. }
  69. /**
  70. * Create fixer factory with all needed fixers registered.
  71. *
  72. * @return FixerFactory
  73. */
  74. protected function createFixerFactory()
  75. {
  76. return FixerFactory::create()->registerBuiltInFixers();
  77. }
  78. /**
  79. * @return string
  80. */
  81. protected function getFixerName()
  82. {
  83. $reflection = new \ReflectionClass($this);
  84. $name = preg_replace('/FixerTest$/', '', $reflection->getShortName());
  85. return Utils::camelCaseToUnderscore($name);
  86. }
  87. /**
  88. * @param string $filename
  89. *
  90. * @return \SplFileInfo
  91. */
  92. protected function getTestFile($filename = __FILE__)
  93. {
  94. static $files = [];
  95. if (!isset($files[$filename])) {
  96. $files[$filename] = new \SplFileInfo($filename);
  97. }
  98. return $files[$filename];
  99. }
  100. /**
  101. * Tests if a fixer fixes a given string to match the expected result.
  102. *
  103. * It is used both if you want to test if something is fixed or if it is not touched by the fixer.
  104. * It also makes sure that the expected output does not change when run through the fixer. That means that you
  105. * do not need two test cases like [$expected] and [$expected, $input] (where $expected is the same in both cases)
  106. * as the latter covers both of them.
  107. * This method throws an exception if $expected and $input are equal to prevent test cases that accidentally do
  108. * not test anything.
  109. *
  110. * @param string $expected The expected fixer output
  111. * @param null|string $input The fixer input, or null if it should intentionally be equal to the output
  112. * @param null|\SplFileInfo $file The file to fix, or null if unneeded
  113. */
  114. protected function doTest($expected, $input = null, \SplFileInfo $file = null)
  115. {
  116. if ($expected === $input) {
  117. throw new \InvalidArgumentException('Input parameter must not be equal to expected parameter.');
  118. }
  119. $file = $file ?: $this->getTestFile();
  120. $fileIsSupported = $this->fixer->supports($file);
  121. if (null !== $input) {
  122. $this->assertNull($this->lintSource($input));
  123. Tokens::clearCache();
  124. $tokens = Tokens::fromCode($input);
  125. if ($fileIsSupported) {
  126. $this->assertTrue($this->fixer->isCandidate($tokens), 'Fixer must be a candidate for input code.');
  127. $this->assertFalse($tokens->isChanged(), 'Fixer must not touch Tokens on candidate check.');
  128. $fixResult = $this->fixer->fix($file, $tokens);
  129. $this->assertNull($fixResult, '->fix method must return null.');
  130. }
  131. $this->assertThat(
  132. $tokens->generateCode(),
  133. new SameStringsConstraint($expected),
  134. 'Code build on input code must match expected code.'
  135. );
  136. $this->assertTrue($tokens->isChanged(), 'Tokens collection built on input code must be marked as changed after fixing.');
  137. $tokens->clearEmptyTokens();
  138. $this->assertSame(
  139. count($tokens),
  140. count(array_unique(array_map(static function (Token $token) {
  141. return spl_object_hash($token);
  142. }, $tokens->toArray()))),
  143. 'Token items inside Tokens collection must be unique.'
  144. );
  145. Tokens::clearCache();
  146. $expectedTokens = Tokens::fromCode($expected);
  147. $this->assertTokens($expectedTokens, $tokens);
  148. }
  149. $this->assertNull($this->lintSource($expected));
  150. Tokens::clearCache();
  151. $tokens = Tokens::fromCode($expected);
  152. if ($fileIsSupported) {
  153. $fixResult = $this->fixer->fix($file, $tokens);
  154. $this->assertNull($fixResult, '->fix method must return null.');
  155. }
  156. $this->assertThat(
  157. $tokens->generateCode(),
  158. new SameStringsConstraint($expected),
  159. 'Code build on expected code must not change.'
  160. );
  161. $this->assertFalse($tokens->isChanged(), 'Tokens collection built on expected code must not be marked as changed after fixing.');
  162. }
  163. /**
  164. * @param string $source
  165. *
  166. * @return null|string
  167. */
  168. protected function lintSource($source)
  169. {
  170. try {
  171. $this->linter->lintSource($source)->check();
  172. } catch (\Exception $e) {
  173. return $e->getMessage()."\n\nSource:\n${source}";
  174. }
  175. }
  176. private function assertTokens(Tokens $expectedTokens, Tokens $inputTokens)
  177. {
  178. foreach ($expectedTokens as $index => $expectedToken) {
  179. $option = ['JSON_PRETTY_PRINT'];
  180. $inputToken = $inputTokens[$index];
  181. $this->assertTrue(
  182. $expectedToken->equals($inputToken),
  183. sprintf("The token at index %d must be:\n%s,\ngot:\n%s.", $index, $expectedToken->toJson($option), $inputToken->toJson($option))
  184. );
  185. $expectedTokenKind = $expectedToken->isArray() ? $expectedToken->getId() : $expectedToken->getContent();
  186. $this->assertTrue(
  187. $inputTokens->isTokenKindFound($expectedTokenKind),
  188. sprintf('The token kind %s must be found in fixed tokens collection.', $expectedTokenKind)
  189. );
  190. }
  191. $this->assertSame($expectedTokens->count(), $inputTokens->count(), 'Both collections must have the same length.');
  192. }
  193. /**
  194. * @return LinterInterface
  195. */
  196. private function getLinter()
  197. {
  198. static $linter = null;
  199. if (null === $linter) {
  200. if (getenv('SKIP_LINT_TEST_CASES')) {
  201. $linterProphecy = $this->prophesize(\PhpCsFixer\Linter\LinterInterface::class);
  202. $linterProphecy
  203. ->lintSource(Argument::type('string'))
  204. ->willReturn($this->prophesize(\PhpCsFixer\Linter\LintingResultInterface::class)->reveal());
  205. $linter = $linterProphecy->reveal();
  206. } else {
  207. $linter = new Linter();
  208. }
  209. }
  210. return $linter;
  211. }
  212. /**
  213. * @return string
  214. */
  215. private function getFixerClassName()
  216. {
  217. if (null !== $this->fixerClassName) {
  218. return $this->fixerClassName;
  219. }
  220. try {
  221. $fixers = $this->createFixerFactory()
  222. ->useRuleSet(new RuleSet([$this->getFixerName() => true]))
  223. ->getFixers()
  224. ;
  225. } catch (\UnexpectedValueException $e) {
  226. throw new \UnexpectedValueException('Cannot determine fixer class, perhaps you forget to override `getFixerName` or `createFixerFactory` method?', 0, $e);
  227. }
  228. if (1 !== count($fixers)) {
  229. throw new \UnexpectedValueException(sprintf('Determine fixer class should result in one fixer, got "%d". Perhaps you configured the fixer to "false" ?', count($fixers)));
  230. }
  231. $this->fixerClassName = get_class($fixers[0]);
  232. return $this->fixerClassName;
  233. }
  234. }