ProjectCodeTest.php 15 KB

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