ProjectCodeTest.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  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\Tokenizer\Tokens;
  14. use PHPUnit\Framework\TestCase;
  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 = array(
  35. 'PhpCsFixer\ConfigurationException\InvalidForEnvFixerConfigurationException',
  36. 'PhpCsFixer\Console\Output\NullOutput',
  37. 'PhpCsFixer\Console\SelfUpdate\GithubClient',
  38. 'PhpCsFixer\Console\WarningsDetector',
  39. 'PhpCsFixer\Differ\DiffConsoleFormatter',
  40. 'PhpCsFixer\Doctrine\Annotation\Tokens',
  41. 'PhpCsFixer\FileRemoval',
  42. 'PhpCsFixer\Fixer\Operator\AlignDoubleArrowFixerHelper',
  43. 'PhpCsFixer\Fixer\Operator\AlignEqualsFixerHelper',
  44. 'PhpCsFixer\Fixer\Phpdoc\GeneralPhpdocAnnotationRemoveFixer',
  45. 'PhpCsFixer\FixerConfiguration\FixerOptionValidatorGenerator',
  46. 'PhpCsFixer\FixerConfiguration\InvalidOptionsForEnvException',
  47. 'PhpCsFixer\FixerFileProcessedEvent',
  48. 'PhpCsFixer\Linter\ProcessLintingResult',
  49. 'PhpCsFixer\Linter\TokenizerLintingResult',
  50. 'PhpCsFixer\PharChecker',
  51. 'PhpCsFixer\Report\ReportSummary',
  52. 'PhpCsFixer\Runner\FileCachingLintingIterator',
  53. 'PhpCsFixer\Runner\FileFilterIterator',
  54. 'PhpCsFixer\Runner\FileLintingIterator',
  55. 'PhpCsFixer\StdinFileInfo',
  56. 'PhpCsFixer\Tokenizer\Transformers',
  57. );
  58. public function testThatClassesWithoutTestsVarIsProper()
  59. {
  60. $unknownClasses = array_filter(self::$classesWithoutTests, function ($class) { return !class_exists($class); });
  61. $this->assertSame(array(), $unknownClasses);
  62. }
  63. /**
  64. * @param string $className
  65. *
  66. * @dataProvider provideSrcConcreteClassCases
  67. */
  68. public function testThatSrcClassHaveTestClass($className)
  69. {
  70. $testClassName = str_replace('PhpCsFixer', 'PhpCsFixer\\Tests', $className).'Test';
  71. if (in_array($className, self::$classesWithoutTests, true)) {
  72. $this->assertFalse(class_exists($testClassName), sprintf('Class "%s" already has tests, so it should be removed from "%s::$classesWithoutTests".', $className, __CLASS__));
  73. $this->markTestIncomplete(sprintf('Class "%s" has no tests yet, please help and add it.', $className));
  74. }
  75. $this->assertTrue(class_exists($testClassName), sprintf('Expected test class "%s" for "%s" not found.', $testClassName, $className));
  76. $this->assertTrue(is_subclass_of($testClassName, '\PHPUnit\Framework\TestCase'), sprintf('Expected test class "%s" to be a subclass of "\PHPUnit\Framework\TestCase".', $testClassName));
  77. }
  78. /**
  79. * @param string $className
  80. *
  81. * @dataProvider provideSrcClassesNotAbuseInterfacesCases
  82. * @requires PHP 5.4
  83. */
  84. public function testThatSrcClassesNotAbuseInterfaces($className)
  85. {
  86. // HHVM knows better which interfaces you implements
  87. // https://github.com/facebook/hhvm/issues/5890
  88. if (defined('HHVM_VERSION') && interface_exists('Stringish')) {
  89. $this->markTestSkipped('Skipped as HHVM violate inheritance tree with `Stringish` interface.');
  90. }
  91. $rc = new \ReflectionClass($className);
  92. $allowedMethods = array_map(
  93. function (\ReflectionClass $interface) {
  94. return $this->getPublicMethodNames($interface);
  95. },
  96. $rc->getInterfaces()
  97. );
  98. if (count($allowedMethods)) {
  99. $allowedMethods = array_unique(call_user_func_array('array_merge', $allowedMethods));
  100. }
  101. $allowedMethods[] = '__construct';
  102. $allowedMethods[] = '__destruct';
  103. $allowedMethods[] = '__wakeup';
  104. $exceptionMethods = array(
  105. 'configure', // due to AbstractFixer::configure
  106. 'getConfigurationDefinition', // due to AbstractFixer::getDefaultConfiguration
  107. 'getDefaultConfiguration', // due to AbstractFixer::getDefaultConfiguration
  108. 'setWhitespacesConfig', // due to AbstractFixer::setWhitespacesConfig
  109. );
  110. // @TODO: should be removed at 3.0
  111. $exceptionMethodsPerClass = array(
  112. 'PhpCsFixer\Config' => array('create'),
  113. 'PhpCsFixer\Fixer\FunctionNotation\MethodArgumentSpaceFixer' => array('fixSpace'),
  114. );
  115. $definedMethods = $this->getPublicMethodNames($rc);
  116. $extraMethods = array_diff(
  117. $definedMethods,
  118. $allowedMethods,
  119. $exceptionMethods,
  120. isset($exceptionMethodsPerClass[$className]) ? $exceptionMethodsPerClass[$className] : array()
  121. );
  122. sort($extraMethods);
  123. $this->assertEmpty(
  124. $extraMethods,
  125. sprintf(
  126. "Class '%s' should not have public methods that are not part of implemented interfaces.\nViolations:\n%s",
  127. $className,
  128. implode("\n", array_map(function ($item) {
  129. return " * ${item}";
  130. }, $extraMethods))
  131. )
  132. );
  133. }
  134. /**
  135. * @param string $className
  136. *
  137. * @dataProvider provideSrcClassCases
  138. */
  139. public function testThatSrcClassesNotExposeProperties($className)
  140. {
  141. $rc = new \ReflectionClass($className);
  142. if ('PhpCsFixer\Fixer\Alias\NoMixedEchoPrintFixer' === $className) {
  143. $this->markTestIncomplete('Public properties of fixer \'PhpCsFixer\Fixer\Alias\NoMixedEchoPrintFixer\' will be remove on 3.0.');
  144. }
  145. $this->assertEmpty(
  146. $rc->getProperties(\ReflectionProperty::IS_PUBLIC),
  147. sprintf('Class \'%s\' should not have public properties.', $className)
  148. );
  149. if ($rc->isFinal()) {
  150. return;
  151. }
  152. $allowedProps = array();
  153. $definedProps = $rc->getProperties(\ReflectionProperty::IS_PROTECTED);
  154. if (false !== $rc->getParentClass()) {
  155. $allowedProps = $rc->getParentClass()->getProperties(\ReflectionProperty::IS_PROTECTED);
  156. }
  157. $allowedProps = array_map(function (\ReflectionProperty $item) {
  158. return $item->getName();
  159. }, $allowedProps);
  160. $definedProps = array_map(function (\ReflectionProperty $item) {
  161. return $item->getName();
  162. }, $definedProps);
  163. $exceptionPropsPerClass = array(
  164. 'PhpCsFixer\AbstractPhpdocTypesFixer' => array('tags'),
  165. 'PhpCsFixer\AbstractAlignFixerHelper' => array('deepestLevel'),
  166. 'PhpCsFixer\AbstractFixer' => array('configuration', 'configurationDefinition', 'whitespacesConfig'),
  167. 'PhpCsFixer\AbstractProxyFixer' => array('proxyFixer'),
  168. 'PhpCsFixer\Test\AbstractFixerTestCase' => array('fixer', 'linter'),
  169. 'PhpCsFixer\Test\AbstractIntegrationTestCase' => array('linter'),
  170. );
  171. $extraProps = array_diff(
  172. $definedProps,
  173. $allowedProps,
  174. isset($exceptionPropsPerClass[$className]) ? $exceptionPropsPerClass[$className] : array()
  175. );
  176. sort($extraProps);
  177. $this->assertEmpty(
  178. $extraProps,
  179. sprintf(
  180. "Class '%s' should not have protected properties.\nViolations:\n%s",
  181. $className,
  182. implode("\n", array_map(function ($item) {
  183. return " * ${item}";
  184. }, $extraProps))
  185. )
  186. );
  187. }
  188. /**
  189. * @param string $className
  190. *
  191. * @dataProvider provideTestClassCases
  192. */
  193. public function testThatTestClassesAreAbstractOrFinal($className)
  194. {
  195. $rc = new \ReflectionClass($className);
  196. $this->assertTrue(
  197. $rc->isAbstract() || $rc->isFinal(),
  198. sprintf('Test class %s should be abstract or final.', $className)
  199. );
  200. }
  201. /**
  202. * @param string $className
  203. *
  204. * @dataProvider provideTestClassCases
  205. */
  206. public function testThatTestClassesAreInternal($className)
  207. {
  208. $rc = new \ReflectionClass($className);
  209. $doc = new DocBlock($rc->getDocComment());
  210. $this->assertNotEmpty(
  211. $doc->getAnnotationsOfType('internal'),
  212. sprintf('Test class %s should have internal annotation.', $className)
  213. );
  214. }
  215. /**
  216. * @dataProvider provideDataProviderMethodNameCases
  217. *
  218. * @param string $testClassName
  219. * @param string $dataProviderMethodName
  220. */
  221. public function testThatDataProvidersAreCorrectlyNamed($testClassName, $dataProviderMethodName)
  222. {
  223. $this->assertRegExp('/^provide[A-Z]\S+Cases$/', $dataProviderMethodName, sprintf(
  224. 'Data provider in "%s" with name "%s" is not correctly named.',
  225. $testClassName,
  226. $dataProviderMethodName
  227. ));
  228. }
  229. public function provideSrcClassCases()
  230. {
  231. return array_map(
  232. function ($item) {
  233. return array($item);
  234. },
  235. $this->getSrcClasses()
  236. );
  237. }
  238. public function provideSrcClassesNotAbuseInterfacesCases()
  239. {
  240. return array_map(
  241. function ($item) {
  242. return array($item);
  243. },
  244. array_filter($this->getSrcClasses(), function ($className) {
  245. $rc = new \ReflectionClass($className);
  246. $doc = false !== $rc->getDocComment()
  247. ? new DocBlock($rc->getDocComment())
  248. : null;
  249. if (
  250. $rc->isInterface()
  251. || ($doc && count($doc->getAnnotationsOfType('internal')))
  252. || 0 === count($rc->getInterfaces())
  253. || in_array($className, array(
  254. 'PhpCsFixer\Finder',
  255. 'PhpCsFixer\Test\AbstractFixerTestCase',
  256. 'PhpCsFixer\Test\AbstractIntegrationTestCase',
  257. 'PhpCsFixer\Tokenizer\Tokens',
  258. ), true)
  259. ) {
  260. return false;
  261. }
  262. return true;
  263. })
  264. );
  265. }
  266. public function provideSrcConcreteClassCases()
  267. {
  268. return array_map(
  269. function ($item) { return array($item); },
  270. array_filter(
  271. $this->getSrcClasses(),
  272. function ($className) {
  273. $rc = new \ReflectionClass($className);
  274. return !$rc->isAbstract() && !$rc->isInterface();
  275. }
  276. )
  277. );
  278. }
  279. public function provideTestClassCases()
  280. {
  281. return array_map(
  282. function ($item) {
  283. return array($item);
  284. },
  285. $this->getTestClasses()
  286. );
  287. }
  288. public function provideDataProviderMethodNameCases()
  289. {
  290. if (extension_loaded('xdebug') && false === getenv('CI')) {
  291. $this->markTestSkipped('Data provider too slow when Xdebug is loaded.');
  292. }
  293. $data = array();
  294. $testClassNames = $this->getTestClasses();
  295. foreach ($testClassNames as $testClassName) {
  296. $dataProviderMethodNames = array();
  297. $tokens = Tokens::fromCode(file_get_contents(
  298. str_replace('\\', DIRECTORY_SEPARATOR, preg_replace('#^PhpCsFixer\\\Tests#', 'tests', $testClassName)).'.php'
  299. ));
  300. foreach ($tokens as $token) {
  301. if ($token->isGivenKind(T_DOC_COMMENT)) {
  302. $docBlock = new DocBlock($token->getContent());
  303. $dataProviderAnnotations = $docBlock->getAnnotationsOfType('dataProvider');
  304. foreach ($dataProviderAnnotations as $dataProviderAnnotation) {
  305. if (1 === preg_match('/@dataProvider\s+(?P<methodName>\w+)/', $dataProviderAnnotation->getContent(), $matches)) {
  306. $dataProviderMethodNames[] = $matches['methodName'];
  307. }
  308. }
  309. }
  310. }
  311. $dataProviderMethodNames = array_unique($dataProviderMethodNames);
  312. foreach ($dataProviderMethodNames as $dataProviderMethodName) {
  313. $data[] = array(
  314. $testClassName,
  315. $dataProviderMethodName,
  316. );
  317. }
  318. }
  319. return $data;
  320. }
  321. private function getSrcClasses()
  322. {
  323. static $classes;
  324. if (null !== $classes) {
  325. return $classes;
  326. }
  327. $finder = Finder::create()
  328. ->files()
  329. ->name('*.php')
  330. ->in(__DIR__.'/../../src')
  331. ->exclude(array(
  332. 'Resources',
  333. ))
  334. ;
  335. $classes = array_map(
  336. function (SplFileInfo $file) {
  337. return sprintf(
  338. '%s\\%s%s%s',
  339. 'PhpCsFixer',
  340. strtr($file->getRelativePath(), DIRECTORY_SEPARATOR, '\\'),
  341. $file->getRelativePath() ? '\\' : '',
  342. $file->getBasename('.'.$file->getExtension())
  343. );
  344. },
  345. iterator_to_array($finder, false)
  346. );
  347. sort($classes);
  348. return $classes;
  349. }
  350. private function getTestClasses()
  351. {
  352. static $classes;
  353. if (null !== $classes) {
  354. return $classes;
  355. }
  356. $finder = Finder::create()
  357. ->files()
  358. ->name('*.php')
  359. ->in(__DIR__.'/..')
  360. ->exclude(array(
  361. 'Fixtures',
  362. ))
  363. ;
  364. $classes = array_map(
  365. function (SplFileInfo $file) {
  366. return sprintf(
  367. 'PhpCsFixer\\Tests\\%s%s%s',
  368. strtr($file->getRelativePath(), DIRECTORY_SEPARATOR, '\\'),
  369. $file->getRelativePath() ? '\\' : '',
  370. $file->getBasename('.'.$file->getExtension())
  371. );
  372. },
  373. iterator_to_array($finder, false)
  374. );
  375. sort($classes);
  376. return $classes;
  377. }
  378. /**
  379. * @param \ReflectionClass $rc
  380. *
  381. * @return string[]
  382. */
  383. private function getPublicMethodNames(\ReflectionClass $rc)
  384. {
  385. return array_map(
  386. function (\ReflectionMethod $rm) {
  387. return $rm->getName();
  388. },
  389. $rc->getMethods(\ReflectionMethod::IS_PUBLIC)
  390. );
  391. }
  392. }