AbstractFixerTestCase.php 9.4 KB

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