ProjectCodeTest.php 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152
  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 fn (Token $v): bool => $v->equalsAny([
  428. [T_STRING, 'PHP_VERSION_ID'],
  429. [T_STRING, 'PHP_MAJOR_VERSION'],
  430. [T_STRING, 'PHP_MINOR_VERSION'],
  431. [T_STRING, 'PHP_RELEASE_VERSION'],
  432. [T_STRING, 'phpversion'],
  433. ], false));
  434. self::assertCount(
  435. 0,
  436. $versionTokens,
  437. \sprintf(
  438. '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".',
  439. $testClassName,
  440. $dataProviderName,
  441. ),
  442. );
  443. }
  444. /**
  445. * @dataProvider provideDataProviderMethodCases
  446. */
  447. public function testDataProvidersDeclaredReturnType(string $testClassName, string $dataProviderName): void
  448. {
  449. $dataProvider = new \ReflectionMethod($testClassName, $dataProviderName);
  450. 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));
  451. $doc = new DocBlock(false !== $dataProvider->getDocComment() ? $dataProvider->getDocComment() : '/** */');
  452. $returnDocs = $doc->getAnnotationsOfType('return');
  453. if (\count($returnDocs) > 1) {
  454. throw new \UnexpectedValueException(\sprintf('Multiple "%s::%s@return" annotations.', $testClassName, $dataProviderName));
  455. }
  456. if (1 !== \count($returnDocs)) {
  457. $this->addToAssertionCount(1); // no @return annotation, all good!
  458. return;
  459. }
  460. $returnDoc = $returnDocs[0];
  461. $types = $returnDoc->getTypes();
  462. self::assertCount(1, $types, \sprintf('Data provider "%s::%s@return" must provide single type.', $testClassName, $dataProviderName));
  463. self::assertMatchesRegularExpression('/^iterable\</', $types[0], \sprintf('Data provider "%s::%s@return" must return iterable.', $testClassName, $dataProviderName));
  464. 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));
  465. }
  466. /**
  467. * @dataProvider provideSrcClassCases
  468. * @dataProvider provideTestClassCases
  469. *
  470. * @param class-string $className
  471. */
  472. public function testAllCodeContainSingleClassy(string $className): void
  473. {
  474. $headerTypes = [
  475. T_ABSTRACT,
  476. T_AS,
  477. T_COMMENT,
  478. T_DECLARE,
  479. T_DOC_COMMENT,
  480. T_FINAL,
  481. T_LNUMBER,
  482. T_NAMESPACE,
  483. T_NS_SEPARATOR,
  484. T_OPEN_TAG,
  485. T_STRING,
  486. T_USE,
  487. T_WHITESPACE,
  488. ];
  489. if (\defined('T_READONLY')) { // @TODO: drop condition when PHP 8.1+ is required
  490. $headerTypes[] = T_READONLY;
  491. }
  492. $tokens = $this->createTokensForClass($className);
  493. $classyIndex = null;
  494. self::assertTrue($tokens->isAnyTokenKindsFound(Token::getClassyTokenKinds()), \sprintf('File for "%s" should contains a classy.', $className));
  495. $count = \count($tokens);
  496. for ($index = 1; $index < $count; ++$index) {
  497. if ($tokens[$index]->isClassy()) {
  498. $classyIndex = $index;
  499. break;
  500. }
  501. if (\defined('T_ATTRIBUTE') && $tokens[$index]->isGivenKind(T_ATTRIBUTE)) {
  502. $index = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_ATTRIBUTE, $index);
  503. continue;
  504. }
  505. if (!$tokens[$index]->isGivenKind($headerTypes) && !$tokens[$index]->equalsAny([';', '=', '(', ')'])) {
  506. self::fail(\sprintf('File for "%s" should only contains single classy, found "%s" @ %d.', $className, $tokens[$index]->toJson(), $index));
  507. }
  508. }
  509. self::assertNotNull($classyIndex, \sprintf('File for "%s" does not contain a classy.', $className));
  510. $nextTokenOfKind = $tokens->getNextTokenOfKind($classyIndex, ['{']);
  511. if (!\is_int($nextTokenOfKind)) {
  512. throw new \UnexpectedValueException('Classy without {} - braces.');
  513. }
  514. $classyEndIndex = $tokens->findBlockEnd(Tokens::BLOCK_TYPE_CURLY_BRACE, $nextTokenOfKind);
  515. self::assertNull($tokens->getNextMeaningfulToken($classyEndIndex), \sprintf('File for "%s" should only contains a single classy.', $className));
  516. }
  517. /**
  518. * @dataProvider provideSrcClassCases
  519. *
  520. * @param class-string $className
  521. */
  522. public function testInheritdocIsNotAbused(string $className): void
  523. {
  524. $rc = new \ReflectionClass($className);
  525. $allowedMethods = array_map(
  526. fn (\ReflectionClass $interface): array => $this->getPublicMethodNames($interface),
  527. $rc->getInterfaces()
  528. );
  529. if (\count($allowedMethods) > 0) {
  530. $allowedMethods = array_merge(...array_values($allowedMethods));
  531. }
  532. $parentClass = $rc;
  533. while (false !== $parentClass = $parentClass->getParentClass()) {
  534. foreach ($parentClass->getMethods(\ReflectionMethod::IS_PUBLIC | \ReflectionMethod::IS_PROTECTED) as $method) {
  535. $allowedMethods[] = $method->getName();
  536. }
  537. }
  538. $allowedMethods = array_unique($allowedMethods);
  539. $methodsWithInheritdoc = array_filter(
  540. $rc->getMethods(),
  541. static fn (\ReflectionMethod $rm): bool => false !== $rm->getDocComment() && stripos($rm->getDocComment(), '@inheritdoc')
  542. );
  543. $methodsWithInheritdoc = array_map(
  544. static fn (\ReflectionMethod $rm): string => $rm->getName(),
  545. $methodsWithInheritdoc
  546. );
  547. $extraMethods = array_diff($methodsWithInheritdoc, $allowedMethods);
  548. self::assertEmpty(
  549. $extraMethods,
  550. \sprintf(
  551. "Class '%s' should not have methods with '@inheritdoc' in PHPDoc that are not inheriting PHPDoc.\nViolations:\n%s",
  552. $className,
  553. implode("\n", array_map(static fn ($item): string => " * {$item}", $extraMethods))
  554. )
  555. );
  556. }
  557. /**
  558. * @return iterable<string, array{class-string}>
  559. */
  560. public static function provideSrcClassCases(): iterable
  561. {
  562. if (null === self::$srcClassCases) {
  563. $cases = self::getSrcClasses();
  564. self::$srcClassCases = array_combine(
  565. $cases,
  566. array_map(static fn (string $case): array => [$case], $cases),
  567. );
  568. }
  569. yield from self::$srcClassCases;
  570. }
  571. /**
  572. * @return iterable<array{string}>
  573. */
  574. public static function provideThatSrcClassesNotAbuseInterfacesCases(): iterable
  575. {
  576. return array_map(
  577. static fn (string $item): array => [$item],
  578. array_filter(self::getSrcClasses(), static function (string $className): bool {
  579. $rc = new \ReflectionClass($className);
  580. $doc = false !== $rc->getDocComment()
  581. ? new DocBlock($rc->getDocComment())
  582. : null;
  583. if (
  584. $rc->isInterface()
  585. || (null !== $doc && \count($doc->getAnnotationsOfType('internal')) > 0)
  586. || \in_array($className, [
  587. \PhpCsFixer\Finder::class,
  588. AbstractFixerTestCase::class,
  589. AbstractIntegrationTestCase::class,
  590. Tokens::class,
  591. ], true)
  592. ) {
  593. return false;
  594. }
  595. $interfaces = $rc->getInterfaces();
  596. $interfacesCount = \count($interfaces);
  597. if (0 === $interfacesCount) {
  598. return false;
  599. }
  600. if (1 === $interfacesCount) {
  601. $interface = reset($interfaces);
  602. if (\Stringable::class === $interface->getName()) {
  603. return false;
  604. }
  605. }
  606. return true;
  607. })
  608. );
  609. }
  610. /**
  611. * @return iterable<array{string}>
  612. */
  613. public static function provideThatSrcClassHaveTestClassCases(): iterable
  614. {
  615. return array_map(
  616. static fn (string $item): array => [$item],
  617. array_filter(
  618. self::getSrcClasses(),
  619. static function (string $className): bool {
  620. $rc = new \ReflectionClass($className);
  621. return !$rc->isTrait() && !$rc->isAbstract() && !$rc->isInterface() && \count($rc->getMethods(\ReflectionMethod::IS_PUBLIC)) > 0;
  622. }
  623. )
  624. );
  625. }
  626. public function testAllTestsForShortOpenTagAreHandled(): void
  627. {
  628. $testClassesWithShortOpenTag = array_filter(
  629. self::getTestClasses(),
  630. fn (string $className): bool => str_contains($this->getFileContentForClass($className), 'short_open_tag') && self::class !== $className
  631. );
  632. $testFilesWithShortOpenTag = array_map(
  633. fn (string $className): string => './'.$this->getFilePathForClass($className),
  634. $testClassesWithShortOpenTag
  635. );
  636. $phpunitXmlContent = file_get_contents(__DIR__.'/../../phpunit.xml.dist');
  637. $phpunitFiles = (array) simplexml_load_string($phpunitXmlContent)->xpath('testsuites/testsuite[@name="short-open-tag"]')[0]->file;
  638. sort($testFilesWithShortOpenTag);
  639. sort($phpunitFiles);
  640. self::assertSame($testFilesWithShortOpenTag, $phpunitFiles);
  641. }
  642. /**
  643. * @dataProvider provideTestClassCases
  644. *
  645. * @param class-string $className
  646. */
  647. public function testThatTestMethodsAreNotDuplicated(string $className): void
  648. {
  649. $class = new \ReflectionClass($className);
  650. $alreadyFoundMethods = [];
  651. $duplicates = [];
  652. foreach ($class->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
  653. if (!str_starts_with($method->getName(), 'test')) {
  654. continue;
  655. }
  656. $startLine = (int) $method->getStartLine();
  657. $length = (int) $method->getEndLine() - $startLine;
  658. if (3 === $length) { // open and closing brace are included - this checks for single line methods
  659. continue;
  660. }
  661. /** @var list<string> $source */
  662. $source = file((string) $method->getFileName());
  663. $candidateContent = implode('', \array_slice($source, $startLine, $length));
  664. if (str_contains($candidateContent, '$this->doTest(')) {
  665. continue;
  666. }
  667. $foundInDuplicates = false;
  668. foreach ($alreadyFoundMethods as $methodKey => $methodContent) {
  669. if ($candidateContent === $methodContent) {
  670. $duplicates[] = \sprintf('%s is duplicate of %s', $methodKey, $method->getName());
  671. $foundInDuplicates = true;
  672. }
  673. }
  674. if (!$foundInDuplicates) {
  675. $alreadyFoundMethods[$method->getName()] = $candidateContent;
  676. }
  677. }
  678. self::assertSame(
  679. [],
  680. $duplicates,
  681. \sprintf(
  682. "Duplicated methods found in %s:\n - %s",
  683. $className,
  684. implode("\n - ", $duplicates)
  685. )
  686. );
  687. }
  688. /**
  689. * @dataProvider provideDataProviderMethodCases
  690. *
  691. * @param class-string<TestCase> $testClassName
  692. */
  693. public function testThatDataFromDataProvidersIsNotDuplicated(string $testClassName, string $dataProviderName): void
  694. {
  695. $exceptions = [ // should only shrink
  696. 'PhpCsFixer\Tests\AutoReview\CommandTest::provideCommandHasNameConstCases',
  697. 'PhpCsFixer\Tests\AutoReview\DocumentationTest::provideFixerDocumentationFileIsUpToDateCases',
  698. 'PhpCsFixer\Tests\AutoReview\FixerFactoryTest::providePriorityIntegrationTestFilesAreListedInPriorityGraphCases',
  699. 'PhpCsFixer\Tests\Console\Command\DescribeCommandTest::provideExecuteOutputCases',
  700. 'PhpCsFixer\Tests\Console\Command\HelpCommandTest::provideGetDisplayableAllowedValuesCases',
  701. 'PhpCsFixer\Tests\Documentation\FixerDocumentGeneratorTest::provideGenerateRuleSetsDocumentationCases',
  702. 'PhpCsFixer\Tests\Fixer\Basic\EncodingFixerTest::provideFixCases',
  703. 'PhpCsFixer\Tests\UtilsTest::provideStableSortCases',
  704. ];
  705. if (\in_array($testClassName.'::'.$dataProviderName, $exceptions, true)) {
  706. $this->addToAssertionCount(1);
  707. return;
  708. }
  709. $dataProvider = new \ReflectionMethod($testClassName, $dataProviderName);
  710. $duplicates = [];
  711. $alreadyFoundCases = [];
  712. foreach ($dataProvider->invoke($dataProvider->getDeclaringClass()->newInstanceWithoutConstructor()) as $candidateKey => $candidateData) {
  713. $candidateData = serialize($candidateData);
  714. $foundInDuplicates = false;
  715. foreach ($alreadyFoundCases as $caseKey => $caseData) {
  716. if ($candidateData === $caseData) {
  717. $duplicates[] = \sprintf(
  718. 'Duplicate in %s::%s: %s and %s.'.PHP_EOL,
  719. $testClassName,
  720. $dataProviderName,
  721. \is_int($caseKey) ? '#'.$caseKey : '"'.$caseKey.'"',
  722. \is_int($candidateKey) ? '#'.$candidateKey : '"'.$candidateKey.'"',
  723. );
  724. $foundInDuplicates = true;
  725. }
  726. }
  727. if (!$foundInDuplicates) {
  728. $alreadyFoundCases[$candidateKey] = $candidateData;
  729. }
  730. }
  731. self::assertSame([], $duplicates);
  732. }
  733. /**
  734. * @return iterable<string, array{class-string<TestCase>}>
  735. */
  736. public static function provideTestClassCases(): iterable
  737. {
  738. if (null === self::$testClassCases) {
  739. $cases = self::getTestClasses();
  740. self::$testClassCases = array_combine(
  741. $cases,
  742. array_map(static fn (string $case): array => [$case], $cases),
  743. );
  744. }
  745. yield from self::$testClassCases;
  746. }
  747. /**
  748. * @return iterable<array{string}>
  749. */
  750. public static function provideThereIsNoPregFunctionUsedDirectlyCases(): iterable
  751. {
  752. return array_map(
  753. static fn (string $item): array => [$item],
  754. array_filter(
  755. self::getSrcClasses(),
  756. static fn (string $className): bool => Preg::class !== $className,
  757. ),
  758. );
  759. }
  760. /**
  761. * @dataProvider providePhpUnitFixerExtendsAbstractPhpUnitFixerCases
  762. *
  763. * @param class-string $className
  764. */
  765. public function testPhpUnitFixerExtendsAbstractPhpUnitFixer(string $className): void
  766. {
  767. $reflection = new \ReflectionClass($className);
  768. self::assertTrue($reflection->isSubclassOf(AbstractPhpUnitFixer::class));
  769. }
  770. /**
  771. * @return iterable<array{string}>
  772. */
  773. public static function providePhpUnitFixerExtendsAbstractPhpUnitFixerCases(): iterable
  774. {
  775. $factory = new FixerFactory();
  776. $factory->registerBuiltInFixers();
  777. foreach ($factory->getFixers() as $fixer) {
  778. if (!str_starts_with($fixer->getName(), 'php_unit_')) {
  779. continue;
  780. }
  781. // this one fixes usage of PHPUnit classes
  782. if ($fixer instanceof PhpUnitNamespacedFixer) {
  783. continue;
  784. }
  785. if ($fixer instanceof AbstractProxyFixer) {
  786. continue;
  787. }
  788. yield [\get_class($fixer)];
  789. }
  790. }
  791. /**
  792. * @dataProvider provideSrcClassCases
  793. * @dataProvider provideTestClassCases
  794. *
  795. * @param class-string $className
  796. */
  797. public function testConstantsAreInUpperCase(string $className): void
  798. {
  799. $rc = new \ReflectionClass($className);
  800. $reflectionClassConstants = $rc->getReflectionConstants();
  801. if (\count($reflectionClassConstants) < 1) {
  802. $this->expectNotToPerformAssertions();
  803. return;
  804. }
  805. foreach ($reflectionClassConstants as $constant) {
  806. $constantName = $constant->getName();
  807. self::assertSame(strtoupper($constantName), $constantName, $className);
  808. }
  809. }
  810. /**
  811. * @param class-string $className
  812. *
  813. * @return list<string>
  814. */
  815. private function extractFunctionNamesCalledInClass(string $className): array
  816. {
  817. $tokens = $this->createTokensForClass($className);
  818. $stringTokens = array_filter(
  819. $tokens->toArray(),
  820. static fn (Token $token): bool => $token->isGivenKind(T_STRING)
  821. );
  822. $strings = array_map(
  823. static fn (Token $token): string => $token->getContent(),
  824. $stringTokens
  825. );
  826. return array_unique($strings);
  827. }
  828. /**
  829. * @param class-string $className
  830. */
  831. private function getFilePathForClass(string $className): string
  832. {
  833. $file = $className;
  834. $file = preg_replace('#^PhpCsFixer\\\Tests\\\#', 'tests\\', $file);
  835. $file = preg_replace('#^PhpCsFixer\\\#', 'src\\', $file);
  836. return str_replace('\\', \DIRECTORY_SEPARATOR, $file).'.php';
  837. }
  838. /**
  839. * @param class-string $className
  840. */
  841. private function getFileContentForClass(string $className): string
  842. {
  843. return file_get_contents($this->getFilePathForClass($className));
  844. }
  845. /**
  846. * @param class-string $className
  847. */
  848. private function createTokensForClass(string $className): Tokens
  849. {
  850. if (!isset(self::$tokensCache[$className])) {
  851. self::$tokensCache[$className] = Tokens::fromCode(self::getFileContentForClass($className));
  852. }
  853. return self::$tokensCache[$className];
  854. }
  855. /**
  856. * @param class-string<TestCase> $testClassName
  857. *
  858. * @return iterable<string, string>
  859. */
  860. private function getUsedDataProviderMethodNames(string $testClassName): iterable
  861. {
  862. foreach ($this->getAnnotationsOfTestClass($testClassName, 'dataProvider') as $methodName => $dataProviderAnnotation) {
  863. if (1 === preg_match('/@dataProvider\s+(?P<methodName>\w+)/', $dataProviderAnnotation->getContent(), $matches)) {
  864. yield $methodName => $matches['methodName'];
  865. }
  866. }
  867. }
  868. /**
  869. * @param class-string<TestCase> $testClassName
  870. *
  871. * @return iterable<string, Annotation>
  872. */
  873. private function getAnnotationsOfTestClass(string $testClassName, string $annotation): iterable
  874. {
  875. $tokens = $this->createTokensForClass($testClassName);
  876. foreach ($tokens as $index => $token) {
  877. if (!$token->isGivenKind(T_DOC_COMMENT)) {
  878. continue;
  879. }
  880. $methodName = $tokens[$tokens->getNextTokenOfKind($index, [[T_STRING]])]->getContent();
  881. $docBlock = new DocBlock($token->getContent());
  882. $dataProviderAnnotations = $docBlock->getAnnotationsOfType($annotation);
  883. foreach ($dataProviderAnnotations as $dataProviderAnnotation) {
  884. yield $methodName => $dataProviderAnnotation;
  885. }
  886. }
  887. }
  888. /**
  889. * @return list<class-string>
  890. */
  891. private static function getSrcClasses(): array
  892. {
  893. static $classes;
  894. if (null !== $classes) {
  895. return $classes;
  896. }
  897. $finder = Finder::create()
  898. ->files()
  899. ->name('*.php')
  900. ->in(__DIR__.'/../../src')
  901. ->exclude([
  902. 'Resources',
  903. ])
  904. ;
  905. /** @var list<class-string> $classes */
  906. $classes = array_map(
  907. static fn (SplFileInfo $file): string => \sprintf(
  908. '%s\%s%s%s',
  909. 'PhpCsFixer',
  910. strtr($file->getRelativePath(), \DIRECTORY_SEPARATOR, '\\'),
  911. '' !== $file->getRelativePath() ? '\\' : '',
  912. $file->getBasename('.'.$file->getExtension())
  913. ),
  914. iterator_to_array($finder, false)
  915. );
  916. sort($classes);
  917. return $classes;
  918. }
  919. /**
  920. * @return list<class-string<TestCase>>
  921. */
  922. private static function getTestClasses(): array
  923. {
  924. static $classes;
  925. if (null !== $classes) {
  926. return $classes;
  927. }
  928. $finder = Finder::create()
  929. ->files()
  930. ->name('*Test.php')
  931. ->in(__DIR__.'/..')
  932. ->exclude([
  933. 'Fixtures',
  934. ])
  935. ;
  936. /** @var list<class-string<TestCase>> $classes */
  937. $classes = array_map(
  938. static fn (SplFileInfo $file): string => \sprintf(
  939. 'PhpCsFixer\Tests\%s%s%s',
  940. strtr($file->getRelativePath(), \DIRECTORY_SEPARATOR, '\\'),
  941. '' !== $file->getRelativePath() ? '\\' : '',
  942. $file->getBasename('.'.$file->getExtension())
  943. ),
  944. iterator_to_array($finder, false)
  945. );
  946. sort($classes);
  947. return $classes;
  948. }
  949. /**
  950. * @param \ReflectionClass<object> $rc
  951. *
  952. * @return list<string>
  953. */
  954. private function getPublicMethodNames(\ReflectionClass $rc): array
  955. {
  956. return array_map(
  957. static fn (\ReflectionMethod $rm): string => $rm->getName(),
  958. $rc->getMethods(\ReflectionMethod::IS_PUBLIC)
  959. );
  960. }
  961. }