3 namespace Drupal\simpletest;
5 use Doctrine\Common\Annotations\SimpleAnnotationReader;
6 use Doctrine\Common\Reflection\StaticReflectionParser;
7 use Drupal\Component\Annotation\Reflection\MockFileFinder;
8 use Drupal\Component\Utility\NestedArray;
9 use Drupal\Core\Cache\CacheBackendInterface;
10 use Drupal\Core\Extension\ExtensionDiscovery;
11 use Drupal\Core\Extension\ModuleHandlerInterface;
12 use Drupal\simpletest\Exception\MissingGroupException;
13 use PHPUnit_Util_Test;
16 * Discovers available tests.
23 * @var \Composer\Autoload\ClassLoader
25 protected $classLoader;
28 * Backend for caching discovery results.
30 * @var \Drupal\Core\Cache\CacheBackendInterface
32 protected $cacheBackend;
35 * Cached map of all test namespaces to respective directories.
39 protected $testNamespaces;
42 * Cached list of all available extension names, keyed by extension type.
46 protected $availableExtensions;
58 * @var \Drupal\Core\Extension\ModuleHandlerInterface
60 protected $moduleHandler;
63 * Constructs a new test discovery.
67 * @param $class_loader
68 * The class loader. Normally Composer's ClassLoader, as included by the
69 * front controller, but may also be decorated; e.g.,
70 * \Symfony\Component\ClassLoader\ApcClassLoader.
71 * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
73 * @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
74 * (optional) Backend for caching discovery results.
76 public function __construct($root, $class_loader, ModuleHandlerInterface $module_handler, CacheBackendInterface $cache_backend = NULL) {
78 $this->classLoader = $class_loader;
79 $this->moduleHandler = $module_handler;
80 $this->cacheBackend = $cache_backend;
84 * Registers test namespaces of all extensions and core test classes.
87 * An associative array whose keys are PSR-4 namespace prefixes and whose
88 * values are directory names.
90 public function registerTestNamespaces() {
91 if (isset($this->testNamespaces)) {
92 return $this->testNamespaces;
94 $this->testNamespaces = [];
96 $existing = $this->classLoader->getPrefixesPsr4();
98 // Add PHPUnit test namespaces of Drupal core.
99 $this->testNamespaces['Drupal\\Tests\\'] = [$this->root . '/core/tests/Drupal/Tests'];
100 $this->testNamespaces['Drupal\\KernelTests\\'] = [$this->root . '/core/tests/Drupal/KernelTests'];
101 $this->testNamespaces['Drupal\\FunctionalTests\\'] = [$this->root . '/core/tests/Drupal/FunctionalTests'];
102 $this->testNamespaces['Drupal\\FunctionalJavascriptTests\\'] = [$this->root . '/core/tests/Drupal/FunctionalJavascriptTests'];
104 $this->availableExtensions = [];
105 foreach ($this->getExtensions() as $name => $extension) {
106 $this->availableExtensions[$extension->getType()][$name] = $name;
108 $base_path = $this->root . '/' . $extension->getPath();
110 // Add namespace of disabled/uninstalled extensions.
111 if (!isset($existing["Drupal\\$name\\"])) {
112 $this->classLoader->addPsr4("Drupal\\$name\\", "$base_path/src");
114 // Add Simpletest test namespace.
115 $this->testNamespaces["Drupal\\$name\\Tests\\"][] = "$base_path/src/Tests";
117 // Add PHPUnit test namespaces.
118 $this->testNamespaces["Drupal\\Tests\\$name\\Unit\\"][] = "$base_path/tests/src/Unit";
119 $this->testNamespaces["Drupal\\Tests\\$name\\Kernel\\"][] = "$base_path/tests/src/Kernel";
120 $this->testNamespaces["Drupal\\Tests\\$name\\Functional\\"][] = "$base_path/tests/src/Functional";
121 $this->testNamespaces["Drupal\\Tests\\$name\\FunctionalJavascript\\"][] = "$base_path/tests/src/FunctionalJavascript";
123 // Add discovery for traits which are shared between different test
125 $this->testNamespaces["Drupal\\Tests\\$name\\Traits\\"][] = "$base_path/tests/src/Traits";
128 foreach ($this->testNamespaces as $prefix => $paths) {
129 $this->classLoader->addPsr4($prefix, $paths);
132 return $this->testNamespaces;
136 * Discovers all available tests in all extensions.
138 * @param string $extension
139 * (optional) The name of an extension to limit discovery to; e.g., 'node'.
140 * @param string[] $types
141 * An array of included test types.
144 * An array of tests keyed by the the group name.
146 * $groups['block'] => array(
147 * 'Drupal\Tests\block\Functional\BlockTest' => array(
148 * 'name' => 'Drupal\Tests\block\Functional\BlockTest',
149 * 'description' => 'Tests block UI CRUD functionality.',
150 * 'group' => 'block',
155 * @todo Remove singular grouping; retain list of groups in 'group' key.
156 * @see https://www.drupal.org/node/2296615
158 public function getTestClasses($extension = NULL, array $types = []) {
159 $reader = new SimpleAnnotationReader();
160 $reader->addNamespace('Drupal\\simpletest\\Annotation');
162 if (!isset($extension)) {
163 if ($this->cacheBackend && $cache = $this->cacheBackend->get('simpletest:discovery:classes')) {
169 $classmap = $this->findAllClassFiles($extension);
171 // Prevent expensive class loader lookups for each reflected test class by
172 // registering the complete classmap of test classes to the class loader.
173 // This also ensures that test classes are loaded from the discovered
174 // pathnames; a namespace/classname mismatch will throw an exception.
175 $this->classLoader->addClassMap($classmap);
177 foreach ($classmap as $classname => $pathname) {
178 $finder = MockFileFinder::create($pathname);
179 $parser = new StaticReflectionParser($classname, $finder, TRUE);
181 $info = static::getTestInfo($classname, $parser->getDocComment());
183 catch (MissingGroupException $e) {
184 // If the class name ends in Test and is not a migrate table dump.
185 if (preg_match('/Test$/', $classname) && strpos($classname, 'migrate_drupal\Tests\Table') === FALSE) {
188 // If the class is @group annotation just skip it. Most likely it is an
189 // abstract class, trait or test fixture.
192 // Skip this test class if it is a Simpletest-based test and requires
193 // unavailable modules. TestDiscovery should not filter out module
194 // requirements for PHPUnit-based test classes.
195 // @todo Move this behavior to \Drupal\simpletest\TestBase so tests can be
196 // marked as skipped, instead.
197 // @see https://www.drupal.org/node/1273478
198 if ($info['type'] == 'Simpletest') {
199 if (!empty($info['requires']['module'])) {
200 if (array_diff($info['requires']['module'], $this->availableExtensions['module'])) {
206 $list[$info['group']][$classname] = $info;
209 // Sort the groups and tests within the groups by name.
210 uksort($list, 'strnatcasecmp');
211 foreach ($list as &$tests) {
212 uksort($tests, 'strnatcasecmp');
215 // Allow modules extending core tests to disable originals.
216 $this->moduleHandler->alter('simpletest', $list);
218 if (!isset($extension)) {
219 if ($this->cacheBackend) {
220 $this->cacheBackend->set('simpletest:discovery:classes', $list);
225 $list = NestedArray::filter($list, function ($element) use ($types) {
226 return !(is_array($element) && isset($element['type']) && !in_array($element['type'], $types));
234 * Discovers all class files in all available extensions.
236 * @param string $extension
237 * (optional) The name of an extension to limit discovery to; e.g., 'node'.
240 * A classmap containing all discovered class files; i.e., a map of
241 * fully-qualified classnames to pathnames.
243 public function findAllClassFiles($extension = NULL) {
245 $namespaces = $this->registerTestNamespaces();
246 if (isset($extension)) {
247 // Include tests in the \Drupal\Tests\{$extension} namespace.
248 $pattern = "/Drupal\\\(Tests\\\)?$extension\\\/";
249 $namespaces = array_intersect_key($namespaces, array_flip(preg_grep($pattern, array_keys($namespaces))));
251 foreach ($namespaces as $namespace => $paths) {
252 foreach ($paths as $path) {
253 if (!is_dir($path)) {
256 $classmap += static::scanDirectory($namespace, $path);
263 * Scans a given directory for class files.
265 * @param string $namespace_prefix
266 * The namespace prefix to use for discovered classes. Must contain a
267 * trailing namespace separator (backslash).
268 * For example: 'Drupal\\node\\Tests\\'
269 * @param string $path
270 * The directory path to scan.
271 * For example: '/path/to/drupal/core/modules/node/tests/src'
274 * An associative array whose keys are fully-qualified class names and whose
275 * values are corresponding filesystem pathnames.
277 * @throws \InvalidArgumentException
278 * If $namespace_prefix does not end in a namespace separator (backslash).
280 * @todo Limit to '*Test.php' files (~10% less files to reflect/introspect).
281 * @see https://www.drupal.org/node/2296635
283 public static function scanDirectory($namespace_prefix, $path) {
284 if (substr($namespace_prefix, -1) !== '\\') {
285 throw new \InvalidArgumentException("Namespace prefix for $path must contain a trailing namespace separator.");
287 $flags = \FilesystemIterator::UNIX_PATHS;
288 $flags |= \FilesystemIterator::SKIP_DOTS;
289 $flags |= \FilesystemIterator::FOLLOW_SYMLINKS;
290 $flags |= \FilesystemIterator::CURRENT_AS_SELF;
292 $iterator = new \RecursiveDirectoryIterator($path, $flags);
293 $filter = new \RecursiveCallbackFilterIterator($iterator, function ($current, $key, $iterator) {
294 if ($iterator->hasChildren()) {
297 return $current->isFile() && $current->getExtension() === 'php';
299 $files = new \RecursiveIteratorIterator($filter);
301 foreach ($files as $fileinfo) {
302 $class = $namespace_prefix;
303 if ('' !== $subpath = $fileinfo->getSubPath()) {
304 $class .= strtr($subpath, '/', '\\') . '\\';
306 $class .= $fileinfo->getBasename('.php');
307 $classes[$class] = $fileinfo->getPathname();
313 * Retrieves information about a test class for UI purposes.
315 * @param string $classname
316 * The test classname.
317 * @param string $doc_comment
318 * (optional) The class PHPDoc comment. If not passed in reflection will be
319 * used but this is very expensive when parsing all the test classes.
322 * An associative array containing:
323 * - name: The test class name.
324 * - description: The test (PHPDoc) summary.
325 * - group: The test's first @group (parsed from PHPDoc annotations).
326 * - requires: An associative array containing test requirements parsed from
327 * PHPDoc annotations:
328 * - module: List of Drupal module extension names the test depends on.
330 * @throws \Drupal\simpletest\Exception\MissingGroupException
331 * If the class does not have a @group annotation.
333 public static function getTestInfo($classname, $doc_comment = NULL) {
335 $reflection = new \ReflectionClass($classname);
336 $doc_comment = $reflection->getDocComment();
339 'name' => $classname,
342 // Look for annotations, allow an arbitrary amount of spaces before the
343 // * but nothing else.
344 preg_match_all('/^[ ]*\* \@([^\s]*) (.*$)/m', $doc_comment, $matches);
345 if (isset($matches[1])) {
346 foreach ($matches[1] as $key => $annotation) {
347 if (!empty($annotations[$annotation])) {
348 // Only have the first match per annotation. This deals with
349 // multiple @group annotations.
352 $annotations[$annotation] = $matches[2][$key];
356 if (empty($annotations['group'])) {
357 // Concrete tests must have a group.
358 throw new MissingGroupException(sprintf('Missing @group annotation in %s', $classname));
360 $info['group'] = $annotations['group'];
361 // Put PHPUnit test suites into their own custom groups.
362 if ($testsuite = static::getPhpunitTestSuite($classname)) {
363 $info['type'] = 'PHPUnit-' . $testsuite;
366 $info['type'] = 'Simpletest';
369 if (!empty($annotations['coversDefaultClass'])) {
370 $info['description'] = 'Tests ' . $annotations['coversDefaultClass'] . '.';
373 $info['description'] = static::parseTestClassSummary($doc_comment);
375 if (isset($annotations['dependencies'])) {
376 $info['requires']['module'] = array_map('trim', explode(',', $annotations['dependencies']));
383 * Parses the phpDoc summary line of a test class.
385 * @param string $doc_comment
388 * The parsed phpDoc summary line. An empty string is returned if no summary
389 * line can be parsed.
391 public static function parseTestClassSummary($doc_comment) {
392 // Normalize line endings.
393 $doc_comment = preg_replace('/\r\n|\r/', '\n', $doc_comment);
394 // Strip leading and trailing doc block lines.
395 $doc_comment = substr($doc_comment, 4, -4);
397 $lines = explode("\n", $doc_comment);
399 // Add every line to the summary until the first empty line or annotation
401 foreach ($lines as $line) {
402 if (preg_match('/^[ ]*\*$/', $line) || preg_match('/^[ ]*\* \@/', $line)) {
405 $summary[] = trim($line, ' *');
407 return implode(' ', $summary);
411 * Parses annotations in the phpDoc of a test class.
413 * @param \ReflectionClass $class
414 * The reflected test class.
417 * An associative array that contains all annotations on the test class;
418 * typically including:
419 * - group: A list of @group values.
420 * - requires: An associative array of @requires values; e.g.:
421 * - module: A list of Drupal module dependencies that are required to
424 * @see PHPUnit_Util_Test::parseTestMethodAnnotations()
425 * @see http://phpunit.de/manual/current/en/incomplete-and-skipped-tests.html#incomplete-and-skipped-tests.skipping-tests-using-requires
427 public static function parseTestClassAnnotations(\ReflectionClass $class) {
428 $annotations = PHPUnit_Util_Test::parseTestMethodAnnotations($class->getName())['class'];
430 // @todo Enhance PHPUnit upstream to allow for custom @requires identifiers.
431 // @see PHPUnit_Util_Test::getRequirements()
432 // @todo Add support for 'PHP', 'OS', 'function', 'extension'.
433 // @see https://www.drupal.org/node/1273478
434 if (isset($annotations['requires'])) {
435 foreach ($annotations['requires'] as $i => $value) {
436 list($type, $value) = explode(' ', $value, 2);
437 if ($type === 'module') {
438 $annotations['requires']['module'][$value] = $value;
439 unset($annotations['requires'][$i]);
447 * Determines the phpunit testsuite for a given classname.
449 * @param string $classname
450 * The test classname.
452 * @return string|false
453 * The testsuite name or FALSE if its not a phpunit test.
455 public static function getPhpunitTestSuite($classname) {
456 if (preg_match('/Drupal\\\\Tests\\\\Core\\\\(\w+)/', $classname, $matches)) {
459 if (preg_match('/Drupal\\\\Tests\\\\Component\\\\(\w+)/', $classname, $matches)) {
463 if (preg_match('/Drupal\\\\Tests\\\\(\w+)\\\\(\w+)/', $classname, $matches)) {
467 elseif (preg_match('/Drupal\\\\(\w*)Tests\\\\/', $classname, $matches)) {
468 if ($matches[1] == '') {
477 * Returns all available extensions.
479 * @return \Drupal\Core\Extension\Extension[]
480 * An array of Extension objects, keyed by extension name.
482 protected function getExtensions() {
483 $listing = new ExtensionDiscovery($this->root);
484 // Ensure that tests in all profiles are discovered.
485 $listing->setProfileDirectories([]);
486 $extensions = $listing->scan('module', TRUE);
487 $extensions += $listing->scan('profile', TRUE);
488 $extensions += $listing->scan('theme', TRUE);