ProjectCodeTest.php 13 KB

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