AbstractIntegrationTestCase.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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\Cache\NullCacheManager;
  14. use PhpCsFixer\Differ\SebastianBergmannDiffer;
  15. use PhpCsFixer\Error\Error;
  16. use PhpCsFixer\Error\ErrorsManager;
  17. use PhpCsFixer\FileRemoval;
  18. use PhpCsFixer\Fixer\FixerInterface;
  19. use PhpCsFixer\FixerFactory;
  20. use PhpCsFixer\Linter\Linter;
  21. use PhpCsFixer\Linter\LinterInterface;
  22. use PhpCsFixer\Runner\Runner;
  23. use PhpCsFixer\Tests\TestCase;
  24. use PhpCsFixer\Tokenizer\Tokens;
  25. use PhpCsFixer\WhitespacesFixerConfig;
  26. use Prophecy\Argument;
  27. use Symfony\Component\Filesystem\Exception\IOException;
  28. use Symfony\Component\Filesystem\Filesystem;
  29. use Symfony\Component\Finder\Finder;
  30. /**
  31. * Integration test base class.
  32. *
  33. * This test searches for '.test' fixture files in the given directory.
  34. * Each fixture file will be parsed and tested against the expected result.
  35. *
  36. * Fixture files have the following format:
  37. *
  38. * --TEST--
  39. * Example test description.
  40. * --RULESET--
  41. * {"@PSR2": true, "strict": true}
  42. * --CONFIG--*
  43. * {"indent": " ", "lineEnding": "\n"}
  44. * --SETTINGS--*
  45. * {"key": "value"} # optional extension point for custom IntegrationTestCase class
  46. * --REQUIREMENTS--*
  47. * {"php": 50600**}
  48. * --EXPECT--
  49. * Expected code after fixing
  50. * --INPUT--*
  51. * Code to fix
  52. *
  53. * * Section or any line in it may be omitted.
  54. * ** PHP minimum version. Default to current running php version (no effect).
  55. *
  56. * @author SpacePossum
  57. *
  58. * @internal
  59. */
  60. abstract class AbstractIntegrationTestCase extends TestCase
  61. {
  62. /**
  63. * @var LinterInterface
  64. */
  65. protected $linter;
  66. /**
  67. * @var FileRemoval
  68. */
  69. private static $fileRemoval;
  70. public static function setUpBeforeClass()
  71. {
  72. parent::setUpBeforeClass();
  73. $tmpFile = static::getTempFile();
  74. self::$fileRemoval = new FileRemoval();
  75. self::$fileRemoval->observe($tmpFile);
  76. if (!is_file($tmpFile)) {
  77. $dir = dirname($tmpFile);
  78. if (!is_dir($dir)) {
  79. $fs = new Filesystem();
  80. $fs->mkdir($dir, 0766);
  81. }
  82. }
  83. }
  84. public static function tearDownAfterClass()
  85. {
  86. parent::tearDownAfterClass();
  87. $tmpFile = static::getTempFile();
  88. self::$fileRemoval->delete($tmpFile);
  89. }
  90. protected function setUp()
  91. {
  92. parent::setUp();
  93. $this->linter = $this->getLinter();
  94. // @todo remove at 3.0 together with env var itself
  95. if (getenv('PHP_CS_FIXER_TEST_USE_LEGACY_TOKENIZER')) {
  96. Tokens::setLegacyMode(true);
  97. }
  98. }
  99. protected function tearDown()
  100. {
  101. parent::tearDown();
  102. // @todo remove at 3.0
  103. Tokens::setLegacyMode(false);
  104. }
  105. /**
  106. * @dataProvider provideIntegrationCases
  107. *
  108. * @see doTest()
  109. *
  110. * @param IntegrationCase $case
  111. */
  112. public function testIntegration(IntegrationCase $case)
  113. {
  114. $this->doTest($case);
  115. }
  116. /**
  117. * Creates test data by parsing '.test' files.
  118. *
  119. * @return IntegrationCase[][]
  120. */
  121. public function provideIntegrationCases()
  122. {
  123. $fixturesDir = realpath(static::getFixturesDir());
  124. if (!is_dir($fixturesDir)) {
  125. throw new \UnexpectedValueException(sprintf('Given fixture dir "%s" is not a directory.', $fixturesDir));
  126. }
  127. $factory = static::createIntegrationCaseFactory();
  128. $tests = [];
  129. foreach (Finder::create()->files()->in($fixturesDir) as $file) {
  130. if ('test' !== $file->getExtension()) {
  131. continue;
  132. }
  133. $tests[] = [
  134. $factory->create($file),
  135. ];
  136. }
  137. return $tests;
  138. }
  139. /**
  140. * @return IntegrationCaseFactoryInterface
  141. */
  142. protected static function createIntegrationCaseFactory()
  143. {
  144. return new IntegrationCaseFactory();
  145. }
  146. /**
  147. * Returns the full path to directory which contains the tests.
  148. *
  149. * @return string
  150. */
  151. protected static function getFixturesDir()
  152. {
  153. throw new \BadMethodCallException('Method "getFixturesDir" must be overridden by the extending class.');
  154. }
  155. /**
  156. * Returns the full path to the temporary file where the test will write to.
  157. *
  158. * @return string
  159. */
  160. protected static function getTempFile()
  161. {
  162. throw new \BadMethodCallException('Method "getTempFile" must be overridden by the extending class.');
  163. }
  164. /**
  165. * Applies the given fixers on the input and checks the result.
  166. *
  167. * It will write the input to a temp file. The file will be fixed by a Fixer instance
  168. * configured with the given fixers. The result is compared with the expected output.
  169. * It checks if no errors were reported during the fixing.
  170. *
  171. * @param IntegrationCase $case
  172. */
  173. protected function doTest(IntegrationCase $case)
  174. {
  175. if (PHP_VERSION_ID < $case->getRequirement('php')) {
  176. $this->markTestSkipped(sprintf('PHP %d (or later) is required for "%s", current "%d".', $case->getRequirement('php'), $case->getFileName(), PHP_VERSION_ID));
  177. }
  178. $input = $case->getInputCode();
  179. $expected = $case->getExpectedCode();
  180. $input = $case->hasInputCode() ? $input : $expected;
  181. $tmpFile = static::getTempFile();
  182. if (false === @file_put_contents($tmpFile, $input)) {
  183. throw new IOException(sprintf('Failed to write to tmp. file "%s".', $tmpFile));
  184. }
  185. $errorsManager = new ErrorsManager();
  186. $fixers = static::createFixers($case);
  187. $runner = new Runner(
  188. new \ArrayIterator([new \SplFileInfo($tmpFile)]),
  189. $fixers,
  190. new SebastianBergmannDiffer(),
  191. null,
  192. $errorsManager,
  193. $this->linter,
  194. false,
  195. new NullCacheManager()
  196. );
  197. Tokens::clearCache();
  198. $result = $runner->fix();
  199. $changed = array_pop($result);
  200. if (!$errorsManager->isEmpty()) {
  201. $errors = $errorsManager->getExceptionErrors();
  202. $this->assertEmpty($errors, sprintf('Errors reported during fixing of file "%s": %s', $case->getFileName(), $this->implodeErrors($errors)));
  203. $errors = $errorsManager->getInvalidErrors();
  204. $this->assertEmpty($errors, sprintf('Errors reported during linting before fixing file "%s": %s.', $case->getFileName(), $this->implodeErrors($errors)));
  205. $errors = $errorsManager->getLintErrors();
  206. $this->assertEmpty($errors, sprintf('Errors reported during linting after fixing file "%s": %s.', $case->getFileName(), $this->implodeErrors($errors)));
  207. }
  208. if (!$case->hasInputCode()) {
  209. $this->assertEmpty(
  210. $changed,
  211. sprintf(
  212. "Expected no changes made to test \"%s\" in \"%s\".\nFixers applied:\n%s.\nDiff.:\n%s.",
  213. $case->getTitle(),
  214. $case->getFileName(),
  215. null === $changed ? '[None]' : implode(',', $changed['appliedFixers']),
  216. null === $changed ? '[None]' : $changed['diff']
  217. )
  218. );
  219. return;
  220. }
  221. $this->assertNotEmpty($changed, sprintf('Expected changes made to test "%s" in "%s".', $case->getTitle(), $case->getFileName()));
  222. $fixedInputCode = file_get_contents($tmpFile);
  223. $this->assertThat(
  224. $fixedInputCode,
  225. new SameStringsConstraint($expected),
  226. sprintf(
  227. "Expected changes do not match result for \"%s\" in \"%s\".\nFixers applied:\n%s.",
  228. $case->getTitle(),
  229. $case->getFileName(),
  230. null === $changed ? '[None]' : implode(',', $changed['appliedFixers'])
  231. )
  232. );
  233. if (1 < count($fixers)) {
  234. $tmpFile = static::getTempFile();
  235. if (false === @file_put_contents($tmpFile, $input)) {
  236. throw new IOException(sprintf('Failed to write to tmp. file "%s".', $tmpFile));
  237. }
  238. $runner = new Runner(
  239. new \ArrayIterator([new \SplFileInfo($tmpFile)]),
  240. array_reverse($fixers),
  241. new SebastianBergmannDiffer(),
  242. null,
  243. $errorsManager,
  244. $this->linter,
  245. false,
  246. new NullCacheManager()
  247. );
  248. Tokens::clearCache();
  249. $runner->fix();
  250. $fixedInputCodeWithReversedFixers = file_get_contents($tmpFile);
  251. $this->assertRevertedOrderFixing($case, $fixedInputCode, $fixedInputCodeWithReversedFixers);
  252. }
  253. // run the test again with the `expected` part, this should always stay the same
  254. $this->testIntegration(
  255. new IntegrationCase(
  256. $case->getFileName(),
  257. $case->getTitle().' "--EXPECT-- part run"',
  258. $case->getSettings(),
  259. $case->getRequirements(),
  260. $case->getConfig(),
  261. $case->getRuleset(),
  262. $case->getExpectedCode(),
  263. null
  264. )
  265. );
  266. }
  267. /**
  268. * @param IntegrationCase $case
  269. * @param string $fixedInputCode
  270. * @param string $fixedInputCodeWithReversedFixers
  271. */
  272. protected static function assertRevertedOrderFixing(IntegrationCase $case, $fixedInputCode, $fixedInputCodeWithReversedFixers)
  273. {
  274. // If output is different depends on rules order - we need to verify that the rules are ordered by priority.
  275. // If not, any order is valid.
  276. if ($fixedInputCode !== $fixedInputCodeWithReversedFixers) {
  277. static::assertGreaterThan(
  278. 1,
  279. count(array_unique(array_map(
  280. static function (FixerInterface $fixer) {
  281. return $fixer->getPriority();
  282. },
  283. static::createFixers($case)
  284. ))),
  285. sprintf(
  286. 'Rules priorities are not differential enough. If rules would be used in reverse order then final output would be different than the expected one. For that, different priorities must be set up for used rules to ensure stable order of them. In "%s".',
  287. $case->getFileName()
  288. )
  289. );
  290. }
  291. }
  292. /**
  293. * @param IntegrationCase $case
  294. *
  295. * @return FixerInterface[]
  296. */
  297. private static function createFixers(IntegrationCase $case)
  298. {
  299. $config = $case->getConfig();
  300. return FixerFactory::create()
  301. ->registerBuiltInFixers()
  302. ->useRuleSet($case->getRuleset())
  303. ->setWhitespacesConfig(
  304. new WhitespacesFixerConfig($config['indent'], $config['lineEnding'])
  305. )
  306. ->getFixers();
  307. }
  308. /**
  309. * @param Error[] $errors
  310. *
  311. * @return string
  312. */
  313. private function implodeErrors(array $errors)
  314. {
  315. $errorStr = '';
  316. foreach ($errors as $error) {
  317. $source = $error->getSource();
  318. $errorStr .= sprintf("%d: %s%s\n", $error->getType(), $error->getFilePath(), null === $source ? '' : ' '.$source->getMessage()."\n\n".$source->getTraceAsString());
  319. }
  320. return $errorStr;
  321. }
  322. /**
  323. * @return LinterInterface
  324. */
  325. private function getLinter()
  326. {
  327. static $linter = null;
  328. if (null === $linter) {
  329. if (getenv('SKIP_LINT_TEST_CASES')) {
  330. $linterProphecy = $this->prophesize(\PhpCsFixer\Linter\LinterInterface::class);
  331. $linterProphecy
  332. ->lintSource(Argument::type('string'))
  333. ->willReturn($this->prophesize(\PhpCsFixer\Linter\LintingResultInterface::class)->reveal());
  334. $linterProphecy
  335. ->lintFile(Argument::type('string'))
  336. ->willReturn($this->prophesize(\PhpCsFixer\Linter\LintingResultInterface::class)->reveal());
  337. $linterProphecy
  338. ->isAsync()
  339. ->willReturn(false);
  340. $linter = $linterProphecy->reveal();
  341. } else {
  342. $linter = new Linter();
  343. }
  344. }
  345. return $linter;
  346. }
  347. }