ProjectCodeTest.php 39 KB

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