Version 1
[yaffs-website] / web / core / modules / simpletest / src / TestDiscovery.php
1 <?php
2
3 namespace Drupal\simpletest;
4
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;
14
15 /**
16  * Discovers available tests.
17  */
18 class TestDiscovery {
19
20   /**
21    * The class loader.
22    *
23    * @var \Composer\Autoload\ClassLoader
24    */
25   protected $classLoader;
26
27   /**
28    * Backend for caching discovery results.
29    *
30    * @var \Drupal\Core\Cache\CacheBackendInterface
31    */
32   protected $cacheBackend;
33
34   /**
35    * Cached map of all test namespaces to respective directories.
36    *
37    * @var array
38    */
39   protected $testNamespaces;
40
41   /**
42    * Cached list of all available extension names, keyed by extension type.
43    *
44    * @var array
45    */
46   protected $availableExtensions;
47
48   /**
49    * The app root.
50    *
51    * @var string
52    */
53   protected $root;
54
55   /**
56    * The module handler.
57    *
58    * @var \Drupal\Core\Extension\ModuleHandlerInterface
59    */
60   protected $moduleHandler;
61
62   /**
63    * Constructs a new test discovery.
64    *
65    * @param string $root
66    *   The app root.
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
72    *   The module handler.
73    * @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
74    *   (optional) Backend for caching discovery results.
75    */
76   public function __construct($root, $class_loader, ModuleHandlerInterface $module_handler, CacheBackendInterface $cache_backend = NULL) {
77     $this->root = $root;
78     $this->classLoader = $class_loader;
79     $this->moduleHandler = $module_handler;
80     $this->cacheBackend = $cache_backend;
81   }
82
83   /**
84    * Registers test namespaces of all extensions and core test classes.
85    *
86    * @return array
87    *   An associative array whose keys are PSR-4 namespace prefixes and whose
88    *   values are directory names.
89    */
90   public function registerTestNamespaces() {
91     if (isset($this->testNamespaces)) {
92       return $this->testNamespaces;
93     }
94     $this->testNamespaces = [];
95
96     $existing = $this->classLoader->getPrefixesPsr4();
97
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'];
103
104     $this->availableExtensions = [];
105     foreach ($this->getExtensions() as $name => $extension) {
106       $this->availableExtensions[$extension->getType()][$name] = $name;
107
108       $base_path = $this->root . '/' . $extension->getPath();
109
110       // Add namespace of disabled/uninstalled extensions.
111       if (!isset($existing["Drupal\\$name\\"])) {
112         $this->classLoader->addPsr4("Drupal\\$name\\", "$base_path/src");
113       }
114       // Add Simpletest test namespace.
115       $this->testNamespaces["Drupal\\$name\\Tests\\"][] = "$base_path/src/Tests";
116
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";
122
123       // Add discovery for traits which are shared between different test
124       // suites.
125       $this->testNamespaces["Drupal\\Tests\\$name\\Traits\\"][] = "$base_path/tests/src/Traits";
126     }
127
128     foreach ($this->testNamespaces as $prefix => $paths) {
129       $this->classLoader->addPsr4($prefix, $paths);
130     }
131
132     return $this->testNamespaces;
133   }
134
135   /**
136    * Discovers all available tests in all extensions.
137    *
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.
142    *
143    * @return array
144    *   An array of tests keyed by the the group name.
145    * @code
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',
151    *       ),
152    *     );
153    * @endcode
154    *
155    * @todo Remove singular grouping; retain list of groups in 'group' key.
156    * @see https://www.drupal.org/node/2296615
157    */
158   public function getTestClasses($extension = NULL, array $types = []) {
159     $reader = new SimpleAnnotationReader();
160     $reader->addNamespace('Drupal\\simpletest\\Annotation');
161
162     if (!isset($extension)) {
163       if ($this->cacheBackend && $cache = $this->cacheBackend->get('simpletest:discovery:classes')) {
164         return $cache->data;
165       }
166     }
167     $list = [];
168
169     $classmap = $this->findAllClassFiles($extension);
170
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);
176
177     foreach ($classmap as $classname => $pathname) {
178       $finder = MockFileFinder::create($pathname);
179       $parser = new StaticReflectionParser($classname, $finder, TRUE);
180       try {
181         $info = static::getTestInfo($classname, $parser->getDocComment());
182       }
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) {
186           throw $e;
187         }
188         // If the class is @group annotation just skip it. Most likely it is an
189         // abstract class, trait or test fixture.
190         continue;
191       }
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
195       //   that approach.
196       // @see https://www.drupal.org/node/1273478
197       if (!empty($info['requires']['module'])) {
198         if (array_diff($info['requires']['module'], $this->availableExtensions['module'])) {
199           continue;
200         }
201       }
202
203       $list[$info['group']][$classname] = $info;
204     }
205
206     // Sort the groups and tests within the groups by name.
207     uksort($list, 'strnatcasecmp');
208     foreach ($list as &$tests) {
209       uksort($tests, 'strnatcasecmp');
210     }
211
212     // Allow modules extending core tests to disable originals.
213     $this->moduleHandler->alter('simpletest', $list);
214
215     if (!isset($extension)) {
216       if ($this->cacheBackend) {
217         $this->cacheBackend->set('simpletest:discovery:classes', $list);
218       }
219     }
220
221     if ($types) {
222       $list = NestedArray::filter($list, function ($element) use ($types) {
223         return !(is_array($element) && isset($element['type']) && !in_array($element['type'], $types));
224       });
225     }
226
227     return $list;
228   }
229
230   /**
231    * Discovers all class files in all available extensions.
232    *
233    * @param string $extension
234    *   (optional) The name of an extension to limit discovery to; e.g., 'node'.
235    *
236    * @return array
237    *   A classmap containing all discovered class files; i.e., a map of
238    *   fully-qualified classnames to pathnames.
239    */
240   public function findAllClassFiles($extension = NULL) {
241     $classmap = [];
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))));
247     }
248     foreach ($namespaces as $namespace => $paths) {
249       foreach ($paths as $path) {
250         if (!is_dir($path)) {
251           continue;
252         }
253         $classmap += static::scanDirectory($namespace, $path);
254       }
255     }
256     return $classmap;
257   }
258
259   /**
260    * Scans a given directory for class files.
261    *
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'
269    *
270    * @return array
271    *   An associative array whose keys are fully-qualified class names and whose
272    *   values are corresponding filesystem pathnames.
273    *
274    * @throws \InvalidArgumentException
275    *   If $namespace_prefix does not end in a namespace separator (backslash).
276    *
277    * @todo Limit to '*Test.php' files (~10% less files to reflect/introspect).
278    * @see https://www.drupal.org/node/2296635
279    */
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.");
283     }
284     $flags = \FilesystemIterator::UNIX_PATHS;
285     $flags |= \FilesystemIterator::SKIP_DOTS;
286     $flags |= \FilesystemIterator::FOLLOW_SYMLINKS;
287     $flags |= \FilesystemIterator::CURRENT_AS_SELF;
288
289     $iterator = new \RecursiveDirectoryIterator($path, $flags);
290     $filter = new \RecursiveCallbackFilterIterator($iterator, function ($current, $key, $iterator) {
291       if ($iterator->hasChildren()) {
292         return TRUE;
293       }
294       return $current->isFile() && $current->getExtension() === 'php';
295     });
296     $files = new \RecursiveIteratorIterator($filter);
297     $classes = [];
298     foreach ($files as $fileinfo) {
299       $class = $namespace_prefix;
300       if ('' !== $subpath = $fileinfo->getSubPath()) {
301         $class .= strtr($subpath, '/', '\\') . '\\';
302       }
303       $class .= $fileinfo->getBasename('.php');
304       $classes[$class] = $fileinfo->getPathname();
305     }
306     return $classes;
307   }
308
309   /**
310    * Retrieves information about a test class for UI purposes.
311    *
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.
317    *
318    * @return array
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.
326    *
327    * @throws \Drupal\simpletest\Exception\MissingGroupException
328    *   If the class does not have a @group annotation.
329    */
330   public static function getTestInfo($classname, $doc_comment = NULL) {
331     if (!$doc_comment) {
332       $reflection = new \ReflectionClass($classname);
333       $doc_comment = $reflection->getDocComment();
334     }
335     $info = [
336       'name' => $classname,
337     ];
338     $annotations = [];
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.
347           continue;
348         }
349         $annotations[$annotation] = $matches[2][$key];
350       }
351     }
352
353     if (empty($annotations['group'])) {
354       // Concrete tests must have a group.
355       throw new MissingGroupException(sprintf('Missing @group annotation in %s', $classname));
356     }
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;
361     }
362     else {
363       $info['type'] = 'Simpletest';
364     }
365
366     if (!empty($annotations['coversDefaultClass'])) {
367       $info['description'] = 'Tests ' . $annotations['coversDefaultClass'] . '.';
368     }
369     else {
370       $info['description'] = static::parseTestClassSummary($doc_comment);
371     }
372     if (isset($annotations['dependencies'])) {
373       $info['requires']['module'] = array_map('trim', explode(',', $annotations['dependencies']));
374     }
375
376     return $info;
377   }
378
379   /**
380    * Parses the phpDoc summary line of a test class.
381    *
382    * @param string $doc_comment
383    *
384    * @return string
385    *   The parsed phpDoc summary line. An empty string is returned if no summary
386    *   line can be parsed.
387    */
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);
393
394     $lines = explode("\n", $doc_comment);
395     $summary = [];
396     // Add every line to the summary until the first empty line or annotation
397     // is found.
398     foreach ($lines as $line) {
399       if (preg_match('/^[ ]*\*$/', $line) || preg_match('/^[ ]*\* \@/', $line)) {
400         break;
401       }
402       $summary[] = trim($line, ' *');
403     }
404     return implode(' ', $summary);
405   }
406
407   /**
408    * Parses annotations in the phpDoc of a test class.
409    *
410    * @param \ReflectionClass $class
411    *   The reflected test class.
412    *
413    * @return array
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
419    *       exist.
420    *
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
423    */
424   public static function parseTestClassAnnotations(\ReflectionClass $class) {
425     $annotations = PHPUnit_Util_Test::parseTestMethodAnnotations($class->getName())['class'];
426
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]);
437         }
438       }
439     }
440     return $annotations;
441   }
442
443   /**
444    * Determines the phpunit testsuite for a given classname.
445    *
446    * @param string $classname
447    *   The test classname.
448    *
449    * @return string|false
450    *   The testsuite name or FALSE if its not a phpunit test.
451    */
452   public static function getPhpunitTestSuite($classname) {
453     if (preg_match('/Drupal\\\\Tests\\\\Core\\\\(\w+)/', $classname, $matches)) {
454       return 'Unit';
455     }
456     if (preg_match('/Drupal\\\\Tests\\\\Component\\\\(\w+)/', $classname, $matches)) {
457       return 'Unit';
458     }
459     // Module tests.
460     if (preg_match('/Drupal\\\\Tests\\\\(\w+)\\\\(\w+)/', $classname, $matches)) {
461       return $matches[2];
462     }
463     // Core tests.
464     elseif (preg_match('/Drupal\\\\(\w*)Tests\\\\/', $classname, $matches)) {
465       if ($matches[1] == '') {
466         return 'Unit';
467       }
468       return $matches[1];
469     }
470     return FALSE;
471   }
472
473   /**
474    * Returns all available extensions.
475    *
476    * @return \Drupal\Core\Extension\Extension[]
477    *   An array of Extension objects, keyed by extension name.
478    */
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);
486     return $extensions;
487   }
488
489 }