ProjectCodeTest.php 15 KB

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