TestDiscovery.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. <?php
  2. namespace Drupal\simpletest;
  3. use Doctrine\Common\Annotations\SimpleAnnotationReader;
  4. use Doctrine\Common\Reflection\StaticReflectionParser;
  5. use Drupal\Component\Annotation\Reflection\MockFileFinder;
  6. use Drupal\Component\Utility\NestedArray;
  7. use Drupal\Core\Cache\CacheBackendInterface;
  8. use Drupal\Core\Extension\ExtensionDiscovery;
  9. use Drupal\Core\Extension\ModuleHandlerInterface;
  10. use Drupal\simpletest\Exception\MissingGroupException;
  11. use PHPUnit_Util_Test;
  12. /**
  13. * Discovers available tests.
  14. */
  15. class TestDiscovery {
  16. /**
  17. * The class loader.
  18. *
  19. * @var \Composer\Autoload\ClassLoader
  20. */
  21. protected $classLoader;
  22. /**
  23. * Backend for caching discovery results.
  24. *
  25. * @var \Drupal\Core\Cache\CacheBackendInterface
  26. */
  27. protected $cacheBackend;
  28. /**
  29. * Cached map of all test namespaces to respective directories.
  30. *
  31. * @var array
  32. */
  33. protected $testNamespaces;
  34. /**
  35. * Cached list of all available extension names, keyed by extension type.
  36. *
  37. * @var array
  38. */
  39. protected $availableExtensions;
  40. /**
  41. * The app root.
  42. *
  43. * @var string
  44. */
  45. protected $root;
  46. /**
  47. * The module handler.
  48. *
  49. * @var \Drupal\Core\Extension\ModuleHandlerInterface
  50. */
  51. protected $moduleHandler;
  52. /**
  53. * Constructs a new test discovery.
  54. *
  55. * @param string $root
  56. * The app root.
  57. * @param $class_loader
  58. * The class loader. Normally Composer's ClassLoader, as included by the
  59. * front controller, but may also be decorated; e.g.,
  60. * \Symfony\Component\ClassLoader\ApcClassLoader.
  61. * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
  62. * The module handler.
  63. * @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
  64. * (optional) Backend for caching discovery results.
  65. */
  66. public function __construct($root, $class_loader, ModuleHandlerInterface $module_handler, CacheBackendInterface $cache_backend = NULL) {
  67. $this->root = $root;
  68. $this->classLoader = $class_loader;
  69. $this->moduleHandler = $module_handler;
  70. $this->cacheBackend = $cache_backend;
  71. }
  72. /**
  73. * Registers test namespaces of all extensions and core test classes.
  74. *
  75. * @return array
  76. * An associative array whose keys are PSR-4 namespace prefixes and whose
  77. * values are directory names.
  78. */
  79. public function registerTestNamespaces() {
  80. if (isset($this->testNamespaces)) {
  81. return $this->testNamespaces;
  82. }
  83. $this->testNamespaces = [];
  84. $existing = $this->classLoader->getPrefixesPsr4();
  85. // Add PHPUnit test namespaces of Drupal core.
  86. $this->testNamespaces['Drupal\\Tests\\'] = [$this->root . '/core/tests/Drupal/Tests'];
  87. $this->testNamespaces['Drupal\\KernelTests\\'] = [$this->root . '/core/tests/Drupal/KernelTests'];
  88. $this->testNamespaces['Drupal\\FunctionalTests\\'] = [$this->root . '/core/tests/Drupal/FunctionalTests'];
  89. $this->testNamespaces['Drupal\\FunctionalJavascriptTests\\'] = [$this->root . '/core/tests/Drupal/FunctionalJavascriptTests'];
  90. $this->availableExtensions = [];
  91. foreach ($this->getExtensions() as $name => $extension) {
  92. $this->availableExtensions[$extension->getType()][$name] = $name;
  93. $base_path = $this->root . '/' . $extension->getPath();
  94. // Add namespace of disabled/uninstalled extensions.
  95. if (!isset($existing["Drupal\\$name\\"])) {
  96. $this->classLoader->addPsr4("Drupal\\$name\\", "$base_path/src");
  97. }
  98. // Add Simpletest test namespace.
  99. $this->testNamespaces["Drupal\\$name\\Tests\\"][] = "$base_path/src/Tests";
  100. // Add PHPUnit test namespaces.
  101. $this->testNamespaces["Drupal\\Tests\\$name\\Unit\\"][] = "$base_path/tests/src/Unit";
  102. $this->testNamespaces["Drupal\\Tests\\$name\\Kernel\\"][] = "$base_path/tests/src/Kernel";
  103. $this->testNamespaces["Drupal\\Tests\\$name\\Functional\\"][] = "$base_path/tests/src/Functional";
  104. $this->testNamespaces["Drupal\\Tests\\$name\\FunctionalJavascript\\"][] = "$base_path/tests/src/FunctionalJavascript";
  105. // Add discovery for traits which are shared between different test
  106. // suites.
  107. $this->testNamespaces["Drupal\\Tests\\$name\\Traits\\"][] = "$base_path/tests/src/Traits";
  108. }
  109. foreach ($this->testNamespaces as $prefix => $paths) {
  110. $this->classLoader->addPsr4($prefix, $paths);
  111. }
  112. return $this->testNamespaces;
  113. }
  114. /**
  115. * Discovers all available tests in all extensions.
  116. *
  117. * @param string $extension
  118. * (optional) The name of an extension to limit discovery to; e.g., 'node'.
  119. * @param string[] $types
  120. * An array of included test types.
  121. *
  122. * @return array
  123. * An array of tests keyed by the the group name.
  124. * @code
  125. * $groups['block'] => array(
  126. * 'Drupal\Tests\block\Functional\BlockTest' => array(
  127. * 'name' => 'Drupal\Tests\block\Functional\BlockTest',
  128. * 'description' => 'Tests block UI CRUD functionality.',
  129. * 'group' => 'block',
  130. * ),
  131. * );
  132. * @endcode
  133. *
  134. * @todo Remove singular grouping; retain list of groups in 'group' key.
  135. * @see https://www.drupal.org/node/2296615
  136. */
  137. public function getTestClasses($extension = NULL, array $types = []) {
  138. $reader = new SimpleAnnotationReader();
  139. $reader->addNamespace('Drupal\\simpletest\\Annotation');
  140. if (!isset($extension)) {
  141. if ($this->cacheBackend && $cache = $this->cacheBackend->get('simpletest:discovery:classes')) {
  142. return $cache->data;
  143. }
  144. }
  145. $list = [];
  146. $classmap = $this->findAllClassFiles($extension);
  147. // Prevent expensive class loader lookups for each reflected test class by
  148. // registering the complete classmap of test classes to the class loader.
  149. // This also ensures that test classes are loaded from the discovered
  150. // pathnames; a namespace/classname mismatch will throw an exception.
  151. $this->classLoader->addClassMap($classmap);
  152. foreach ($classmap as $classname => $pathname) {
  153. $finder = MockFileFinder::create($pathname);
  154. $parser = new StaticReflectionParser($classname, $finder, TRUE);
  155. try {
  156. $info = static::getTestInfo($classname, $parser->getDocComment());
  157. }
  158. catch (MissingGroupException $e) {
  159. // If the class name ends in Test and is not a migrate table dump.
  160. if (preg_match('/Test$/', $classname) && strpos($classname, 'migrate_drupal\Tests\Table') === FALSE) {
  161. throw $e;
  162. }
  163. // If the class is @group annotation just skip it. Most likely it is an
  164. // abstract class, trait or test fixture.
  165. continue;
  166. }
  167. // Skip this test class if it is a Simpletest-based test and requires
  168. // unavailable modules. TestDiscovery should not filter out module
  169. // requirements for PHPUnit-based test classes.
  170. // @todo Move this behavior to \Drupal\simpletest\TestBase so tests can be
  171. // marked as skipped, instead.
  172. // @see https://www.drupal.org/node/1273478
  173. if ($info['type'] == 'Simpletest') {
  174. if (!empty($info['requires']['module'])) {
  175. if (array_diff($info['requires']['module'], $this->availableExtensions['module'])) {
  176. continue;
  177. }
  178. }
  179. }
  180. $list[$info['group']][$classname] = $info;
  181. }
  182. // Sort the groups and tests within the groups by name.
  183. uksort($list, 'strnatcasecmp');
  184. foreach ($list as &$tests) {
  185. uksort($tests, 'strnatcasecmp');
  186. }
  187. // Allow modules extending core tests to disable originals.
  188. $this->moduleHandler->alter('simpletest', $list);
  189. if (!isset($extension)) {
  190. if ($this->cacheBackend) {
  191. $this->cacheBackend->set('simpletest:discovery:classes', $list);
  192. }
  193. }
  194. if ($types) {
  195. $list = NestedArray::filter($list, function ($element) use ($types) {
  196. return !(is_array($element) && isset($element['type']) && !in_array($element['type'], $types));
  197. });
  198. }
  199. return $list;
  200. }
  201. /**
  202. * Discovers all class files in all available extensions.
  203. *
  204. * @param string $extension
  205. * (optional) The name of an extension to limit discovery to; e.g., 'node'.
  206. *
  207. * @return array
  208. * A classmap containing all discovered class files; i.e., a map of
  209. * fully-qualified classnames to pathnames.
  210. */
  211. public function findAllClassFiles($extension = NULL) {
  212. $classmap = [];
  213. $namespaces = $this->registerTestNamespaces();
  214. if (isset($extension)) {
  215. // Include tests in the \Drupal\Tests\{$extension} namespace.
  216. $pattern = "/Drupal\\\(Tests\\\)?$extension\\\/";
  217. $namespaces = array_intersect_key($namespaces, array_flip(preg_grep($pattern, array_keys($namespaces))));
  218. }
  219. foreach ($namespaces as $namespace => $paths) {
  220. foreach ($paths as $path) {
  221. if (!is_dir($path)) {
  222. continue;
  223. }
  224. $classmap += static::scanDirectory($namespace, $path);
  225. }
  226. }
  227. return $classmap;
  228. }
  229. /**
  230. * Scans a given directory for class files.
  231. *
  232. * @param string $namespace_prefix
  233. * The namespace prefix to use for discovered classes. Must contain a
  234. * trailing namespace separator (backslash).
  235. * For example: 'Drupal\\node\\Tests\\'
  236. * @param string $path
  237. * The directory path to scan.
  238. * For example: '/path/to/drupal/core/modules/node/tests/src'
  239. *
  240. * @return array
  241. * An associative array whose keys are fully-qualified class names and whose
  242. * values are corresponding filesystem pathnames.
  243. *
  244. * @throws \InvalidArgumentException
  245. * If $namespace_prefix does not end in a namespace separator (backslash).
  246. *
  247. * @todo Limit to '*Test.php' files (~10% less files to reflect/introspect).
  248. * @see https://www.drupal.org/node/2296635
  249. */
  250. public static function scanDirectory($namespace_prefix, $path) {
  251. if (substr($namespace_prefix, -1) !== '\\') {
  252. throw new \InvalidArgumentException("Namespace prefix for $path must contain a trailing namespace separator.");
  253. }
  254. $flags = \FilesystemIterator::UNIX_PATHS;
  255. $flags |= \FilesystemIterator::SKIP_DOTS;
  256. $flags |= \FilesystemIterator::FOLLOW_SYMLINKS;
  257. $flags |= \FilesystemIterator::CURRENT_AS_SELF;
  258. $iterator = new \RecursiveDirectoryIterator($path, $flags);
  259. $filter = new \RecursiveCallbackFilterIterator($iterator, function ($current, $key, $iterator) {
  260. if ($iterator->hasChildren()) {
  261. return TRUE;
  262. }
  263. return $current->isFile() && $current->getExtension() === 'php';
  264. });
  265. $files = new \RecursiveIteratorIterator($filter);
  266. $classes = [];
  267. foreach ($files as $fileinfo) {
  268. $class = $namespace_prefix;
  269. if ('' !== $subpath = $fileinfo->getSubPath()) {
  270. $class .= strtr($subpath, '/', '\\') . '\\';
  271. }
  272. $class .= $fileinfo->getBasename('.php');
  273. $classes[$class] = $fileinfo->getPathname();
  274. }
  275. return $classes;
  276. }
  277. /**
  278. * Retrieves information about a test class for UI purposes.
  279. *
  280. * @param string $classname
  281. * The test classname.
  282. * @param string $doc_comment
  283. * (optional) The class PHPDoc comment. If not passed in reflection will be
  284. * used but this is very expensive when parsing all the test classes.
  285. *
  286. * @return array
  287. * An associative array containing:
  288. * - name: The test class name.
  289. * - description: The test (PHPDoc) summary.
  290. * - group: The test's first @group (parsed from PHPDoc annotations).
  291. * - requires: An associative array containing test requirements parsed from
  292. * PHPDoc annotations:
  293. * - module: List of Drupal module extension names the test depends on.
  294. *
  295. * @throws \Drupal\simpletest\Exception\MissingGroupException
  296. * If the class does not have a @group annotation.
  297. */
  298. public static function getTestInfo($classname, $doc_comment = NULL) {
  299. if (!$doc_comment) {
  300. $reflection = new \ReflectionClass($classname);
  301. $doc_comment = $reflection->getDocComment();
  302. }
  303. $info = [
  304. 'name' => $classname,
  305. ];
  306. $annotations = [];
  307. // Look for annotations, allow an arbitrary amount of spaces before the
  308. // * but nothing else.
  309. preg_match_all('/^[ ]*\* \@([^\s]*) (.*$)/m', $doc_comment, $matches);
  310. if (isset($matches[1])) {
  311. foreach ($matches[1] as $key => $annotation) {
  312. if (!empty($annotations[$annotation])) {
  313. // Only have the first match per annotation. This deals with
  314. // multiple @group annotations.
  315. continue;
  316. }
  317. $annotations[$annotation] = $matches[2][$key];
  318. }
  319. }
  320. if (empty($annotations['group'])) {
  321. // Concrete tests must have a group.
  322. throw new MissingGroupException(sprintf('Missing @group annotation in %s', $classname));
  323. }
  324. $info['group'] = $annotations['group'];
  325. // Put PHPUnit test suites into their own custom groups.
  326. if ($testsuite = static::getPhpunitTestSuite($classname)) {
  327. $info['type'] = 'PHPUnit-' . $testsuite;
  328. }
  329. else {
  330. $info['type'] = 'Simpletest';
  331. }
  332. if (!empty($annotations['coversDefaultClass'])) {
  333. $info['description'] = 'Tests ' . $annotations['coversDefaultClass'] . '.';
  334. }
  335. else {
  336. $info['description'] = static::parseTestClassSummary($doc_comment);
  337. }
  338. if (isset($annotations['dependencies'])) {
  339. $info['requires']['module'] = array_map('trim', explode(',', $annotations['dependencies']));
  340. }
  341. return $info;
  342. }
  343. /**
  344. * Parses the phpDoc summary line of a test class.
  345. *
  346. * @param string $doc_comment
  347. *
  348. * @return string
  349. * The parsed phpDoc summary line. An empty string is returned if no summary
  350. * line can be parsed.
  351. */
  352. public static function parseTestClassSummary($doc_comment) {
  353. // Normalize line endings.
  354. $doc_comment = preg_replace('/\r\n|\r/', '\n', $doc_comment);
  355. // Strip leading and trailing doc block lines.
  356. $doc_comment = substr($doc_comment, 4, -4);
  357. $lines = explode("\n", $doc_comment);
  358. $summary = [];
  359. // Add every line to the summary until the first empty line or annotation
  360. // is found.
  361. foreach ($lines as $line) {
  362. if (preg_match('/^[ ]*\*$/', $line) || preg_match('/^[ ]*\* \@/', $line)) {
  363. break;
  364. }
  365. $summary[] = trim($line, ' *');
  366. }
  367. return implode(' ', $summary);
  368. }
  369. /**
  370. * Parses annotations in the phpDoc of a test class.
  371. *
  372. * @param \ReflectionClass $class
  373. * The reflected test class.
  374. *
  375. * @return array
  376. * An associative array that contains all annotations on the test class;
  377. * typically including:
  378. * - group: A list of @group values.
  379. * - requires: An associative array of @requires values; e.g.:
  380. * - module: A list of Drupal module dependencies that are required to
  381. * exist.
  382. *
  383. * @see PHPUnit_Util_Test::parseTestMethodAnnotations()
  384. * @see http://phpunit.de/manual/current/en/incomplete-and-skipped-tests.html#incomplete-and-skipped-tests.skipping-tests-using-requires
  385. */
  386. public static function parseTestClassAnnotations(\ReflectionClass $class) {
  387. $annotations = PHPUnit_Util_Test::parseTestMethodAnnotations($class->getName())['class'];
  388. // @todo Enhance PHPUnit upstream to allow for custom @requires identifiers.
  389. // @see PHPUnit_Util_Test::getRequirements()
  390. // @todo Add support for 'PHP', 'OS', 'function', 'extension'.
  391. // @see https://www.drupal.org/node/1273478
  392. if (isset($annotations['requires'])) {
  393. foreach ($annotations['requires'] as $i => $value) {
  394. list($type, $value) = explode(' ', $value, 2);
  395. if ($type === 'module') {
  396. $annotations['requires']['module'][$value] = $value;
  397. unset($annotations['requires'][$i]);
  398. }
  399. }
  400. }
  401. return $annotations;
  402. }
  403. /**
  404. * Determines the phpunit testsuite for a given classname.
  405. *
  406. * @param string $classname
  407. * The test classname.
  408. *
  409. * @return string|false
  410. * The testsuite name or FALSE if its not a phpunit test.
  411. */
  412. public static function getPhpunitTestSuite($classname) {
  413. if (preg_match('/Drupal\\\\Tests\\\\Core\\\\(\w+)/', $classname, $matches)) {
  414. return 'Unit';
  415. }
  416. if (preg_match('/Drupal\\\\Tests\\\\Component\\\\(\w+)/', $classname, $matches)) {
  417. return 'Unit';
  418. }
  419. // Module tests.
  420. if (preg_match('/Drupal\\\\Tests\\\\(\w+)\\\\(\w+)/', $classname, $matches)) {
  421. return $matches[2];
  422. }
  423. // Core tests.
  424. elseif (preg_match('/Drupal\\\\(\w*)Tests\\\\/', $classname, $matches)) {
  425. if ($matches[1] == '') {
  426. return 'Unit';
  427. }
  428. return $matches[1];
  429. }
  430. return FALSE;
  431. }
  432. /**
  433. * Returns all available extensions.
  434. *
  435. * @return \Drupal\Core\Extension\Extension[]
  436. * An array of Extension objects, keyed by extension name.
  437. */
  438. protected function getExtensions() {
  439. $listing = new ExtensionDiscovery($this->root);
  440. // Ensure that tests in all profiles are discovered.
  441. $listing->setProfileDirectories([]);
  442. $extensions = $listing->scan('module', TRUE);
  443. $extensions += $listing->scan('profile', TRUE);
  444. $extensions += $listing->scan('theme', TRUE);
  445. return $extensions;
  446. }
  447. }