ProjectCodeTest.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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 PHPUnit\Framework\TestCase;
  14. use Symfony\Component\Finder\Finder;
  15. use Symfony\Component\Finder\SplFileInfo;
  16. /**
  17. * @author Dariusz Rumiński <dariusz.ruminski@gmail.com>
  18. *
  19. * @internal
  20. *
  21. * @coversNothing
  22. * @group auto-review
  23. */
  24. final class ProjectCodeTest extends TestCase
  25. {
  26. /**
  27. * This structure contains older classes that are not yet covered by tests.
  28. *
  29. * It may only shrink, never add anything to it.
  30. *
  31. * @var string[]
  32. */
  33. private static $classesWithoutTests = [
  34. \PhpCsFixer\Console\Command\SelfUpdateCommand::class,
  35. \PhpCsFixer\Console\Output\NullOutput::class,
  36. \PhpCsFixer\Differ\DiffConsoleFormatter::class,
  37. \PhpCsFixer\Doctrine\Annotation\Tokens::class,
  38. \PhpCsFixer\FileRemoval::class,
  39. \PhpCsFixer\FixerConfiguration\FixerOptionValidatorGenerator::class,
  40. \PhpCsFixer\FixerFileProcessedEvent::class,
  41. \PhpCsFixer\Fixer\Operator\AlignDoubleArrowFixerHelper::class,
  42. \PhpCsFixer\Fixer\Operator\AlignEqualsFixerHelper::class,
  43. \PhpCsFixer\Fixer\Phpdoc\GeneralPhpdocAnnotationRemoveFixer::class,
  44. \PhpCsFixer\Indicator\PhpUnitIndicator::class,
  45. \PhpCsFixer\Linter\ProcessLintingResult::class,
  46. \PhpCsFixer\Linter\TokenizerLintingResult::class,
  47. \PhpCsFixer\Report\ReportSummary::class,
  48. \PhpCsFixer\Runner\FileCachingLintingIterator::class,
  49. \PhpCsFixer\Runner\FileFilterIterator::class,
  50. \PhpCsFixer\Runner\FileLintingIterator::class,
  51. \PhpCsFixer\StdinFileInfo::class,
  52. \PhpCsFixer\Test\Assert\AssertTokensTrait::class,
  53. \PhpCsFixer\Test\IntegrationCaseFactory::class,
  54. \PhpCsFixer\Tokenizer\Transformers::class,
  55. ];
  56. public function testThatClassesWithoutTestsVarIsProper()
  57. {
  58. $unknownClasses = array_filter(
  59. self::$classesWithoutTests,
  60. function ($class) { return !class_exists($class) && !trait_exists($class); }
  61. );
  62. $this->assertSame([], $unknownClasses);
  63. }
  64. /**
  65. * @param string $className
  66. *
  67. * @dataProvider provideSrcConcreteClasses
  68. */
  69. public function testThatSrcClassHaveTestClass($className)
  70. {
  71. $testClassName = str_replace('PhpCsFixer', 'PhpCsFixer\\Tests', $className).'Test';
  72. if (in_array($className, self::$classesWithoutTests, true)) {
  73. $this->assertFalse(class_exists($testClassName), sprintf('Class "%s" already has tests, so it should be removed from "%s::$classesWithoutTests".', $className, __CLASS__));
  74. $this->markTestIncomplete(sprintf('Class "%s" has no tests yet, please help and add it.', $className));
  75. }
  76. $this->assertTrue(class_exists($testClassName), sprintf('Expected test class "%s" for "%s" not found.', $testClassName, $className));
  77. $this->assertTrue(is_subclass_of($testClassName, TestCase::class), sprintf('Expected test class "%s" to be a subclass of "\PHPUnit\Framework\TestCase".', $testClassName));
  78. }
  79. /**
  80. * @param string $className
  81. *
  82. * @dataProvider provideSrcClasses
  83. */
  84. public function testThatSrcClassesNotAbuseInterfaces($className)
  85. {
  86. $rc = new \ReflectionClass($className);
  87. $doc = false !== $rc->getDocComment()
  88. ? new DocBlock($rc->getDocComment())
  89. : null;
  90. if (
  91. $rc->isInterface()
  92. || ($doc && count($doc->getAnnotationsOfType('internal')))
  93. || 0 === count($rc->getInterfaces())
  94. || in_array($className, [
  95. \PhpCsFixer\Finder::class,
  96. \PhpCsFixer\Test\AbstractFixerTestCase::class,
  97. \PhpCsFixer\Test\AbstractIntegrationTestCase::class,
  98. \PhpCsFixer\Tokenizer\Tokens::class,
  99. ], true)
  100. ) {
  101. return;
  102. }
  103. $allowedMethods = array_map(
  104. function (\ReflectionClass $interface) {
  105. return $this->getPublicMethodNames($interface);
  106. },
  107. $rc->getInterfaces()
  108. );
  109. if (count($allowedMethods)) {
  110. $allowedMethods = array_unique(array_merge(...array_values($allowedMethods)));
  111. }
  112. $allowedMethods[] = '__construct';
  113. $allowedMethods[] = '__destruct';
  114. $allowedMethods[] = '__wakeup';
  115. $exceptionMethods = [
  116. 'configure', // due to AbstractFixer::configure
  117. 'getConfigurationDefinition', // due to AbstractFixer::getDefaultConfiguration
  118. 'getDefaultConfiguration', // due to AbstractFixer::getDefaultConfiguration
  119. 'setWhitespacesConfig', // due to AbstractFixer::setWhitespacesConfig
  120. ];
  121. // @TODO: should be removed at 3.0
  122. $exceptionMethodsPerClass = [
  123. \PhpCsFixer\Config::class => ['create'],
  124. \PhpCsFixer\Fixer\FunctionNotation\MethodArgumentSpaceFixer::class => ['fixSpace'],
  125. ];
  126. $definedMethods = $this->getPublicMethodNames($rc);
  127. $extraMethods = array_diff(
  128. $definedMethods,
  129. $allowedMethods,
  130. $exceptionMethods,
  131. isset($exceptionMethodsPerClass[$className]) ? $exceptionMethodsPerClass[$className] : []
  132. );
  133. sort($extraMethods);
  134. $this->assertEmpty(
  135. $extraMethods,
  136. sprintf(
  137. "Class '%s' should not have public methods that are not part of implemented interfaces.\nViolations:\n%s",
  138. $className,
  139. implode("\n", array_map(function ($item) {
  140. return " * $item";
  141. }, $extraMethods))
  142. )
  143. );
  144. }
  145. /**
  146. * @param string $className
  147. *
  148. * @dataProvider provideSrcClasses
  149. */
  150. public function testThatSrcClassesNotExposeProperties($className)
  151. {
  152. $rc = new \ReflectionClass($className);
  153. if (\PhpCsFixer\Fixer\Alias\NoMixedEchoPrintFixer::class === $className) {
  154. $this->markTestIncomplete(sprintf(
  155. 'Public properties of fixer `%s` will be removed on 3.0.',
  156. \PhpCsFixer\Fixer\Alias\NoMixedEchoPrintFixer::class
  157. ));
  158. }
  159. $this->assertEmpty(
  160. $rc->getProperties(\ReflectionProperty::IS_PUBLIC),
  161. sprintf('Class \'%s\' should not have public properties.', $className)
  162. );
  163. if ($rc->isFinal()) {
  164. return;
  165. }
  166. $allowedProps = [];
  167. $definedProps = $rc->getProperties(\ReflectionProperty::IS_PROTECTED);
  168. if (false !== $rc->getParentClass()) {
  169. $allowedProps = $rc->getParentClass()->getProperties(\ReflectionProperty::IS_PROTECTED);
  170. }
  171. $allowedProps = array_map(function (\ReflectionProperty $item) {
  172. return $item->getName();
  173. }, $allowedProps);
  174. $definedProps = array_map(function (\ReflectionProperty $item) {
  175. return $item->getName();
  176. }, $definedProps);
  177. $exceptionPropsPerClass = [
  178. \PhpCsFixer\AbstractPhpdocTypesFixer::class => ['tags'],
  179. \PhpCsFixer\AbstractAlignFixerHelper::class => ['deepestLevel'],
  180. \PhpCsFixer\AbstractFixer::class => ['configuration', 'configurationDefinition', 'whitespacesConfig'],
  181. \PhpCsFixer\AbstractProxyFixer::class => ['proxyFixer'],
  182. \PhpCsFixer\Test\AbstractFixerTestCase::class => ['fixer', 'linter'],
  183. \PhpCsFixer\Test\AbstractIntegrationTestCase::class => ['linter'],
  184. ];
  185. $extraProps = array_diff(
  186. $definedProps,
  187. $allowedProps,
  188. isset($exceptionPropsPerClass[$className]) ? $exceptionPropsPerClass[$className] : []
  189. );
  190. sort($extraProps);
  191. $this->assertEmpty(
  192. $extraProps,
  193. sprintf(
  194. "Class '%s' should not have protected properties.\nViolations:\n%s",
  195. $className,
  196. implode("\n", array_map(function ($item) {
  197. return " * $item";
  198. }, $extraProps))
  199. )
  200. );
  201. }
  202. /**
  203. * @param string $className
  204. *
  205. * @dataProvider provideTestClasses
  206. */
  207. public function testThatTestClassesAreAbstractOrFinal($className)
  208. {
  209. $rc = new \ReflectionClass($className);
  210. $this->assertTrue(
  211. $rc->isAbstract() || $rc->isFinal(),
  212. sprintf('Test class %s should be abstract or final.', $className)
  213. );
  214. }
  215. /**
  216. * @param string $className
  217. *
  218. * @dataProvider provideTestClasses
  219. */
  220. public function testThatTestClassesAreInternal($className)
  221. {
  222. $rc = new \ReflectionClass($className);
  223. $doc = new DocBlock($rc->getDocComment());
  224. $this->assertNotEmpty(
  225. $doc->getAnnotationsOfType('internal'),
  226. sprintf('Test class %s should have internal annotation.', $className)
  227. );
  228. }
  229. public function provideSrcClasses()
  230. {
  231. return array_map(
  232. function ($item) {
  233. return [$item];
  234. },
  235. $this->getSrcClasses()
  236. );
  237. }
  238. public function provideSrcConcreteClasses()
  239. {
  240. return array_map(
  241. function ($item) { return [$item]; },
  242. array_filter(
  243. $this->getSrcClasses(),
  244. function ($className) {
  245. $rc = new \ReflectionClass($className);
  246. return !$rc->isAbstract() && !$rc->isInterface();
  247. }
  248. )
  249. );
  250. }
  251. public function provideTestClasses()
  252. {
  253. return array_map(
  254. function ($item) {
  255. return [$item];
  256. },
  257. $this->getTestClasses()
  258. );
  259. }
  260. private function getSrcClasses()
  261. {
  262. static $files;
  263. if (null !== $files) {
  264. return $files;
  265. }
  266. $finder = Finder::create()
  267. ->files()
  268. ->name('*.php')
  269. ->in(__DIR__.'/../../src')
  270. ->exclude([
  271. 'Resources',
  272. ])
  273. ;
  274. $names = array_map(
  275. function (SplFileInfo $file) {
  276. return sprintf(
  277. '%s\\%s%s%s',
  278. 'PhpCsFixer',
  279. strtr($file->getRelativePath(), DIRECTORY_SEPARATOR, '\\'),
  280. $file->getRelativePath() ? '\\' : '',
  281. $file->getBasename('.'.$file->getExtension())
  282. );
  283. },
  284. iterator_to_array($finder, false)
  285. );
  286. sort($names);
  287. return $names;
  288. }
  289. private function getTestClasses()
  290. {
  291. static $files;
  292. if (null !== $files) {
  293. return $files;
  294. }
  295. $finder = Finder::create()
  296. ->files()
  297. ->name('*.php')
  298. ->in(__DIR__.'/..')
  299. ->exclude([
  300. 'Fixtures',
  301. ])
  302. ;
  303. $names = array_map(
  304. function (SplFileInfo $file) {
  305. return sprintf(
  306. 'PhpCsFixer\\Tests\\%s%s%s',
  307. strtr($file->getRelativePath(), DIRECTORY_SEPARATOR, '\\'),
  308. $file->getRelativePath() ? '\\' : '',
  309. $file->getBasename('.'.$file->getExtension())
  310. );
  311. },
  312. iterator_to_array($finder, false)
  313. );
  314. sort($names);
  315. return $names;
  316. }
  317. /**
  318. * @param \ReflectionClass $rc
  319. *
  320. * @return string[]
  321. */
  322. private function getPublicMethodNames(\ReflectionClass $rc)
  323. {
  324. return array_map(
  325. function (\ReflectionMethod $rm) {
  326. return $rm->getName();
  327. },
  328. $rc->getMethods(\ReflectionMethod::IS_PUBLIC)
  329. );
  330. }
  331. }