ProjectCodeTest.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. <?php
  2. /*
  3. * This file is part of PHP CS Fixer.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. * Dariusz Rumiński <dariusz.ruminski@gmail.com>
  7. *
  8. * This source file is subject to the MIT license that is bundled
  9. * with this source code in the file LICENSE.
  10. */
  11. namespace PhpCsFixer\Tests\AutoReview;
  12. if (!class_exists(\PHPUnit\Runner\Version::class)) {
  13. class_alias('PHPUnit_Runner_Version', \PHPUnit\Runner\Version::class);
  14. }
  15. use PhpCsFixer\DocBlock\DocBlock;
  16. use PhpCsFixer\Tests\TestCase;
  17. use PhpCsFixer\Tokenizer\Token;
  18. use PhpCsFixer\Tokenizer\Tokens;
  19. use Symfony\Component\Finder\Finder;
  20. use Symfony\Component\Finder\SplFileInfo;
  21. /**
  22. * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
  23. *
  24. * @internal
  25. *
  26. * @coversNothing
  27. * @group auto-review
  28. * @group covers-nothing
  29. */
  30. final class ProjectCodeTest extends TestCase
  31. {
  32. /**
  33. * This structure contains older classes that are not yet covered by tests.
  34. *
  35. * It may only shrink, never add anything to it.
  36. *
  37. * @var string[]
  38. */
  39. private static $classesWithoutTests = [
  40. \PhpCsFixer\Console\SelfUpdate\GithubClient::class,
  41. \PhpCsFixer\Doctrine\Annotation\Tokens::class,
  42. \PhpCsFixer\Fixer\Operator\AlignDoubleArrowFixerHelper::class,
  43. \PhpCsFixer\Fixer\Operator\AlignEqualsFixerHelper::class,
  44. \PhpCsFixer\Fixer\Whitespace\NoExtraConsecutiveBlankLinesFixer::class,
  45. \PhpCsFixer\Runner\FileCachingLintingIterator::class,
  46. \PhpCsFixer\Runner\FileLintingIterator::class,
  47. \PhpCsFixer\Test\AccessibleObject::class,
  48. ];
  49. public function testThatClassesWithoutTestsVarIsProper()
  50. {
  51. $unknownClasses = array_filter(
  52. self::$classesWithoutTests,
  53. static function ($class) { return !class_exists($class) && !trait_exists($class); }
  54. );
  55. static::assertSame([], $unknownClasses);
  56. }
  57. /**
  58. * @param string $className
  59. *
  60. * @dataProvider provideSrcConcreteClassCases
  61. */
  62. public function testThatSrcClassHaveTestClass($className)
  63. {
  64. $testClassName = str_replace('PhpCsFixer', 'PhpCsFixer\\Tests', $className).'Test';
  65. if (\in_array($className, self::$classesWithoutTests, true)) {
  66. static::assertFalse(class_exists($testClassName), sprintf('Class "%s" already has tests, so it should be removed from "%s::$classesWithoutTests".', $className, __CLASS__));
  67. static::markTestIncomplete(sprintf('Class "%s" has no tests yet, please help and add it.', $className));
  68. }
  69. static::assertTrue(class_exists($testClassName), sprintf('Expected test class "%s" for "%s" not found.', $testClassName, $className));
  70. static::assertTrue(is_subclass_of($testClassName, TestCase::class), sprintf('Expected test class "%s" to be a subclass of "\PhpCsFixer\Tests\TestCase".', $testClassName));
  71. }
  72. /**
  73. * @param string $className
  74. *
  75. * @dataProvider provideSrcClassesNotAbuseInterfacesCases
  76. */
  77. public function testThatSrcClassesNotAbuseInterfaces($className)
  78. {
  79. $rc = new \ReflectionClass($className);
  80. $allowedMethods = array_map(
  81. function (\ReflectionClass $interface) {
  82. return $this->getPublicMethodNames($interface);
  83. },
  84. $rc->getInterfaces()
  85. );
  86. if (\count($allowedMethods)) {
  87. $allowedMethods = array_unique(array_merge(...array_values($allowedMethods)));
  88. }
  89. $allowedMethods[] = '__construct';
  90. $allowedMethods[] = '__destruct';
  91. $allowedMethods[] = '__wakeup';
  92. $exceptionMethods = [
  93. 'configure', // due to AbstractFixer::configure
  94. 'getConfigurationDefinition', // due to AbstractFixer::getConfigurationDefinition
  95. 'getDefaultConfiguration', // due to AbstractFixer::getDefaultConfiguration
  96. 'setWhitespacesConfig', // due to AbstractFixer::setWhitespacesConfig
  97. ];
  98. // @TODO: 3.0 should be removed
  99. $exceptionMethodsPerClass = [
  100. \PhpCsFixer\Config::class => ['create'],
  101. \PhpCsFixer\Fixer\FunctionNotation\MethodArgumentSpaceFixer::class => ['fixSpace'],
  102. ];
  103. $definedMethods = $this->getPublicMethodNames($rc);
  104. $extraMethods = array_diff(
  105. $definedMethods,
  106. $allowedMethods,
  107. $exceptionMethods,
  108. isset($exceptionMethodsPerClass[$className]) ? $exceptionMethodsPerClass[$className] : []
  109. );
  110. sort($extraMethods);
  111. static::assertEmpty(
  112. $extraMethods,
  113. sprintf(
  114. "Class '%s' should not have public methods that are not part of implemented interfaces.\nViolations:\n%s",
  115. $className,
  116. implode("\n", array_map(static function ($item) {
  117. return " * {$item}";
  118. }, $extraMethods))
  119. )
  120. );
  121. }
  122. /**
  123. * @param string $className
  124. *
  125. * @dataProvider provideSrcClassCases
  126. */
  127. public function testThatSrcClassesNotExposeProperties($className)
  128. {
  129. $rc = new \ReflectionClass($className);
  130. if (\PhpCsFixer\Fixer\Alias\NoMixedEchoPrintFixer::class === $className) {
  131. static::markTestIncomplete(sprintf(
  132. 'Public properties of fixer `%s` will be removed on 3.0.',
  133. \PhpCsFixer\Fixer\Alias\NoMixedEchoPrintFixer::class
  134. ));
  135. }
  136. static::assertEmpty(
  137. $rc->getProperties(\ReflectionProperty::IS_PUBLIC),
  138. sprintf('Class \'%s\' should not have public properties.', $className)
  139. );
  140. if ($rc->isFinal()) {
  141. return;
  142. }
  143. $allowedProps = [];
  144. $definedProps = $rc->getProperties(\ReflectionProperty::IS_PROTECTED);
  145. if (false !== $rc->getParentClass()) {
  146. $allowedProps = $rc->getParentClass()->getProperties(\ReflectionProperty::IS_PROTECTED);
  147. }
  148. $allowedProps = array_map(static function (\ReflectionProperty $item) {
  149. return $item->getName();
  150. }, $allowedProps);
  151. $definedProps = array_map(static function (\ReflectionProperty $item) {
  152. return $item->getName();
  153. }, $definedProps);
  154. $exceptionPropsPerClass = [
  155. \PhpCsFixer\AbstractPhpdocTypesFixer::class => ['tags'],
  156. \PhpCsFixer\AbstractAlignFixerHelper::class => ['deepestLevel'],
  157. \PhpCsFixer\AbstractFixer::class => ['configuration', 'configurationDefinition', 'whitespacesConfig'],
  158. \PhpCsFixer\AbstractProxyFixer::class => ['proxyFixers'],
  159. \PhpCsFixer\Test\AbstractFixerTestCase::class => ['fixer', 'linter'],
  160. \PhpCsFixer\Test\AbstractIntegrationTestCase::class => ['linter'],
  161. ];
  162. $extraProps = array_diff(
  163. $definedProps,
  164. $allowedProps,
  165. isset($exceptionPropsPerClass[$className]) ? $exceptionPropsPerClass[$className] : []
  166. );
  167. sort($extraProps);
  168. static::assertEmpty(
  169. $extraProps,
  170. sprintf(
  171. "Class '%s' should not have protected properties.\nViolations:\n%s",
  172. $className,
  173. implode("\n", array_map(static function ($item) {
  174. return " * {$item}";
  175. }, $extraProps))
  176. )
  177. );
  178. }
  179. /**
  180. * @param string $className
  181. *
  182. * @dataProvider provideTestClassCases
  183. */
  184. public function testThatTestClassesAreTraitOrAbstractOrFinal($className)
  185. {
  186. $rc = new \ReflectionClass($className);
  187. static::assertTrue(
  188. $rc->isTrait() || $rc->isAbstract() || $rc->isFinal(),
  189. sprintf('Test class %s should be trait, abstract or final.', $className)
  190. );
  191. }
  192. /**
  193. * @param string $className
  194. *
  195. * @dataProvider provideTestClassCases
  196. */
  197. public function testThatTestClassesAreInternal($className)
  198. {
  199. $rc = new \ReflectionClass($className);
  200. $doc = new DocBlock($rc->getDocComment());
  201. static::assertNotEmpty(
  202. $doc->getAnnotationsOfType('internal'),
  203. sprintf('Test class %s should have internal annotation.', $className)
  204. );
  205. }
  206. /**
  207. * @dataProvider provideTestClassCases
  208. *
  209. * @param string $testClassName
  210. */
  211. public function testThatDataProvidersAreCorrectlyNamed($testClassName)
  212. {
  213. $dataProviderMethodNames = $this->getDataProviderMethodNames($testClassName);
  214. if (empty($dataProviderMethodNames)) {
  215. $this->addToAssertionCount(1); // no data providers to test, all good!
  216. }
  217. foreach ($dataProviderMethodNames as $dataProviderMethodName) {
  218. static::assertRegExp('/^provide[A-Z]\S+Cases$/', $dataProviderMethodName, sprintf(
  219. 'Data provider in "%s" with name "%s" is not correctly named.',
  220. $testClassName,
  221. $dataProviderMethodName
  222. ));
  223. }
  224. }
  225. /**
  226. * @dataProvider provideClassesWherePregFunctionsAreForbiddenCases
  227. *
  228. * @param string $className
  229. */
  230. public function testThereIsNoPregFunctionUsedDirectly($className)
  231. {
  232. $rc = new \ReflectionClass($className);
  233. $tokens = Tokens::fromCode(file_get_contents($rc->getFileName()));
  234. $stringTokens = array_filter(
  235. $tokens->toArray(),
  236. function (Token $token) {
  237. return $token->isGivenKind(T_STRING);
  238. }
  239. );
  240. $strings = array_map(
  241. function (Token $token) {
  242. return $token->getContent();
  243. },
  244. $stringTokens
  245. );
  246. $strings = array_unique($strings);
  247. $message = sprintf('Class %s must not use preg_*, it shall use Preg::* instead.', $className);
  248. static::assertNotContains('preg_filter', $strings, $message);
  249. static::assertNotContains('preg_grep', $strings, $message);
  250. static::assertNotContains('preg_match', $strings, $message);
  251. static::assertNotContains('preg_match_all', $strings, $message);
  252. static::assertNotContains('preg_replace', $strings, $message);
  253. static::assertNotContains('preg_replace_callback', $strings, $message);
  254. static::assertNotContains('preg_split', $strings, $message);
  255. }
  256. public function provideSrcClassCases()
  257. {
  258. return array_map(
  259. static function ($item) {
  260. return [$item];
  261. },
  262. $this->getSrcClasses()
  263. );
  264. }
  265. public function provideSrcClassesNotAbuseInterfacesCases()
  266. {
  267. return array_map(
  268. static function ($item) {
  269. return [$item];
  270. },
  271. array_filter($this->getSrcClasses(), static function ($className) {
  272. $rc = new \ReflectionClass($className);
  273. $doc = false !== $rc->getDocComment()
  274. ? new DocBlock($rc->getDocComment())
  275. : null;
  276. if (
  277. $rc->isInterface()
  278. || ($doc && \count($doc->getAnnotationsOfType('internal')))
  279. || 0 === \count($rc->getInterfaces())
  280. || \in_array($className, [
  281. \PhpCsFixer\Finder::class,
  282. \PhpCsFixer\Test\AbstractFixerTestCase::class,
  283. \PhpCsFixer\Test\AbstractIntegrationTestCase::class,
  284. \PhpCsFixer\Tests\Test\AbstractFixerTestCase::class,
  285. \PhpCsFixer\Tests\Test\AbstractIntegrationTestCase::class,
  286. \PhpCsFixer\Tokenizer\Tokens::class,
  287. ], true)
  288. ) {
  289. return false;
  290. }
  291. return true;
  292. })
  293. );
  294. }
  295. public function provideSrcConcreteClassCases()
  296. {
  297. return array_map(
  298. static function ($item) { return [$item]; },
  299. array_filter(
  300. $this->getSrcClasses(),
  301. static function ($className) {
  302. $rc = new \ReflectionClass($className);
  303. return !$rc->isAbstract() && !$rc->isInterface();
  304. }
  305. )
  306. );
  307. }
  308. public function provideTestClassCases()
  309. {
  310. return array_map(
  311. static function ($item) {
  312. return [$item];
  313. },
  314. $this->getTestClasses()
  315. );
  316. }
  317. public function provideClassesWherePregFunctionsAreForbiddenCases()
  318. {
  319. return array_map(
  320. function ($item) {
  321. return [$item];
  322. },
  323. array_filter(
  324. $this->getSrcClasses(),
  325. function ($className) {
  326. return 'PhpCsFixer\\Preg' !== $className;
  327. }
  328. )
  329. );
  330. }
  331. private function getDataProviderMethodNames($testClassName)
  332. {
  333. $dataProviderMethodNames = [];
  334. $tokens = Tokens::fromCode(file_get_contents(
  335. str_replace('\\', \DIRECTORY_SEPARATOR, preg_replace('#^PhpCsFixer\\\Tests#', 'tests', $testClassName)).'.php'
  336. ));
  337. foreach ($tokens as $token) {
  338. if ($token->isGivenKind(T_DOC_COMMENT)) {
  339. $docBlock = new DocBlock($token->getContent());
  340. $dataProviderAnnotations = $docBlock->getAnnotationsOfType('dataProvider');
  341. foreach ($dataProviderAnnotations as $dataProviderAnnotation) {
  342. if (1 === preg_match('/@dataProvider\s+(?P<methodName>\w+)/', $dataProviderAnnotation->getContent(), $matches)) {
  343. $dataProviderMethodNames[] = $matches['methodName'];
  344. }
  345. }
  346. }
  347. }
  348. return array_unique($dataProviderMethodNames);
  349. }
  350. private function getSrcClasses()
  351. {
  352. static $classes;
  353. if (null !== $classes) {
  354. return $classes;
  355. }
  356. $finder = Finder::create()
  357. ->files()
  358. ->name('*.php')
  359. ->in(__DIR__.'/../../src')
  360. ->exclude([
  361. 'Resources',
  362. ])
  363. ;
  364. $classes = array_map(
  365. static function (SplFileInfo $file) {
  366. return sprintf(
  367. '%s\\%s%s%s',
  368. 'PhpCsFixer',
  369. strtr($file->getRelativePath(), \DIRECTORY_SEPARATOR, '\\'),
  370. $file->getRelativePath() ? '\\' : '',
  371. $file->getBasename('.'.$file->getExtension())
  372. );
  373. },
  374. iterator_to_array($finder, false)
  375. );
  376. sort($classes);
  377. return $classes;
  378. }
  379. private function getTestClasses()
  380. {
  381. static $classes;
  382. if (null !== $classes) {
  383. return $classes;
  384. }
  385. $finder = Finder::create()
  386. ->files()
  387. ->name('*.php')
  388. ->in(__DIR__.'/..')
  389. ->exclude([
  390. 'Fixtures',
  391. ])
  392. ;
  393. $classes = array_map(
  394. static function (SplFileInfo $file) {
  395. return sprintf(
  396. 'PhpCsFixer\\Tests\\%s%s%s',
  397. strtr($file->getRelativePath(), \DIRECTORY_SEPARATOR, '\\'),
  398. $file->getRelativePath() ? '\\' : '',
  399. $file->getBasename('.'.$file->getExtension())
  400. );
  401. },
  402. iterator_to_array($finder, false)
  403. );
  404. sort($classes);
  405. return $classes;
  406. }
  407. /**
  408. * @param \ReflectionClass $rc
  409. *
  410. * @return string[]
  411. */
  412. private function getPublicMethodNames(\ReflectionClass $rc)
  413. {
  414. return array_map(
  415. static function (\ReflectionMethod $rm) {
  416. return $rm->getName();
  417. },
  418. $rc->getMethods(\ReflectionMethod::IS_PUBLIC)
  419. );
  420. }
  421. }