ProjectCodeTest.php 16 KB

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