PageRenderTime 48ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/protected/vendor/fabpot/php-cs-fixer/Symfony/CS/Tests/AbstractIntegrationTest.php

https://gitlab.com/I-NOZex/quiz
PHP | 331 lines | 190 code | 48 blank | 93 comment | 30 complexity | 625646c1192bb568c24b45e6ec466ba0 MD5 | raw file
  1. <?php
  2. /*
  3. * This file is part of the PHP CS utility.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * This source file is subject to the MIT license that is bundled
  8. * with this source code in the file LICENSE.
  9. */
  10. namespace Symfony\CS\Tests;
  11. use Symfony\Component\Filesystem\Exception\IOException;
  12. use Symfony\Component\Filesystem\Filesystem;
  13. use Symfony\CS\ErrorsManager;
  14. use Symfony\CS\FileCacheManager;
  15. use Symfony\CS\Fixer;
  16. use Symfony\CS\FixerInterface;
  17. /**
  18. * Integration test base class.
  19. *
  20. * This test searches for '.test' fixture files in the given directory.
  21. * Each fixture file will be parsed and tested against the expected result.
  22. *
  23. * Fixture files have the following format:
  24. *
  25. * --TEST--
  26. * Example test description
  27. * --CONFIG--
  28. * level=symfony|none|psr0|psr1|psr2|symfony
  29. * fixers=fixer1,fixer2,...*
  30. * --fixers=fixer3,fixer4,...****
  31. * --REQUIREMENTS--
  32. * php=5.4**
  33. * hhvm=false***
  34. * --INPUT--
  35. * Code to fix
  36. * --EXPECT--
  37. * Expected code after fixing*****
  38. *
  39. * * Additional fixers may be omitted.
  40. * ** PHP minimum version. Default to current running php version (no effect).
  41. * *** HHVM compliant flag. Default to true. Set to false to skip test under HHVM.
  42. * **** Black listed filters may be omitted.
  43. * ***** When the expected block is omitted the input is expected not to
  44. * be changed by the fixers.
  45. *
  46. * @author SpacePossum <possumfromspace@gmail.com>
  47. *
  48. * @internal
  49. */
  50. abstract class AbstractIntegrationTest extends \PHPUnit_Framework_TestCase
  51. {
  52. private static $builtInFixers;
  53. public static function setUpBeforeClass()
  54. {
  55. $tmpFile = static::getTempFile();
  56. if (!is_file($tmpFile)) {
  57. $dir = dirname($tmpFile);
  58. if (!is_dir($dir)) {
  59. $fs = new Filesystem();
  60. $fs->mkdir($dir, 0766);
  61. }
  62. }
  63. }
  64. public static function tearDownAfterClass()
  65. {
  66. @unlink(static::getTempFile());
  67. }
  68. /**
  69. * @dataProvider getTests
  70. *
  71. * @see doTestIntegration()
  72. */
  73. public function testIntegration($testFileName, $testTitle, $fixers, array $requirements, $input, $expected = null)
  74. {
  75. $this->doTestIntegration($testFileName, $testTitle, $fixers, $requirements, $input, $expected);
  76. }
  77. /**
  78. * Creates test data by parsing '.test' files.
  79. *
  80. * @return array
  81. */
  82. public function getTests()
  83. {
  84. $fixturesDir = realpath($this->getFixturesDir());
  85. if (!is_dir($fixturesDir)) {
  86. throw new \UnexpectedValueException(sprintf('Given fixture dir "%s" is not a directory.', $fixturesDir));
  87. }
  88. $tests = array();
  89. foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($fixturesDir), \RecursiveIteratorIterator::LEAVES_ONLY) as $file) {
  90. if (!preg_match('/\.test$/', $file)) {
  91. continue;
  92. }
  93. $test = file_get_contents($file->getRealpath());
  94. $fileName = $file->getFileName();
  95. if (!preg_match('/--TEST--[\n](.*?)\s--CONFIG--[\n](.*?)(\s--REQUIREMENTS--[\n](.*?))?\s--INPUT--[\n](.*?[\n]*)(?:[\n]--EXPECT--\s(.*)|$)/s', $test, $match)) {
  96. throw new \InvalidArgumentException(sprintf('Test format invalid for "%s".', $fileName));
  97. }
  98. $tests[] = array($fileName, $match[1], $this->getFixersFromConfig($fileName, $match[2]), $this->getRequirementsFromConfig($fileName, $match[4]), $match[5], isset($match[6]) ? $match[6] : null);
  99. }
  100. return $tests;
  101. }
  102. /**
  103. * Returns the full path to directory which contains the tests.
  104. *
  105. * @return string
  106. */
  107. protected static function getFixturesDir()
  108. {
  109. throw new \BadMethodCallException('Method "getFixturesDir" must be overridden by the extending class.');
  110. }
  111. /**
  112. * Returns the full path to the temporary file where the test will write to.
  113. *
  114. * @return string
  115. */
  116. protected static function getTempFile()
  117. {
  118. throw new \BadMethodCallException('Method "getTempFile" must be overridden by the extending class.');
  119. }
  120. /**
  121. * Applies the given fixers on the input and checks the result.
  122. *
  123. * It will write the input to a temp file. The file will be fixed by a Fixer instance
  124. * configured with the given fixers. The result is compared with the expected output.
  125. * It checks if no errors were reported during the fixing.
  126. *
  127. * @param string $testFileName Filename
  128. * @param string $testTitle Test title
  129. * @param FixerInterface[] $fixers Fixers to use
  130. * @param array $requirements Env requirements (PHP, HHVM)
  131. * @param string $input Code to fix
  132. * @param string|null $expected Expected result or null if the input is expected not to change
  133. */
  134. protected function doTestIntegration($testFileName, $testTitle, $fixers, array $requirements, $input, $expected = null)
  135. {
  136. if (defined('HHVM_VERSION') && false === $requirements['hhvm']) {
  137. $this->markTestSkipped('HHVM is not supported.');
  138. }
  139. if (isset($requirements['php']) && version_compare(PHP_VERSION, $requirements['php']) < 0) {
  140. $this->markTestSkipped(sprintf('PHP %s (or later) is required.', $requirements['php']));
  141. }
  142. $errorsManager = new ErrorsManager();
  143. $fixer = new Fixer();
  144. $fixer->setErrorsManager($errorsManager);
  145. $tmpFile = static::getTempFile();
  146. if (false === @file_put_contents($tmpFile, $input)) {
  147. throw new IOException(sprintf('Failed to write to tmp. file "%s".', $tmpFile));
  148. }
  149. $changed = $fixer->fixFile(new \SplFileInfo($tmpFile), $fixers, false, true, new FileCacheManager(false, null, $fixers));
  150. $this->assertTrue($errorsManager->isEmpty(), 'Errors reported during fixing.');
  151. if (null === $expected) {
  152. $this->assertEmpty($changed, sprintf("Expected no changes made to test \"%s\" in \"%s\".\nFixers applied:\n\"%s\".\nDiff.:\n\"%s\".", $testTitle, $testFileName, $changed === null ? '[None]' : implode(',', $changed['appliedFixers']), $changed === null ? '[None]' : $changed['diff']));
  153. return;
  154. }
  155. $this->assertNotEmpty($changed, sprintf('Expected changes made to test "%s" in "%s".', $testTitle, $testFileName));
  156. $this->assertSame($expected, file_get_contents($tmpFile), sprintf('Expected changes do not match result for "%s" in "%s".', $testTitle, $testFileName));
  157. // run the test again with the `expected` part, this should always stay the same
  158. $this->testIntegration($testFileName, $testTitle.' "--EXPECT-- part run"', $fixers, $requirements, $expected);
  159. }
  160. /**
  161. * Parses the '--CONFIG--' block of a '.test' file and determines what fixers should be used.
  162. *
  163. * @param string $fileName
  164. * @param string $config
  165. *
  166. * @return FixerInterface[]
  167. */
  168. protected function getFixersFromConfig($fileName, $config)
  169. {
  170. static $levelMap = array(
  171. 'none' => FixerInterface::NONE_LEVEL,
  172. 'psr1' => FixerInterface::PSR1_LEVEL,
  173. 'psr2' => FixerInterface::PSR2_LEVEL,
  174. 'symfony' => FixerInterface::SYMFONY_LEVEL,
  175. );
  176. $lines = explode("\n", $config);
  177. if (empty($lines)) {
  178. throw new \InvalidArgumentException(sprintf('No configuration options found in "%s".', $fileName));
  179. }
  180. $config = array('level' => null, 'fixers' => array(), '--fixers' => array());
  181. foreach ($lines as $line) {
  182. $labelValuePair = explode('=', $line);
  183. if (2 !== count($labelValuePair)) {
  184. throw new \InvalidArgumentException(sprintf('Invalid configuration line "%s" in "%s".', $line, $fileName));
  185. }
  186. $label = strtolower(trim($labelValuePair[0]));
  187. $value = trim($labelValuePair[1]);
  188. switch ($label) {
  189. case 'level':
  190. if (!array_key_exists($value, $levelMap)) {
  191. throw new \InvalidArgumentException(sprintf('Unknown level "%s" set in configuration in "%s", expected any of "%s".', $value, $fileName, implode(', ', array_keys($levelMap))));
  192. }
  193. if (null !== $config['level']) {
  194. throw new \InvalidArgumentException(sprintf('Cannot use multiple levels in configuration in "%s".', $fileName));
  195. }
  196. $config['level'] = $value;
  197. break;
  198. case 'fixers':
  199. case '--fixers':
  200. foreach (explode(',', $value) as $fixer) {
  201. $config[$label][] = strtolower(trim($fixer));
  202. }
  203. break;
  204. default:
  205. throw new \InvalidArgumentException(sprintf('Unknown configuration item "%s" in "%s".', $label, $fileName));
  206. }
  207. }
  208. if (null === $config['level']) {
  209. throw new \InvalidArgumentException(sprintf('Level not set in configuration "%s".', $fileName));
  210. }
  211. if (null === self::$builtInFixers) {
  212. $fixer = new Fixer();
  213. $fixer->registerBuiltInFixers();
  214. self::$builtInFixers = $fixer->getFixers();
  215. }
  216. $fixers = array();
  217. for ($i = 0, $limit = count(self::$builtInFixers); $i < $limit; ++$i) {
  218. $fixer = self::$builtInFixers[$i];
  219. $fixerName = $fixer->getName();
  220. if ('psr0' === $fixer->getName()) {
  221. // File based fixer won't work
  222. continue;
  223. }
  224. if ($fixer->getLevel() !== ($fixer->getLevel() & $levelMap[$config['level']])) {
  225. if (false !== $key = array_search($fixerName, $config['fixers'], true)) {
  226. $fixers[] = $fixer;
  227. unset($config['fixers'][$key]);
  228. }
  229. continue;
  230. }
  231. if (false !== $key = array_search($fixerName, $config['--fixers'], true)) {
  232. unset($config['--fixers'][$key]);
  233. continue;
  234. }
  235. if (in_array($fixerName, $config['fixers'], true)) {
  236. throw new \InvalidArgumentException(sprintf('Additional fixer "%s" configured, but is already part of the level.', $fixerName));
  237. }
  238. $fixers[] = $fixer;
  239. }
  240. if (!empty($config['fixers']) || !empty($config['--fixers'])) {
  241. throw new \InvalidArgumentException(sprintf('Unknown fixers in configuration "%s".', implode(',', empty($config['fixers']) ? $config['--fixers'] : $config['fixers'])));
  242. }
  243. return $fixers;
  244. }
  245. /**
  246. * Parses the '--REQUIREMENTS--' block of a '.test' file and determines requirements.
  247. *
  248. * @param string $fileName
  249. * @param string $config
  250. *
  251. * @return array
  252. */
  253. protected function getRequirementsFromConfig($fileName, $config)
  254. {
  255. $requirements = array('hhvm' => true, 'php' => PHP_VERSION);
  256. if ('' === $config) {
  257. return $requirements;
  258. }
  259. $lines = explode("\n", $config);
  260. if (empty($lines)) {
  261. return $requirements;
  262. }
  263. foreach ($lines as $line) {
  264. $labelValuePair = explode('=', $line);
  265. if (2 !== count($labelValuePair)) {
  266. throw new \InvalidArgumentException(sprintf('Invalid requirements line "%s" in "%s".', $line, $fileName));
  267. }
  268. $label = strtolower(trim($labelValuePair[0]));
  269. $value = trim($labelValuePair[1]);
  270. switch ($label) {
  271. case 'hhvm':
  272. $requirements['hhvm'] = 'false' === $value ? false : true;
  273. break;
  274. case 'php':
  275. $requirements['php'] = $value;
  276. break;
  277. default:
  278. throw new \InvalidArgumentException(sprintf('Unknown configuration item "%s" in "%s".', $label, $fileName));
  279. }
  280. }
  281. return $requirements;
  282. }
  283. }