ProjectCodeTest.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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. use PhpCsFixer\DocBlock\DocBlock;
  13. use PhpCsFixer\Tests\TestCase;
  14. use PhpCsFixer\Tokenizer\Tokens;
  15. use Symfony\Component\Finder\Finder;
  16. use Symfony\Component\Finder\SplFileInfo;
  17. /**
  18. * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
  19. *
  20. * @internal
  21. *
  22. * @coversNothing
  23. * @group auto-review
  24. */
  25. final class ProjectCodeTest extends TestCase
  26. {
  27. /**
  28. * This structure contains older classes that are not yet covered by tests.
  29. *
  30. * It may only shrink, never add anything to it.
  31. *
  32. * @var string[]
  33. */
  34. private static $classesWithoutTests = [
  35. \PhpCsFixer\Console\SelfUpdate\GithubClient::class,
  36. \PhpCsFixer\Console\WarningsDetector::class,
  37. \PhpCsFixer\Doctrine\Annotation\Tokens::class,
  38. \PhpCsFixer\FileReader::class,
  39. \PhpCsFixer\FileRemoval::class,
  40. \PhpCsFixer\Fixer\Operator\AlignDoubleArrowFixerHelper::class,
  41. \PhpCsFixer\Fixer\Operator\AlignEqualsFixerHelper::class,
  42. \PhpCsFixer\Fixer\Whitespace\NoExtraConsecutiveBlankLinesFixer::class,
  43. \PhpCsFixer\Indicator\PhpUnitTestCaseIndicator::class,
  44. \PhpCsFixer\Runner\FileCachingLintingIterator::class,
  45. \PhpCsFixer\Runner\FileLintingIterator::class,
  46. \PhpCsFixer\StdinFileInfo::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 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. public function provideSrcClassCases()
  222. {
  223. return array_map(
  224. static function ($item) {
  225. return [$item];
  226. },
  227. $this->getSrcClasses()
  228. );
  229. }
  230. public function provideSrcClassesNotAbuseInterfacesCases()
  231. {
  232. return array_map(
  233. static function ($item) {
  234. return [$item];
  235. },
  236. array_filter($this->getSrcClasses(), static function ($className) {
  237. $rc = new \ReflectionClass($className);
  238. $doc = false !== $rc->getDocComment()
  239. ? new DocBlock($rc->getDocComment())
  240. : null;
  241. if (
  242. $rc->isInterface()
  243. || ($doc && count($doc->getAnnotationsOfType('internal')))
  244. || 0 === count($rc->getInterfaces())
  245. || in_array($className, [
  246. \PhpCsFixer\Finder::class,
  247. \PhpCsFixer\Test\AbstractFixerTestCase::class,
  248. \PhpCsFixer\Test\AbstractIntegrationTestCase::class,
  249. \PhpCsFixer\Tests\Test\AbstractFixerTestCase::class,
  250. \PhpCsFixer\Tests\Test\AbstractIntegrationTestCase::class,
  251. \PhpCsFixer\Tokenizer\Tokens::class,
  252. ], true)
  253. ) {
  254. return false;
  255. }
  256. return true;
  257. })
  258. );
  259. }
  260. public function provideSrcConcreteClassCases()
  261. {
  262. return array_map(
  263. static function ($item) { return [$item]; },
  264. array_filter(
  265. $this->getSrcClasses(),
  266. static function ($className) {
  267. $rc = new \ReflectionClass($className);
  268. return !$rc->isAbstract() && !$rc->isInterface();
  269. }
  270. )
  271. );
  272. }
  273. public function provideTestClassCases()
  274. {
  275. return array_map(
  276. static function ($item) {
  277. return [$item];
  278. },
  279. $this->getTestClasses()
  280. );
  281. }
  282. public function provideDataProviderMethodNameCases()
  283. {
  284. if (extension_loaded('xdebug') && false === getenv('CI')) {
  285. $this->markTestSkipped('Data provider too slow when Xdebug is loaded.');
  286. }
  287. $data = [];
  288. $testClassNames = $this->getTestClasses();
  289. foreach ($testClassNames as $testClassName) {
  290. $dataProviderMethodNames = [];
  291. $tokens = Tokens::fromCode(file_get_contents(
  292. str_replace('\\', DIRECTORY_SEPARATOR, preg_replace('#^PhpCsFixer\\\Tests#', 'tests', $testClassName)).'.php'
  293. ));
  294. foreach ($tokens as $token) {
  295. if ($token->isGivenKind(T_DOC_COMMENT)) {
  296. $docBlock = new DocBlock($token->getContent());
  297. $dataProviderAnnotations = $docBlock->getAnnotationsOfType('dataProvider');
  298. foreach ($dataProviderAnnotations as $dataProviderAnnotation) {
  299. if (1 === preg_match('/@dataProvider\s+(?P<methodName>\w+)/', $dataProviderAnnotation->getContent(), $matches)) {
  300. $dataProviderMethodNames[] = $matches['methodName'];
  301. }
  302. }
  303. }
  304. }
  305. $dataProviderMethodNames = array_unique($dataProviderMethodNames);
  306. foreach ($dataProviderMethodNames as $dataProviderMethodName) {
  307. $data[] = [
  308. $testClassName,
  309. $dataProviderMethodName,
  310. ];
  311. }
  312. }
  313. return $data;
  314. }
  315. private function getSrcClasses()
  316. {
  317. static $classes;
  318. if (null !== $classes) {
  319. return $classes;
  320. }
  321. $finder = Finder::create()
  322. ->files()
  323. ->name('*.php')
  324. ->in(__DIR__.'/../../src')
  325. ->exclude([
  326. 'Resources',
  327. ])
  328. ;
  329. $classes = array_map(
  330. static function (SplFileInfo $file) {
  331. return sprintf(
  332. '%s\\%s%s%s',
  333. 'PhpCsFixer',
  334. strtr($file->getRelativePath(), DIRECTORY_SEPARATOR, '\\'),
  335. $file->getRelativePath() ? '\\' : '',
  336. $file->getBasename('.'.$file->getExtension())
  337. );
  338. },
  339. iterator_to_array($finder, false)
  340. );
  341. sort($classes);
  342. return $classes;
  343. }
  344. private function getTestClasses()
  345. {
  346. static $classes;
  347. if (null !== $classes) {
  348. return $classes;
  349. }
  350. $finder = Finder::create()
  351. ->files()
  352. ->name('*.php')
  353. ->in(__DIR__.'/..')
  354. ->exclude([
  355. 'Fixtures',
  356. ])
  357. ;
  358. $classes = array_map(
  359. static function (SplFileInfo $file) {
  360. return sprintf(
  361. 'PhpCsFixer\\Tests\\%s%s%s',
  362. strtr($file->getRelativePath(), DIRECTORY_SEPARATOR, '\\'),
  363. $file->getRelativePath() ? '\\' : '',
  364. $file->getBasename('.'.$file->getExtension())
  365. );
  366. },
  367. iterator_to_array($finder, false)
  368. );
  369. sort($classes);
  370. return $classes;
  371. }
  372. /**
  373. * @param \ReflectionClass $rc
  374. *
  375. * @return string[]
  376. */
  377. private function getPublicMethodNames(\ReflectionClass $rc)
  378. {
  379. return array_map(
  380. static function (\ReflectionMethod $rm) {
  381. return $rm->getName();
  382. },
  383. $rc->getMethods(\ReflectionMethod::IS_PUBLIC)
  384. );
  385. }
  386. }