ProjectCodeTest.php 17 KB

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