TestDiscovery.php 17 KB

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