RuleSetsTest.php 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. <?php
  2. declare(strict_types=1);
  3. /*
  4. * This file is part of PHP CS Fixer.
  5. *
  6. * (c) Fabien Potencier <fabien@symfony.com>
  7. * Dariusz Rumiński <dariusz.ruminski@gmail.com>
  8. *
  9. * This source file is subject to the MIT license that is bundled
  10. * with this source code in the file LICENSE.
  11. */
  12. namespace PhpCsFixer\Tests\RuleSet;
  13. use PhpCsFixer\Fixer\ConfigurableFixerInterface;
  14. use PhpCsFixer\Fixer\PhpUnit\PhpUnitTargetVersion;
  15. use PhpCsFixer\RuleSet\RuleSet;
  16. use PhpCsFixer\RuleSet\RuleSets;
  17. use PhpCsFixer\Tests\Test\TestCaseUtils;
  18. use PhpCsFixer\Tests\TestCase;
  19. /**
  20. * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
  21. *
  22. * @internal
  23. *
  24. * @covers \PhpCsFixer\RuleSet\RuleSets
  25. */
  26. final class RuleSetsTest extends TestCase
  27. {
  28. public function testGetSetDefinitionNames(): void
  29. {
  30. self::assertSame(
  31. array_keys(RuleSets::getSetDefinitions()),
  32. RuleSets::getSetDefinitionNames()
  33. );
  34. }
  35. public function testGetSetDefinitions(): void
  36. {
  37. $sets = RuleSets::getSetDefinitions();
  38. foreach ($sets as $name => $set) {
  39. self::assertIsString($name);
  40. self::assertStringStartsWith('@', $name);
  41. self::assertIsArray($set->getRules());
  42. self::assertSame($set, RuleSets::getSetDefinition($name));
  43. }
  44. }
  45. public function testGetUnknownSetDefinition(): void
  46. {
  47. $name = 'Unknown';
  48. $this->expectException(\InvalidArgumentException::class);
  49. $this->expectExceptionMessageMatches(\sprintf('#^Set "%s" does not exist\.$#', $name));
  50. RuleSets::getSetDefinition($name);
  51. }
  52. /**
  53. * @dataProvider provideSetDefinitionNameCases
  54. */
  55. public function testHasIntegrationTest(string $setDefinitionName): void
  56. {
  57. $setsWithoutTests = [
  58. '@PER',
  59. '@PER:risky',
  60. '@PER-CS',
  61. '@PER-CS:risky',
  62. '@PHP56Migration',
  63. '@PHP56Migration:risky',
  64. '@PHP70Migration',
  65. '@PHP70Migration:risky',
  66. '@PHP71Migration',
  67. '@PHP71Migration:risky',
  68. '@PHP73Migration',
  69. '@PHP80Migration',
  70. '@PhpCsFixer',
  71. '@PhpCsFixer:risky',
  72. '@PHPUnit48Migration',
  73. '@PHPUnit55Migration:risky',
  74. '@PHPUnit75Migration:risky',
  75. '@PHPUnit84Migration:risky',
  76. '@PHPUnit91Migration:risky',
  77. '@PHPUnit100Migration:risky',
  78. '@PSR1',
  79. ];
  80. if (\in_array($setDefinitionName, $setsWithoutTests, true)) {
  81. self::markTestIncomplete(\sprintf('Set "%s" has no integration test.', $setDefinitionName));
  82. }
  83. $setDefinitionFileNamePrefix = str_replace(':', '-', $setDefinitionName);
  84. $dir = __DIR__.'/../../tests/Fixtures/Integration/set';
  85. $file = \sprintf('%s/%s.test', $dir, $setDefinitionFileNamePrefix);
  86. self::assertFileExists($file);
  87. self::assertFileExists(\sprintf('%s/%s.test-in.php', $dir, $setDefinitionFileNamePrefix));
  88. self::assertFileExists(\sprintf('%s/%s.test-out.php', $dir, $setDefinitionFileNamePrefix));
  89. $template = '--TEST--
  90. Integration of %s.
  91. --RULESET--
  92. {"%s": true}
  93. ';
  94. self::assertStringStartsWith(
  95. \sprintf($template, $setDefinitionName, $setDefinitionName),
  96. file_get_contents($file)
  97. );
  98. }
  99. /**
  100. * @dataProvider provideSetDefinitionNameCases
  101. */
  102. public function testBuildInSetDefinitionNames(string $setName): void
  103. {
  104. self::assertStringStartsWith('@', $setName);
  105. }
  106. /**
  107. * @dataProvider provideSetDefinitionNameCases
  108. */
  109. public function testSetDefinitionsAreSorted(string $setDefinitionName): void
  110. {
  111. $setDefinition = RuleSets::getSetDefinitions()[$setDefinitionName]->getRules();
  112. $sortedSetDefinition = $setDefinition;
  113. $this->sort($sortedSetDefinition);
  114. self::assertSame($sortedSetDefinition, $setDefinition, \sprintf(
  115. 'Failed to assert that the set definition for "%s" is sorted by key.',
  116. $setDefinitionName
  117. ));
  118. }
  119. public function testSetDefinitionsItselfIsSorted(): void
  120. {
  121. $setDefinition = array_keys(RuleSets::getSetDefinitions());
  122. $sortedSetDefinition = $setDefinition;
  123. natsort($sortedSetDefinition);
  124. self::assertSame($sortedSetDefinition, $setDefinition);
  125. }
  126. /**
  127. * @return iterable<array{string}>
  128. */
  129. public static function provideSetDefinitionNameCases(): iterable
  130. {
  131. $setDefinitionNames = RuleSets::getSetDefinitionNames();
  132. return array_map(static fn (string $setDefinitionName): array => [$setDefinitionName], $setDefinitionNames);
  133. }
  134. /**
  135. * @dataProvider providePHPUnitMigrationTargetVersionsCases
  136. */
  137. public function testPHPUnitMigrationTargetVersions(string $setName): void
  138. {
  139. $ruleSet = new RuleSet([$setName => true]);
  140. foreach ($ruleSet->getRules() as $ruleName => $ruleConfig) {
  141. $targetVersion = $ruleConfig['target'] ?? $this->getDefaultPHPUnitTargetOfRule($ruleName);
  142. if (null === $targetVersion) {
  143. // fixer does not have "target" option
  144. $this->addToAssertionCount(1);
  145. continue;
  146. }
  147. self::assertPHPUnitVersionIsLargestAllowed($setName, $ruleName, $targetVersion);
  148. }
  149. }
  150. /**
  151. * @return iterable<array{string}>
  152. */
  153. public static function providePHPUnitMigrationTargetVersionsCases(): iterable
  154. {
  155. $setDefinitionNames = RuleSets::getSetDefinitionNames();
  156. $setDefinitionPHPUnitMigrationNames = array_filter($setDefinitionNames, static fn (string $setDefinitionName): bool => 1 === preg_match('/^@PHPUnit\d+Migration:risky$/', $setDefinitionName));
  157. return array_map(static fn (string $setDefinitionName): array => [$setDefinitionName], $setDefinitionPHPUnitMigrationNames);
  158. }
  159. private static function assertPHPUnitVersionIsLargestAllowed(string $setName, string $ruleName, string $actualTargetVersion): void
  160. {
  161. $maximumVersionForRuleset = preg_replace('/^@PHPUnit(\d+)(\d)Migration:risky$/', '$1.$2', $setName);
  162. $fixer = TestCaseUtils::getFixerByName($ruleName);
  163. self::assertInstanceOf(ConfigurableFixerInterface::class, $fixer, \sprintf('The fixer "%s" shall be configurable.', $fixer->getName()));
  164. foreach ($fixer->getConfigurationDefinition()->getOptions() as $option) {
  165. if ('target' === $option->getName()) {
  166. /** @var list<PhpUnitTargetVersion::VERSION_*> */
  167. $allowedValues = $option->getAllowedValues();
  168. $allowedVersionsForFixer = array_diff(
  169. $allowedValues,
  170. [PhpUnitTargetVersion::VERSION_NEWEST]
  171. );
  172. break;
  173. }
  174. }
  175. if (!isset($allowedVersionsForFixer)) {
  176. throw new \Exception(\sprintf('The fixer "%s" does not have option "target".', $fixer->getName()));
  177. }
  178. /** @var list<PhpUnitTargetVersion::VERSION_*> */
  179. $allowedVersionsForRuleset = array_filter(
  180. $allowedVersionsForFixer,
  181. static fn (string $version): bool => version_compare($maximumVersionForRuleset, $version) >= 0
  182. );
  183. self::assertTrue(\in_array($actualTargetVersion, $allowedVersionsForRuleset, true), \sprintf(
  184. 'Rule "%s" (in rule set "%s") has target "%s", but the rule set is not allowing it (allowed are only "%s")',
  185. $fixer->getName(),
  186. $setName,
  187. $actualTargetVersion,
  188. implode('", "', $allowedVersionsForRuleset)
  189. ));
  190. rsort($allowedVersionsForRuleset);
  191. $maximumAllowedVersionForRuleset = reset($allowedVersionsForRuleset);
  192. self::assertSame($maximumAllowedVersionForRuleset, $actualTargetVersion, \sprintf(
  193. 'Rule "%s" (in rule set "%s") has target "%s", but there is higher available target "%s"',
  194. $fixer->getName(),
  195. $setName,
  196. $actualTargetVersion,
  197. $maximumAllowedVersionForRuleset
  198. ));
  199. }
  200. /**
  201. * Sorts an array of rule set definitions recursively.
  202. *
  203. * Sometimes keys are all string, sometimes they are integers - we need to account for that.
  204. *
  205. * @param array<array-key, mixed> $data
  206. */
  207. private function sort(array &$data): void
  208. {
  209. $this->doSort($data, '');
  210. }
  211. /**
  212. * @param array<array-key, mixed> $data
  213. */
  214. private function doSort(array &$data, string $path): void
  215. {
  216. if ('ordered_imports.imports_order' === $path) { // order matters
  217. return;
  218. }
  219. $keys = array_keys($data);
  220. if ($this->allInteger($keys)) {
  221. sort($data);
  222. } else {
  223. ksort($data);
  224. }
  225. foreach ($data as $key => $value) {
  226. if (\is_array($value)) {
  227. $this->doSort(
  228. $data[$key],
  229. $path.('' !== $path ? '.' : '').$key
  230. );
  231. }
  232. }
  233. }
  234. /**
  235. * @param array<array-key, mixed> $values
  236. */
  237. private function allInteger(array $values): bool
  238. {
  239. foreach ($values as $value) {
  240. if (!\is_int($value)) {
  241. return false;
  242. }
  243. }
  244. return true;
  245. }
  246. private function getDefaultPHPUnitTargetOfRule(string $ruleName): ?string
  247. {
  248. $targetVersion = null;
  249. $fixer = TestCaseUtils::getFixerByName($ruleName);
  250. if ($fixer instanceof ConfigurableFixerInterface) {
  251. foreach ($fixer->getConfigurationDefinition()->getOptions() as $option) {
  252. if ('target' === $option->getName()) {
  253. $targetVersion = $option->getDefault();
  254. break;
  255. }
  256. }
  257. }
  258. return $targetVersion;
  259. }
  260. }