ProjectCodeTest.php 14 KB

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