ProjectCodeTest.php 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150
  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\AutoReview;
  13. use PhpCsFixer\AbstractFixer;
  14. use PhpCsFixer\AbstractPhpdocToTypeDeclarationFixer;
  15. use PhpCsFixer\AbstractPhpdocTypesFixer;
  16. use PhpCsFixer\AbstractProxyFixer;
  17. use PhpCsFixer\Console\Command\FixCommand;
  18. use PhpCsFixer\DocBlock\Annotation;
  19. use PhpCsFixer\DocBlock\DocBlock;
  20. use PhpCsFixer\Fixer\AbstractPhpUnitFixer;
  21. use PhpCsFixer\Fixer\ConfigurableFixerTrait;
  22. use PhpCsFixer\Fixer\PhpUnit\PhpUnitNamespacedFixer;
  23. use PhpCsFixer\FixerFactory;
  24. use PhpCsFixer\Preg;
  25. use PhpCsFixer\Tests\Test\AbstractFixerTestCase;
  26. use PhpCsFixer\Tests\Test\AbstractIntegrationTestCase;
  27. use PhpCsFixer\Tests\TestCase;
  28. use PhpCsFixer\Tokenizer\Token;
  29. use PhpCsFixer\Tokenizer\Tokens;
  30. use PhpCsFixer\Tokenizer\TokensAnalyzer;
  31. use Symfony\Component\Finder\Finder;
  32. use Symfony\Component\Finder\SplFileInfo;
  33. /**
  34. * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
  35. *
  36. * @internal
  37. *
  38. * @coversNothing
  39. *
  40. * @group auto-review
  41. * @group covers-nothing
  42. */
  43. final class ProjectCodeTest extends TestCase
  44. {
  45. /**
  46. * @var null|array<string, array{class-string<TestCase>}>
  47. */
  48. private static ?array $testClassCases = null;
  49. /**
  50. * @var null|array<string, array{class-string}>
  51. */
  52. private static ?array $srcClassCases = null;
  53. /**
  54. * @var null|array<string, array{class-string, string}>
  55. */
  56. private static ?array $dataProviderMethodCases = null;
  57. /**
  58. * @var array<class-string, Tokens>
  59. */
  60. private static array $tokensCache = [];
  61. public static function tearDownAfterClass(): void
  62. {
  63. self::$srcClassCases = null;
  64. self::$testClassCases = null;
  65. self::$tokensCache = [];
  66. }
  67. /**
  68. * @dataProvider provideThatSrcClassHaveTestClassCases
  69. */
  70. public function testThatSrcClassHaveTestClass(string $className): void
  71. {
  72. $testClassName = 'PhpCsFixer\Tests'.substr($className, 10).'Test';
  73. self::assertTrue(class_exists($testClassName), \sprintf('Expected test class "%s" for "%s" not found.', $testClassName, $className));
  74. }
  75. /**
  76. * @dataProvider provideThatSrcClassesNotAbuseInterfacesCases
  77. *
  78. * @param class-string $className
  79. */
  80. public function testThatSrcClassesNotAbuseInterfaces(string $className): void
  81. {
  82. $rc = new \ReflectionClass($className);
  83. $allowedMethods = array_map(
  84. fn (\ReflectionClass $interface): array => $this->getPublicMethodNames($interface),
  85. $rc->getInterfaces()
  86. );
  87. if (\count($allowedMethods) > 0) {
  88. $allowedMethods = array_unique(array_merge(...array_values($allowedMethods)));
  89. }
  90. $allowedMethods[] = '__construct';
  91. $allowedMethods[] = '__destruct';
  92. $allowedMethods[] = '__wakeup';
  93. $exceptionMethods = [
  94. 'configure', // due to AbstractFixer::configure
  95. 'getConfigurationDefinition', // due to AbstractFixer::getConfigurationDefinition
  96. 'getDefaultConfiguration', // due to AbstractFixer::getDefaultConfiguration
  97. 'setWhitespacesConfig', // due to AbstractFixer::setWhitespacesConfig
  98. 'createConfigurationDefinition', // due to AbstractProxyFixer calling `createConfigurationDefinition` of proxied rule
  99. ];
  100. $definedMethods = $this->getPublicMethodNames($rc);
  101. $extraMethods = array_diff(
  102. $definedMethods,
  103. $allowedMethods,
  104. $exceptionMethods
  105. );
  106. sort($extraMethods);
  107. self::assertEmpty(
  108. $extraMethods,
  109. \sprintf(
  110. "Class '%s' should not have public methods that are not part of implemented interfaces.\nViolations:\n%s",
  111. $className,
  112. implode("\n", array_map(static fn (string $item): string => " * {$item}", $extraMethods))
  113. )
  114. );
  115. }
  116. /**
  117. * @dataProvider provideSrcClassCases
  118. *
  119. * @param class-string $className
  120. */
  121. public function testThatSrcClassesNotExposeProperties(string $className): void
  122. {
  123. $rc = new \ReflectionClass($className);
  124. self::assertEmpty(
  125. $rc->getProperties(\ReflectionProperty::IS_PUBLIC),
  126. \sprintf('Class \'%s\' should not have public properties.', $className)
  127. );
  128. if ($rc->isFinal()) {
  129. return;
  130. }
  131. $allowedProps = [];
  132. $definedProps = $rc->getProperties(\ReflectionProperty::IS_PROTECTED);
  133. if (false !== $rc->getParentClass()) {
  134. $allowedProps = $rc->getParentClass()->getProperties(\ReflectionProperty::IS_PROTECTED);
  135. }
  136. $allowedProps = array_map(static fn (\ReflectionProperty $item): string => $item->getName(), $allowedProps);
  137. $definedProps = array_map(static fn (\ReflectionProperty $item): string => $item->getName(), $definedProps);
  138. $exceptionPropsPerClass = [
  139. AbstractFixer::class => ['configuration', 'configurationDefinition', 'whitespacesConfig'],
  140. AbstractPhpdocToTypeDeclarationFixer::class => ['configuration'],
  141. AbstractPhpdocTypesFixer::class => ['tags'],
  142. AbstractProxyFixer::class => ['proxyFixers'],
  143. ConfigurableFixerTrait::class => ['configuration'],
  144. FixCommand::class => ['defaultDescription', 'defaultName'], // TODO: PHP 8.0+, remove properties and test when PHP 8+ is required
  145. ];
  146. $extraProps = array_diff(
  147. $definedProps,
  148. $allowedProps,
  149. $exceptionPropsPerClass[$className] ?? []
  150. );
  151. sort($extraProps);
  152. self::assertEmpty(
  153. $extraProps,
  154. \sprintf(
  155. "Class '%s' should not have protected properties.\nViolations:\n%s",
  156. $className,
  157. implode("\n", array_map(static fn (string $item): string => " * {$item}", $extraProps))
  158. )
  159. );
  160. }
  161. /**
  162. * @dataProvider provideTestClassCases
  163. */
  164. public function testThatTestClassExtendsPhpCsFixerTestCaseClass(string $className): void
  165. {
  166. self::assertTrue(is_subclass_of($className, TestCase::class), \sprintf('Expected test class "%s" to be a subclass of "%s".', $className, TestCase::class));
  167. }
  168. /**
  169. * @dataProvider provideTestClassCases
  170. *
  171. * @param class-string<TestCase> $testClassName
  172. */
  173. public function testThatTestClassesAreTraitOrAbstractOrFinal(string $testClassName): void
  174. {
  175. $rc = new \ReflectionClass($testClassName);
  176. self::assertTrue(
  177. $rc->isTrait() || $rc->isAbstract() || $rc->isFinal(),
  178. \sprintf('Test class %s should be trait, abstract or final.', $testClassName)
  179. );
  180. }
  181. /**
  182. * @dataProvider provideTestClassCases
  183. *
  184. * @param class-string<TestCase> $testClassName
  185. */
  186. public function testThatTestClassesAreInternal(string $testClassName): void
  187. {
  188. $rc = new \ReflectionClass($testClassName);
  189. $doc = new DocBlock($rc->getDocComment());
  190. self::assertNotEmpty(
  191. $doc->getAnnotationsOfType('internal'),
  192. \sprintf('Test class %s should have internal annotation.', $testClassName)
  193. );
  194. }
  195. /**
  196. * @dataProvider provideTestClassCases
  197. *
  198. * @param class-string<TestCase> $testClassName
  199. */
  200. public function testThatTestClassesPublicMethodsAreCorrectlyNamed(string $testClassName): void
  201. {
  202. $reflectionClass = new \ReflectionClass($testClassName);
  203. $publicMethods = array_filter(
  204. $reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC),
  205. static fn (\ReflectionMethod $reflectionMethod): bool => $reflectionMethod->getDeclaringClass()->getName() === $reflectionClass->getName()
  206. );
  207. if ([] === $publicMethods) {
  208. $this->expectNotToPerformAssertions(); // no methods to test, all good!
  209. return;
  210. }
  211. foreach ($publicMethods as $method) {
  212. self::assertMatchesRegularExpression(
  213. '/^(test|expect|provide|setUpBeforeClass$|tearDownAfterClass$|__construct$)/',
  214. $method->getName(),
  215. \sprintf('Public method "%s::%s" is not properly named.', $reflectionClass->getName(), $method->getName())
  216. );
  217. }
  218. }
  219. /**
  220. * @dataProvider provideDataProviderMethodCases
  221. *
  222. * @param class-string<TestCase> $testClassName
  223. */
  224. public function testThatTestDataProvidersAreUsed(string $testClassName, string $dataProviderName): void
  225. {
  226. $usedDataProviderMethodNames = [];
  227. foreach ($this->getUsedDataProviderMethodNames($testClassName) as $providerName) {
  228. $usedDataProviderMethodNames[] = $providerName;
  229. }
  230. self::assertContains(
  231. $dataProviderName,
  232. $usedDataProviderMethodNames,
  233. \sprintf('Data provider "%s::%s" is not used.', $testClassName, $dataProviderName),
  234. );
  235. }
  236. /**
  237. * @dataProvider provideDataProviderMethodCases
  238. */
  239. public function testThatTestDataProvidersAreCorrectlyNamed(string $testClassName, string $dataProviderName): void
  240. {
  241. self::assertMatchesRegularExpression('/^provide[A-Z]\S+Cases$/', $dataProviderName, \sprintf(
  242. 'Data provider "%s::%s" is not correctly named.',
  243. $testClassName,
  244. $dataProviderName,
  245. ));
  246. }
  247. /**
  248. * @return iterable<string, array{string, string}>
  249. */
  250. public static function provideDataProviderMethodCases(): iterable
  251. {
  252. if (null === self::$dataProviderMethodCases) {
  253. self::$dataProviderMethodCases = [];
  254. foreach (self::provideTestClassCases() as $testClassName) {
  255. $testClassName = reset($testClassName);
  256. $reflectionClass = new \ReflectionClass($testClassName);
  257. $dataProviderNames = array_filter(
  258. $reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC),
  259. static fn (\ReflectionMethod $reflectionMethod): bool => $reflectionMethod->getDeclaringClass()->getName() === $reflectionClass->getName() && str_starts_with($reflectionMethod->getName(), 'provide')
  260. );
  261. foreach ($dataProviderNames as $dataProviderName) {
  262. self::$dataProviderMethodCases[$testClassName.'::'.$dataProviderName->getName()] = [$testClassName, $dataProviderName->getName()];
  263. }
  264. }
  265. }
  266. yield from self::$dataProviderMethodCases;
  267. }
  268. /**
  269. * @dataProvider provideTestClassCases
  270. *
  271. * @param class-string<TestCase> $testClassName
  272. */
  273. public function testThatTestClassCoversAreCorrect(string $testClassName): void
  274. {
  275. $reflectionClass = new \ReflectionClass($testClassName);
  276. if ($reflectionClass->isAbstract() || $reflectionClass->isInterface()) {
  277. $this->expectNotToPerformAssertions();
  278. return;
  279. }
  280. $doc = $reflectionClass->getDocComment();
  281. self::assertNotFalse($doc);
  282. if (Preg::match('/@coversNothing/', $doc)) {
  283. return;
  284. }
  285. $covers = Preg::matchAll('/@covers (\S*)/', $doc, $matches);
  286. self::assertGreaterThanOrEqual(1, $covers, \sprintf('Missing @covers in PHPDoc of test class "%s".', $testClassName));
  287. array_shift($matches);
  288. /** @var class-string $class */
  289. $class = '\\'.str_replace('PhpCsFixer\Tests\\', 'PhpCsFixer\\', substr($testClassName, 0, -4));
  290. $parentClass = (new \ReflectionClass($class))->getParentClass();
  291. $parentClassName = false === $parentClass ? null : '\\'.$parentClass->getName();
  292. foreach ($matches as $match) {
  293. $classMatch = array_shift($match);
  294. self::assertTrue(
  295. $classMatch === $class || $parentClassName === $classMatch,
  296. \sprintf('Unexpected @covers "%s" for "%s".', $classMatch, $testClassName)
  297. );
  298. }
  299. }
  300. /**
  301. * @dataProvider provideSrcClassCases
  302. * @dataProvider provideTestClassCases
  303. *
  304. * @param class-string $className
  305. */
  306. public function testThereIsNoUsageOfExtract(string $className): void
  307. {
  308. $calledFunctions = $this->extractFunctionNamesCalledInClass($className);
  309. $message = \sprintf('Class %s must not use "extract()", explicitly extract only the keys that are needed - you never know what\'s else inside.', $className);
  310. self::assertNotContains('extract', $calledFunctions, $message);
  311. }
  312. /**
  313. * @dataProvider provideThereIsNoPregFunctionUsedDirectlyCases
  314. *
  315. * @param class-string $className
  316. */
  317. public function testThereIsNoPregFunctionUsedDirectly(string $className): void
  318. {
  319. $calledFunctions = $this->extractFunctionNamesCalledInClass($className);
  320. $message = \sprintf('Class %s must not use preg_*, it shall use Preg::* instead.', $className);
  321. self::assertNotContains('preg_filter', $calledFunctions, $message);
  322. self::assertNotContains('preg_grep', $calledFunctions, $message);
  323. self::assertNotContains('preg_match', $calledFunctions, $message);
  324. self::assertNotContains('preg_match_all', $calledFunctions, $message);
  325. self::assertNotContains('preg_replace', $calledFunctions, $message);
  326. self::assertNotContains('preg_replace_callback', $calledFunctions, $message);
  327. self::assertNotContains('preg_split', $calledFunctions, $message);
  328. }
  329. /**
  330. * @dataProvider provideTestClassCases
  331. *
  332. * @param class-string $className
  333. */
  334. public function testThereIsNoUsageOfSetAccessible(string $className): void
  335. {
  336. $calledFunctions = $this->extractFunctionNamesCalledInClass($className);
  337. $message = \sprintf('Class %s must not use "setAccessible()", use "Closure::bind()" instead.', $className);
  338. self::assertNotContains('setAccessible', $calledFunctions, $message);
  339. }
  340. /**
  341. * @dataProvider provideTestClassCases
  342. *
  343. * @param class-string<TestCase> $className
  344. */
  345. public function testNoPHPUnitMockUsed(string $className): void
  346. {
  347. $calledFunctions = $this->extractFunctionNamesCalledInClass($className);
  348. $message = \sprintf('Class %s must not use PHPUnit\'s mock, it shall use anonymous class instead.', $className);
  349. self::assertNotContains('getMockBuilder', $calledFunctions, $message);
  350. self::assertNotContains('createMock', $calledFunctions, $message);
  351. self::assertNotContains('createMockForIntersectionOfInterfaces', $calledFunctions, $message);
  352. self::assertNotContains('createPartialMock', $calledFunctions, $message);
  353. self::assertNotContains('createTestProxy', $calledFunctions, $message);
  354. self::assertNotContains('getMockForAbstractClass', $calledFunctions, $message);
  355. self::assertNotContains('getMockFromWsdl', $calledFunctions, $message);
  356. self::assertNotContains('getMockForTrait', $calledFunctions, $message);
  357. self::assertNotContains('getMockClass', $calledFunctions, $message);
  358. self::assertNotContains('createConfiguredMock', $calledFunctions, $message);
  359. self::assertNotContains('getObjectForTrait', $calledFunctions, $message);
  360. }
  361. /**
  362. * @dataProvider provideTestClassCases
  363. *
  364. * @param class-string<TestCase> $testClassName
  365. */
  366. public function testExpectedInputOrder(string $testClassName): void
  367. {
  368. $reflectionClass = new \ReflectionClass($testClassName);
  369. $publicMethods = array_filter(
  370. $reflectionClass->getMethods(\ReflectionMethod::IS_PUBLIC),
  371. static fn (\ReflectionMethod $reflectionMethod): bool => $reflectionMethod->getDeclaringClass()->getName() === $reflectionClass->getName()
  372. );
  373. if ([] === $publicMethods) {
  374. $this->expectNotToPerformAssertions(); // no methods to test, all good!
  375. return;
  376. }
  377. /** @var \ReflectionMethod $method */
  378. foreach ($publicMethods as $method) {
  379. $parameters = $method->getParameters();
  380. if (\count($parameters) < 2) {
  381. $this->addToAssertionCount(1); // not enough parameters to test, all good!
  382. continue;
  383. }
  384. $expected = [
  385. 'expected' => false,
  386. 'input' => false,
  387. ];
  388. for ($i = \count($parameters) - 1; $i >= 0; --$i) {
  389. $name = $parameters[$i]->getName();
  390. if (isset($expected[$name])) {
  391. $expected[$name] = $i;
  392. }
  393. }
  394. $expectedFound = array_filter($expected, static fn ($item): bool => false !== $item);
  395. if (\count($expectedFound) < 2) {
  396. $this->addToAssertionCount(1); // not enough parameters to test, all good!
  397. continue;
  398. }
  399. self::assertLessThan(
  400. $expected['input'],
  401. $expected['expected'],
  402. \sprintf('Public method "%s::%s" has parameter \'input\' before \'expected\'.', $reflectionClass->getName(), $method->getName())
  403. );
  404. }
  405. }
  406. /**
  407. * @dataProvider provideDataProviderMethodCases
  408. *
  409. * @param class-string<TestCase> $testClassName
  410. * @param non-empty-string $dataProviderName
  411. */
  412. public function testDataProvidersAreNonPhpVersionConditional(string $testClassName, string $dataProviderName): void
  413. {
  414. $tokens = $this->createTokensForClass($testClassName);
  415. $tokensAnalyzer = new TokensAnalyzer($tokens);
  416. $dataProviderElements = array_filter($tokensAnalyzer->getClassyElements(), static function (array $v, int $k) use ($tokens, $dataProviderName) {
  417. $nextToken = $tokens[$tokens->getNextMeaningfulToken($k)];
  418. // element is data provider method
  419. return 'method' === $v['type'] && $nextToken->equals([T_STRING, $dataProviderName]);
  420. }, ARRAY_FILTER_USE_BOTH);
  421. if (1 !== \count($dataProviderElements)) {
  422. throw new \UnexpectedValueException(\sprintf('Data provider "%s::%s" should be found exactly once, got %d times.', $testClassName, $dataProviderName, \count($dataProviderElements)));
  423. }
  424. $methodIndex = array_key_first($dataProviderElements);
  425. $startIndex = $tokens->getNextTokenOfKind($methodIndex, ['{']);
  426. $endIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $startIndex);
  427. $versionTokens = array_filter($tokens->findGivenKind(T_STRING, $startIndex, $endIndex), static function (Token $v): bool {
  428. return $v->equalsAny([
  429. [T_STRING, 'PHP_VERSION_ID'],
  430. [T_STRING, 'PHP_MAJOR_VERSION'],
  431. [T_STRING, 'PHP_MINOR_VERSION'],
  432. [T_STRING, 'PHP_RELEASE_VERSION'],
  433. [T_STRING, 'phpversion'],
  434. ], false);
  435. });
  436. self::assertCount(
  437. 0,
  438. $versionTokens,
  439. \sprintf(
  440. 'Data provider "%s::%s" should not check PHP version and provide different cases depends on it. It leads to situation when DataProvider provides "sometimes 10, sometimes 11" test cases, depends on PHP version. That makes John Doe to see "you run 10/10" and thinking all tests are executed, instead of actually seeing "you run 10/11 and 1 skipped".',
  441. $testClassName,
  442. $dataProviderName,
  443. ),
  444. );
  445. }
  446. /**
  447. * @dataProvider provideDataProviderMethodCases
  448. */
  449. public function testDataProvidersDeclaredReturnType(string $testClassName, string $dataProviderName): void
  450. {
  451. $dataProvider = new \ReflectionMethod($testClassName, $dataProviderName);
  452. self::assertSame('iterable', $dataProvider->hasReturnType() && $dataProvider->getReturnType() instanceof \ReflectionNamedType ? $dataProvider->getReturnType()->getName() : null, \sprintf('Data provider "%s::%s" must provide `iterable` as return in method prototype.', $testClassName, $dataProviderName));
  453. $doc = new DocBlock(false !== $dataProvider->getDocComment() ? $dataProvider->getDocComment() : '/** */');
  454. $returnDocs = $doc->getAnnotationsOfType('return');
  455. if (\count($returnDocs) > 1) {
  456. throw new \UnexpectedValueException(\sprintf('Multiple "%s::%s@return" annotations.', $testClassName, $dataProviderName));
  457. }
  458. if (1 !== \count($returnDocs)) {
  459. $this->addToAssertionCount(1); // no @return annotation, all good!
  460. return;
  461. }
  462. $returnDoc = $returnDocs[0];
  463. $types = $returnDoc->getTypes();
  464. self::assertCount(1, $types, \sprintf('Data provider "%s::%s@return" must provide single type.', $testClassName, $dataProviderName));
  465. self::assertMatchesRegularExpression('/^iterable\</', $types[0], \sprintf('Data provider "%s::%s@return" must return iterable.', $testClassName, $dataProviderName));
  466. self::assertMatchesRegularExpression('/^iterable\<(?:(?:int\|)?string, )?array\{/', $types[0], \sprintf('Data provider "%s::%s@return" must return iterable of tuples (eg `iterable<string, array{string, string}>`).', $testClassName, $dataProviderName));
  467. }
  468. /**
  469. * @dataProvider provideSrcClassCases
  470. * @dataProvider provideTestClassCases
  471. *
  472. * @param class-string $className
  473. */
  474. public function testAllCodeContainSingleClassy(string $className): void
  475. {
  476. $headerTypes = [
  477. T_ABSTRACT,
  478. T_AS,
  479. T_COMMENT,
  480. T_DECLARE,
  481. T_DOC_COMMENT,
  482. T_FINAL,
  483. T_LNUMBER,
  484. T_NAMESPACE,
  485. T_NS_SEPARATOR,
  486. T_OPEN_TAG,
  487. T_STRING,
  488. T_USE,
  489. T_WHITESPACE,
  490. ];
  491. $tokens = $this->createTokensForClass($className);
  492. $classyIndex = null;
  493. self::assertTrue($tokens->isAnyTokenKindsFound(Token::getClassyTokenKinds()), \sprintf('File for "%s" should contains a classy.', $className));
  494. $count = \count($tokens);
  495. for ($index = 1; $index < $count; ++$index) {
  496. if ($tokens[$index]->isClassy()) {
  497. $classyIndex = $index;
  498. break;
  499. }
  500. if (\defined('T_ATTRIBUTE') && $tokens[$index]->isGivenKind(T_ATTRIBUTE)) {
  501. $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ATTRIBUTE, $index);
  502. continue;
  503. }
  504. if (!$tokens[$index]->isGivenKind($headerTypes) && !$tokens[$index]->equalsAny([';', '=', '(', ')'])) {
  505. self::fail(\sprintf('File for "%s" should only contains single classy, found "%s" @ %d.', $className, $tokens[$index]->toJson(), $index));
  506. }
  507. }
  508. self::assertNotNull($classyIndex, \sprintf('File for "%s" does not contain a classy.', $className));
  509. $nextTokenOfKind = $tokens->getNextTokenOfKind($classyIndex, ['{']);
  510. if (!\is_int($nextTokenOfKind)) {
  511. throw new \UnexpectedValueException('Classy without {} - braces.');
  512. }
  513. $classyEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $nextTokenOfKind);
  514. self::assertNull($tokens->getNextMeaningfulToken($classyEndIndex), \sprintf('File for "%s" should only contains a single classy.', $className));
  515. }
  516. /**
  517. * @dataProvider provideSrcClassCases
  518. *
  519. * @param class-string $className
  520. */
  521. public function testInheritdocIsNotAbused(string $className): void
  522. {
  523. $rc = new \ReflectionClass($className);
  524. $allowedMethods = array_map(
  525. fn (\ReflectionClass $interface): array => $this->getPublicMethodNames($interface),
  526. $rc->getInterfaces()
  527. );
  528. if (\count($allowedMethods) > 0) {
  529. $allowedMethods = array_merge(...array_values($allowedMethods));
  530. }
  531. $parentClass = $rc;
  532. while (false !== $parentClass = $parentClass->getParentClass()) {
  533. foreach ($parentClass->getMethods(\ReflectionMethod::IS_PUBLIC | \ReflectionMethod::IS_PROTECTED) as $method) {
  534. $allowedMethods[] = $method->getName();
  535. }
  536. }
  537. $allowedMethods = array_unique($allowedMethods);
  538. $methodsWithInheritdoc = array_filter(
  539. $rc->getMethods(),
  540. static fn (\ReflectionMethod $rm): bool => false !== $rm->getDocComment() && stripos($rm->getDocComment(), '@inheritdoc')
  541. );
  542. $methodsWithInheritdoc = array_map(
  543. static fn (\ReflectionMethod $rm): string => $rm->getName(),
  544. $methodsWithInheritdoc
  545. );
  546. $extraMethods = array_diff($methodsWithInheritdoc, $allowedMethods);
  547. self::assertEmpty(
  548. $extraMethods,
  549. \sprintf(
  550. "Class '%s' should not have methods with '@inheritdoc' in PHPDoc that are not inheriting PHPDoc.\nViolations:\n%s",
  551. $className,
  552. implode("\n", array_map(static fn ($item): string => " * {$item}", $extraMethods))
  553. )
  554. );
  555. }
  556. /**
  557. * @return iterable<string, array{class-string}>
  558. */
  559. public static function provideSrcClassCases(): iterable
  560. {
  561. if (null === self::$srcClassCases) {
  562. $cases = self::getSrcClasses();
  563. self::$srcClassCases = array_combine(
  564. $cases,
  565. array_map(static fn (string $case): array => [$case], $cases),
  566. );
  567. }
  568. yield from self::$srcClassCases;
  569. }
  570. /**
  571. * @return iterable<array{string}>
  572. */
  573. public static function provideThatSrcClassesNotAbuseInterfacesCases(): iterable
  574. {
  575. return array_map(
  576. static fn (string $item): array => [$item],
  577. array_filter(self::getSrcClasses(), static function (string $className): bool {
  578. $rc = new \ReflectionClass($className);
  579. $doc = false !== $rc->getDocComment()
  580. ? new DocBlock($rc->getDocComment())
  581. : null;
  582. if (
  583. $rc->isInterface()
  584. || (null !== $doc && \count($doc->getAnnotationsOfType('internal')) > 0)
  585. || \in_array($className, [
  586. \PhpCsFixer\Finder::class,
  587. AbstractFixerTestCase::class,
  588. AbstractIntegrationTestCase::class,
  589. Tokens::class,
  590. ], true)
  591. ) {
  592. return false;
  593. }
  594. $interfaces = $rc->getInterfaces();
  595. $interfacesCount = \count($interfaces);
  596. if (0 === $interfacesCount) {
  597. return false;
  598. }
  599. if (1 === $interfacesCount) {
  600. $interface = reset($interfaces);
  601. if (\Stringable::class === $interface->getName()) {
  602. return false;
  603. }
  604. }
  605. return true;
  606. })
  607. );
  608. }
  609. /**
  610. * @return iterable<array{string}>
  611. */
  612. public static function provideThatSrcClassHaveTestClassCases(): iterable
  613. {
  614. return array_map(
  615. static fn (string $item): array => [$item],
  616. array_filter(
  617. self::getSrcClasses(),
  618. static function (string $className): bool {
  619. $rc = new \ReflectionClass($className);
  620. return !$rc->isTrait() && !$rc->isAbstract() && !$rc->isInterface() && \count($rc->getMethods(\ReflectionMethod::IS_PUBLIC)) > 0;
  621. }
  622. )
  623. );
  624. }
  625. public function testAllTestsForShortOpenTagAreHandled(): void
  626. {
  627. $testClassesWithShortOpenTag = array_filter(
  628. self::getTestClasses(),
  629. fn (string $className): bool => str_contains($this->getFileContentForClass($className), 'short_open_tag') && self::class !== $className
  630. );
  631. $testFilesWithShortOpenTag = array_map(
  632. fn (string $className): string => './'.$this->getFilePathForClass($className),
  633. $testClassesWithShortOpenTag
  634. );
  635. $phpunitXmlContent = file_get_contents(__DIR__.'/../../phpunit.xml.dist');
  636. $phpunitFiles = (array) simplexml_load_string($phpunitXmlContent)->xpath('testsuites/testsuite[@name="short-open-tag"]')[0]->file;
  637. sort($testFilesWithShortOpenTag);
  638. sort($phpunitFiles);
  639. self::assertSame($testFilesWithShortOpenTag, $phpunitFiles);
  640. }
  641. /**
  642. * @dataProvider provideTestClassCases
  643. *
  644. * @param class-string $className
  645. */
  646. public function testThatTestMethodsAreNotDuplicated(string $className): void
  647. {
  648. $class = new \ReflectionClass($className);
  649. $alreadyFoundMethods = [];
  650. $duplicates = [];
  651. foreach ($class->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
  652. if (!str_starts_with($method->getName(), 'test')) {
  653. continue;
  654. }
  655. $startLine = (int) $method->getStartLine();
  656. $length = (int) $method->getEndLine() - $startLine;
  657. if (3 === $length) { // open and closing brace are included - this checks for single line methods
  658. continue;
  659. }
  660. /** @var list<string> $source */
  661. $source = file((string) $method->getFileName());
  662. $candidateContent = implode('', \array_slice($source, $startLine, $length));
  663. if (str_contains($candidateContent, '$this->doTest(')) {
  664. continue;
  665. }
  666. $foundInDuplicates = false;
  667. foreach ($alreadyFoundMethods as $methodKey => $methodContent) {
  668. if ($candidateContent === $methodContent) {
  669. $duplicates[] = \sprintf('%s is duplicate of %s', $methodKey, $method->getName());
  670. $foundInDuplicates = true;
  671. }
  672. }
  673. if (!$foundInDuplicates) {
  674. $alreadyFoundMethods[$method->getName()] = $candidateContent;
  675. }
  676. }
  677. self::assertSame(
  678. [],
  679. $duplicates,
  680. \sprintf(
  681. "Duplicated methods found in %s:\n - %s",
  682. $className,
  683. implode("\n - ", $duplicates)
  684. )
  685. );
  686. }
  687. /**
  688. * @dataProvider provideDataProviderMethodCases
  689. *
  690. * @param class-string<TestCase> $testClassName
  691. */
  692. public function testThatDataFromDataProvidersIsNotDuplicated(string $testClassName, string $dataProviderName): void
  693. {
  694. $exceptions = [ // should only shrink
  695. 'PhpCsFixer\Tests\AutoReview\CommandTest::provideCommandHasNameConstCases',
  696. 'PhpCsFixer\Tests\AutoReview\DocumentationTest::provideFixerDocumentationFileIsUpToDateCases',
  697. 'PhpCsFixer\Tests\AutoReview\FixerFactoryTest::providePriorityIntegrationTestFilesAreListedInPriorityGraphCases',
  698. 'PhpCsFixer\Tests\Console\Command\DescribeCommandTest::provideExecuteOutputCases',
  699. 'PhpCsFixer\Tests\Console\Command\HelpCommandTest::provideGetDisplayableAllowedValuesCases',
  700. 'PhpCsFixer\Tests\Documentation\FixerDocumentGeneratorTest::provideGenerateRuleSetsDocumentationCases',
  701. 'PhpCsFixer\Tests\Fixer\Basic\EncodingFixerTest::provideFixCases',
  702. 'PhpCsFixer\Tests\UtilsTest::provideStableSortCases',
  703. ];
  704. if (\in_array($testClassName.'::'.$dataProviderName, $exceptions, true)) {
  705. $this->addToAssertionCount(1);
  706. return;
  707. }
  708. $dataProvider = new \ReflectionMethod($testClassName, $dataProviderName);
  709. $duplicates = [];
  710. $alreadyFoundCases = [];
  711. foreach ($dataProvider->invoke($dataProvider->getDeclaringClass()->newInstanceWithoutConstructor()) as $candidateKey => $candidateData) {
  712. $candidateData = serialize($candidateData);
  713. $foundInDuplicates = false;
  714. foreach ($alreadyFoundCases as $caseKey => $caseData) {
  715. if ($candidateData === $caseData) {
  716. $duplicates[] = \sprintf(
  717. 'Duplicate in %s::%s: %s and %s.'.PHP_EOL,
  718. $testClassName,
  719. $dataProviderName,
  720. \is_int($caseKey) ? '#'.$caseKey : '"'.$caseKey.'"',
  721. \is_int($candidateKey) ? '#'.$candidateKey : '"'.$candidateKey.'"',
  722. );
  723. $foundInDuplicates = true;
  724. }
  725. }
  726. if (!$foundInDuplicates) {
  727. $alreadyFoundCases[$candidateKey] = $candidateData;
  728. }
  729. }
  730. self::assertSame([], $duplicates);
  731. }
  732. /**
  733. * @return iterable<string, array{class-string<TestCase>}>
  734. */
  735. public static function provideTestClassCases(): iterable
  736. {
  737. if (null === self::$testClassCases) {
  738. $cases = self::getTestClasses();
  739. self::$testClassCases = array_combine(
  740. $cases,
  741. array_map(static fn (string $case): array => [$case], $cases),
  742. );
  743. }
  744. yield from self::$testClassCases;
  745. }
  746. /**
  747. * @return iterable<array{string}>
  748. */
  749. public static function provideThereIsNoPregFunctionUsedDirectlyCases(): iterable
  750. {
  751. return array_map(
  752. static fn (string $item): array => [$item],
  753. array_filter(
  754. self::getSrcClasses(),
  755. static fn (string $className): bool => Preg::class !== $className,
  756. ),
  757. );
  758. }
  759. /**
  760. * @dataProvider providePhpUnitFixerExtendsAbstractPhpUnitFixerCases
  761. *
  762. * @param class-string $className
  763. */
  764. public function testPhpUnitFixerExtendsAbstractPhpUnitFixer(string $className): void
  765. {
  766. $reflection = new \ReflectionClass($className);
  767. self::assertTrue($reflection->isSubclassOf(AbstractPhpUnitFixer::class));
  768. }
  769. /**
  770. * @return iterable<array{string}>
  771. */
  772. public static function providePhpUnitFixerExtendsAbstractPhpUnitFixerCases(): iterable
  773. {
  774. $factory = new FixerFactory();
  775. $factory->registerBuiltInFixers();
  776. foreach ($factory->getFixers() as $fixer) {
  777. if (!str_starts_with($fixer->getName(), 'php_unit_')) {
  778. continue;
  779. }
  780. // this one fixes usage of PHPUnit classes
  781. if ($fixer instanceof PhpUnitNamespacedFixer) {
  782. continue;
  783. }
  784. if ($fixer instanceof AbstractProxyFixer) {
  785. continue;
  786. }
  787. yield [\get_class($fixer)];
  788. }
  789. }
  790. /**
  791. * @dataProvider provideSrcClassCases
  792. * @dataProvider provideTestClassCases
  793. *
  794. * @param class-string $className
  795. */
  796. public function testConstantsAreInUpperCase(string $className): void
  797. {
  798. $rc = new \ReflectionClass($className);
  799. $reflectionClassConstants = $rc->getReflectionConstants();
  800. if (\count($reflectionClassConstants) < 1) {
  801. $this->expectNotToPerformAssertions();
  802. return;
  803. }
  804. foreach ($reflectionClassConstants as $constant) {
  805. $constantName = $constant->getName();
  806. self::assertSame(strtoupper($constantName), $constantName, $className);
  807. }
  808. }
  809. /**
  810. * @param class-string $className
  811. *
  812. * @return list<string>
  813. */
  814. private function extractFunctionNamesCalledInClass(string $className): array
  815. {
  816. $tokens = $this->createTokensForClass($className);
  817. $stringTokens = array_filter(
  818. $tokens->toArray(),
  819. static fn (Token $token): bool => $token->isGivenKind(T_STRING)
  820. );
  821. $strings = array_map(
  822. static fn (Token $token): string => $token->getContent(),
  823. $stringTokens
  824. );
  825. return array_unique($strings);
  826. }
  827. /**
  828. * @param class-string $className
  829. */
  830. private function getFilePathForClass(string $className): string
  831. {
  832. $file = $className;
  833. $file = preg_replace('#^PhpCsFixer\\\Tests\\\#', 'tests\\', $file);
  834. $file = preg_replace('#^PhpCsFixer\\\#', 'src\\', $file);
  835. return str_replace('\\', \DIRECTORY_SEPARATOR, $file).'.php';
  836. }
  837. /**
  838. * @param class-string $className
  839. */
  840. private function getFileContentForClass(string $className): string
  841. {
  842. return file_get_contents($this->getFilePathForClass($className));
  843. }
  844. /**
  845. * @param class-string $className
  846. */
  847. private function createTokensForClass(string $className): Tokens
  848. {
  849. if (!isset(self::$tokensCache[$className])) {
  850. self::$tokensCache[$className] = Tokens::fromCode(self::getFileContentForClass($className));
  851. }
  852. return self::$tokensCache[$className];
  853. }
  854. /**
  855. * @param class-string<TestCase> $testClassName
  856. *
  857. * @return iterable<string, string>
  858. */
  859. private function getUsedDataProviderMethodNames(string $testClassName): iterable
  860. {
  861. foreach ($this->getAnnotationsOfTestClass($testClassName, 'dataProvider') as $methodName => $dataProviderAnnotation) {
  862. if (1 === preg_match('/@dataProvider\s+(?P<methodName>\w+)/', $dataProviderAnnotation->getContent(), $matches)) {
  863. yield $methodName => $matches['methodName'];
  864. }
  865. }
  866. }
  867. /**
  868. * @param class-string<TestCase> $testClassName
  869. *
  870. * @return iterable<string, Annotation>
  871. */
  872. private function getAnnotationsOfTestClass(string $testClassName, string $annotation): iterable
  873. {
  874. $tokens = $this->createTokensForClass($testClassName);
  875. foreach ($tokens as $index => $token) {
  876. if (!$token->isGivenKind(T_DOC_COMMENT)) {
  877. continue;
  878. }
  879. $methodName = $tokens[$tokens->getNextTokenOfKind($index, [[T_STRING]])]->getContent();
  880. $docBlock = new DocBlock($token->getContent());
  881. $dataProviderAnnotations = $docBlock->getAnnotationsOfType($annotation);
  882. foreach ($dataProviderAnnotations as $dataProviderAnnotation) {
  883. yield $methodName => $dataProviderAnnotation;
  884. }
  885. }
  886. }
  887. /**
  888. * @return list<class-string>
  889. */
  890. private static function getSrcClasses(): array
  891. {
  892. static $classes;
  893. if (null !== $classes) {
  894. return $classes;
  895. }
  896. $finder = Finder::create()
  897. ->files()
  898. ->name('*.php')
  899. ->in(__DIR__.'/../../src')
  900. ->exclude([
  901. 'Resources',
  902. ])
  903. ;
  904. /** @var list<class-string> $classes */
  905. $classes = array_map(
  906. static fn (SplFileInfo $file): string => \sprintf(
  907. '%s\%s%s%s',
  908. 'PhpCsFixer',
  909. strtr($file->getRelativePath(), \DIRECTORY_SEPARATOR, '\\'),
  910. '' !== $file->getRelativePath() ? '\\' : '',
  911. $file->getBasename('.'.$file->getExtension())
  912. ),
  913. iterator_to_array($finder, false)
  914. );
  915. sort($classes);
  916. return $classes;
  917. }
  918. /**
  919. * @return list<class-string<TestCase>>
  920. */
  921. private static function getTestClasses(): array
  922. {
  923. static $classes;
  924. if (null !== $classes) {
  925. return $classes;
  926. }
  927. $finder = Finder::create()
  928. ->files()
  929. ->name('*Test.php')
  930. ->in(__DIR__.'/..')
  931. ->exclude([
  932. 'Fixtures',
  933. ])
  934. ;
  935. /** @var list<class-string<TestCase>> $classes */
  936. $classes = array_map(
  937. static fn (SplFileInfo $file): string => \sprintf(
  938. 'PhpCsFixer\Tests\%s%s%s',
  939. strtr($file->getRelativePath(), \DIRECTORY_SEPARATOR, '\\'),
  940. '' !== $file->getRelativePath() ? '\\' : '',
  941. $file->getBasename('.'.$file->getExtension())
  942. ),
  943. iterator_to_array($finder, false)
  944. );
  945. sort($classes);
  946. return $classes;
  947. }
  948. /**
  949. * @param \ReflectionClass<object> $rc
  950. *
  951. * @return list<string>
  952. */
  953. private function getPublicMethodNames(\ReflectionClass $rc): array
  954. {
  955. return array_map(
  956. static fn (\ReflectionMethod $rm): string => $rm->getName(),
  957. $rc->getMethods(\ReflectionMethod::IS_PUBLIC)
  958. );
  959. }
  960. }