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\block\Tests\BlockTest' => array(
148 * 'name' => 'Drupal\block\Tests\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 requires unavailable modules.
193 // @todo PHPUnit skips tests with unmet requirements when executing a test
194 // (instead of excluding them upfront). Refactor test runner to follow
196 // @see https://www.drupal.org/node/1273478
197 if (!empty($info['requires']['module'])) {
198 if (array_diff($info['requires']['module'], $this->availableExtensions['module'])) {
203 $list[$info['group']][$classname] = $info;
206 // Sort the groups and tests within the groups by name.
207 uksort($list, 'strnatcasecmp');
208 foreach ($list as &$tests) {
209 uksort($tests, 'strnatcasecmp');
212 // Allow modules extending core tests to disable originals.
213 $this->moduleHandler->alter('simpletest', $list);
215 if (!isset($extension)) {
216 if ($this->cacheBackend) {
217 $this->cacheBackend->set('simpletest:discovery:classes', $list);
222 $list = NestedArray::filter($list, function ($element) use ($types) {
223 return !(is_array($element) && isset($element['type']) && !in_array($element['type'], $types));
231 * Discovers all class files in all available extensions.
233 * @param string $extension
234 * (optional) The name of an extension to limit discovery to; e.g., 'node'.
237 * A classmap containing all discovered class files; i.e., a map of
238 * fully-qualified classnames to pathnames.
240 public function findAllClassFiles($extension = NULL) {
242 $namespaces = $this->registerTestNamespaces();
243 if (isset($extension)) {
244 // Include tests in the \Drupal\Tests\{$extension} namespace.
245 $pattern = "/Drupal\\\(Tests\\\)?$extension\\\/";
246 $namespaces = array_intersect_key($namespaces, array_flip(preg_grep($pattern, array_keys($namespaces))));
248 foreach ($namespaces as $namespace => $paths) {
249 foreach ($paths as $path) {
250 if (!is_dir($path)) {
253 $classmap += static::scanDirectory($namespace, $path);
260 * Scans a given directory for class files.
262 * @param string $namespace_prefix
263 * The namespace prefix to use for discovered classes. Must contain a
264 * trailing namespace separator (backslash).
265 * For example: 'Drupal\\node\\Tests\\'
266 * @param string $path
267 * The directory path to scan.
268 * For example: '/path/to/drupal/core/modules/node/tests/src'
271 * An associative array whose keys are fully-qualified class names and whose
272 * values are corresponding filesystem pathnames.
274 * @throws \InvalidArgumentException
275 * If $namespace_prefix does not end in a namespace separator (backslash).
277 * @todo Limit to '*Test.php' files (~10% less files to reflect/introspect).
278 * @see https://www.drupal.org/node/2296635
280 public static function scanDirectory($namespace_prefix, $path) {
281 if (substr($namespace_prefix, -1) !== '\\') {
282 throw new \InvalidArgumentException("Namespace prefix for $path must contain a trailing namespace separator.");
284 $flags = \FilesystemIterator::UNIX_PATHS;
285 $flags |= \FilesystemIterator::SKIP_DOTS;
286 $flags |= \FilesystemIterator::FOLLOW_SYMLINKS;
287 $flags |= \FilesystemIterator::CURRENT_AS_SELF;
289 $iterator = new \RecursiveDirectoryIterator($path, $flags);
290 $filter = new \RecursiveCallbackFilterIterator($iterator, function ($current, $key, $iterator) {
291 if ($iterator->hasChildren()) {
294 return $current->isFile() && $current->getExtension() === 'php';
296 $files = new \RecursiveIteratorIterator($filter);
298 foreach ($files as $fileinfo) {
299 $class = $namespace_prefix;
300 if ('' !== $subpath = $fileinfo->getSubPath()) {
301 $class .= strtr($subpath, '/', '\\') . '\\';
303 $class .= $fileinfo->getBasename('.php');
304 $classes[$class] = $fileinfo->getPathname();
310 * Retrieves information about a test class for UI purposes.
312 * @param string $class
313 * The test classname.
314 * @param string $doc_comment
315 * (optional) The class PHPDoc comment. If not passed in reflection will be
316 * used but this is very expensive when parsing all the test classes.
319 * An associative array containing:
320 * - name: The test class name.
321 * - description: The test (PHPDoc) summary.
322 * - group: The test's first @group (parsed from PHPDoc annotations).
323 * - requires: An associative array containing test requirements parsed from
324 * PHPDoc annotations:
325 * - module: List of Drupal module extension names the test depends on.
327 * @throws \Drupal\simpletest\Exception\MissingGroupException
328 * If the class does not have a @group annotation.
330 public static function getTestInfo($classname, $doc_comment = NULL) {
332 $reflection = new \ReflectionClass($classname);
333 $doc_comment = $reflection->getDocComment();
336 'name' => $classname,
339 // Look for annotations, allow an arbitrary amount of spaces before the
340 // * but nothing else.
341 preg_match_all('/^[ ]*\* \@([^\s]*) (.*$)/m', $doc_comment, $matches);
342 if (isset($matches[1])) {
343 foreach ($matches[1] as $key => $annotation) {
344 if (!empty($annotations[$annotation])) {
345 // Only have the first match per annotation. This deals with
346 // multiple @group annotations.
349 $annotations[$annotation] = $matches[2][$key];
353 if (empty($annotations['group'])) {
354 // Concrete tests must have a group.
355 throw new MissingGroupException(sprintf('Missing @group annotation in %s', $classname));
357 $info['group'] = $annotations['group'];
358 // Put PHPUnit test suites into their own custom groups.
359 if ($testsuite = static::getPhpunitTestSuite($classname)) {
360 $info['type'] = 'PHPUnit-' . $testsuite;
363 $info['type'] = 'Simpletest';
366 if (!empty($annotations['coversDefaultClass'])) {
367 $info['description'] = 'Tests ' . $annotations['coversDefaultClass'] . '.';
370 $info['description'] = static::parseTestClassSummary($doc_comment);
372 if (isset($annotations['dependencies'])) {
373 $info['requires']['module'] = array_map('trim', explode(',', $annotations['dependencies']));
380 * Parses the phpDoc summary line of a test class.
382 * @param string $doc_comment
385 * The parsed phpDoc summary line. An empty string is returned if no summary
386 * line can be parsed.
388 public static function parseTestClassSummary($doc_comment) {
389 // Normalize line endings.
390 $doc_comment = preg_replace('/\r\n|\r/', '\n', $doc_comment);
391 // Strip leading and trailing doc block lines.
392 $doc_comment = substr($doc_comment, 4, -4);
394 $lines = explode("\n", $doc_comment);
396 // Add every line to the summary until the first empty line or annotation
398 foreach ($lines as $line) {
399 if (preg_match('/^[ ]*\*$/', $line) || preg_match('/^[ ]*\* \@/', $line)) {
402 $summary[] = trim($line, ' *');
404 return implode(' ', $summary);
408 * Parses annotations in the phpDoc of a test class.
410 * @param \ReflectionClass $class
411 * The reflected test class.
414 * An associative array that contains all annotations on the test class;
415 * typically including:
416 * - group: A list of @group values.
417 * - requires: An associative array of @requires values; e.g.:
418 * - module: A list of Drupal module dependencies that are required to
421 * @see PHPUnit_Util_Test::parseTestMethodAnnotations()
422 * @see http://phpunit.de/manual/current/en/incomplete-and-skipped-tests.html#incomplete-and-skipped-tests.skipping-tests-using-requires
424 public static function parseTestClassAnnotations(\ReflectionClass $class) {
425 $annotations = PHPUnit_Util_Test::parseTestMethodAnnotations($class->getName())['class'];
427 // @todo Enhance PHPUnit upstream to allow for custom @requires identifiers.
428 // @see PHPUnit_Util_Test::getRequirements()
429 // @todo Add support for 'PHP', 'OS', 'function', 'extension'.
430 // @see https://www.drupal.org/node/1273478
431 if (isset($annotations['requires'])) {
432 foreach ($annotations['requires'] as $i => $value) {
433 list($type, $value) = explode(' ', $value, 2);
434 if ($type === 'module') {
435 $annotations['requires']['module'][$value] = $value;
436 unset($annotations['requires'][$i]);
444 * Determines the phpunit testsuite for a given classname.
446 * @param string $classname
447 * The test classname.
449 * @return string|false
450 * The testsuite name or FALSE if its not a phpunit test.
452 public static function getPhpunitTestSuite($classname) {
453 if (preg_match('/Drupal\\\\Tests\\\\Core\\\\(\w+)/', $classname, $matches)) {
456 if (preg_match('/Drupal\\\\Tests\\\\Component\\\\(\w+)/', $classname, $matches)) {
460 if (preg_match('/Drupal\\\\Tests\\\\(\w+)\\\\(\w+)/', $classname, $matches)) {
464 elseif (preg_match('/Drupal\\\\(\w*)Tests\\\\/', $classname, $matches)) {
465 if ($matches[1] == '') {
474 * Returns all available extensions.
476 * @return \Drupal\Core\Extension\Extension[]
477 * An array of Extension objects, keyed by extension name.
479 protected function getExtensions() {
480 $listing = new ExtensionDiscovery($this->root);
481 // Ensure that tests in all profiles are discovered.
482 $listing->setProfileDirectories([]);
483 $extensions = $listing->scan('module', TRUE);
484 $extensions += $listing->scan('profile', TRUE);
485 $extensions += $listing->scan('theme', TRUE);