Mercurial > hg > cmmr2012-drupal-site
comparison core/modules/simpletest/src/TestDiscovery.php @ 0:c75dbcec494b
Initial commit from drush-created site
author | Chris Cannam |
---|---|
date | Thu, 05 Jul 2018 14:24:15 +0000 |
parents | |
children | a9cd425dd02b |
comparison
equal
deleted
inserted
replaced
-1:000000000000 | 0:c75dbcec494b |
---|---|
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\Tests\block\Functional\BlockTest' => array( | |
148 * 'name' => 'Drupal\Tests\block\Functional\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 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'])) { | |
201 continue; | |
202 } | |
203 } | |
204 } | |
205 | |
206 $list[$info['group']][$classname] = $info; | |
207 } | |
208 | |
209 // Sort the groups and tests within the groups by name. | |
210 uksort($list, 'strnatcasecmp'); | |
211 foreach ($list as &$tests) { | |
212 uksort($tests, 'strnatcasecmp'); | |
213 } | |
214 | |
215 // Allow modules extending core tests to disable originals. | |
216 $this->moduleHandler->alter('simpletest', $list); | |
217 | |
218 if (!isset($extension)) { | |
219 if ($this->cacheBackend) { | |
220 $this->cacheBackend->set('simpletest:discovery:classes', $list); | |
221 } | |
222 } | |
223 | |
224 if ($types) { | |
225 $list = NestedArray::filter($list, function ($element) use ($types) { | |
226 return !(is_array($element) && isset($element['type']) && !in_array($element['type'], $types)); | |
227 }); | |
228 } | |
229 | |
230 return $list; | |
231 } | |
232 | |
233 /** | |
234 * Discovers all class files in all available extensions. | |
235 * | |
236 * @param string $extension | |
237 * (optional) The name of an extension to limit discovery to; e.g., 'node'. | |
238 * | |
239 * @return array | |
240 * A classmap containing all discovered class files; i.e., a map of | |
241 * fully-qualified classnames to pathnames. | |
242 */ | |
243 public function findAllClassFiles($extension = NULL) { | |
244 $classmap = []; | |
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)))); | |
250 } | |
251 foreach ($namespaces as $namespace => $paths) { | |
252 foreach ($paths as $path) { | |
253 if (!is_dir($path)) { | |
254 continue; | |
255 } | |
256 $classmap += static::scanDirectory($namespace, $path); | |
257 } | |
258 } | |
259 return $classmap; | |
260 } | |
261 | |
262 /** | |
263 * Scans a given directory for class files. | |
264 * | |
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' | |
272 * | |
273 * @return array | |
274 * An associative array whose keys are fully-qualified class names and whose | |
275 * values are corresponding filesystem pathnames. | |
276 * | |
277 * @throws \InvalidArgumentException | |
278 * If $namespace_prefix does not end in a namespace separator (backslash). | |
279 * | |
280 * @todo Limit to '*Test.php' files (~10% less files to reflect/introspect). | |
281 * @see https://www.drupal.org/node/2296635 | |
282 */ | |
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."); | |
286 } | |
287 $flags = \FilesystemIterator::UNIX_PATHS; | |
288 $flags |= \FilesystemIterator::SKIP_DOTS; | |
289 $flags |= \FilesystemIterator::FOLLOW_SYMLINKS; | |
290 $flags |= \FilesystemIterator::CURRENT_AS_SELF; | |
291 | |
292 $iterator = new \RecursiveDirectoryIterator($path, $flags); | |
293 $filter = new \RecursiveCallbackFilterIterator($iterator, function ($current, $key, $iterator) { | |
294 if ($iterator->hasChildren()) { | |
295 return TRUE; | |
296 } | |
297 return $current->isFile() && $current->getExtension() === 'php'; | |
298 }); | |
299 $files = new \RecursiveIteratorIterator($filter); | |
300 $classes = []; | |
301 foreach ($files as $fileinfo) { | |
302 $class = $namespace_prefix; | |
303 if ('' !== $subpath = $fileinfo->getSubPath()) { | |
304 $class .= strtr($subpath, '/', '\\') . '\\'; | |
305 } | |
306 $class .= $fileinfo->getBasename('.php'); | |
307 $classes[$class] = $fileinfo->getPathname(); | |
308 } | |
309 return $classes; | |
310 } | |
311 | |
312 /** | |
313 * Retrieves information about a test class for UI purposes. | |
314 * | |
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. | |
320 * | |
321 * @return array | |
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. | |
329 * | |
330 * @throws \Drupal\simpletest\Exception\MissingGroupException | |
331 * If the class does not have a @group annotation. | |
332 */ | |
333 public static function getTestInfo($classname, $doc_comment = NULL) { | |
334 if ($doc_comment === NULL) { | |
335 $reflection = new \ReflectionClass($classname); | |
336 $doc_comment = $reflection->getDocComment(); | |
337 } | |
338 $info = [ | |
339 'name' => $classname, | |
340 ]; | |
341 $annotations = []; | |
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. | |
350 continue; | |
351 } | |
352 $annotations[$annotation] = $matches[2][$key]; | |
353 } | |
354 } | |
355 | |
356 if (empty($annotations['group'])) { | |
357 // Concrete tests must have a group. | |
358 throw new MissingGroupException(sprintf('Missing @group annotation in %s', $classname)); | |
359 } | |
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; | |
364 } | |
365 else { | |
366 $info['type'] = 'Simpletest'; | |
367 } | |
368 | |
369 if (!empty($annotations['coversDefaultClass'])) { | |
370 $info['description'] = 'Tests ' . $annotations['coversDefaultClass'] . '.'; | |
371 } | |
372 else { | |
373 $info['description'] = static::parseTestClassSummary($doc_comment); | |
374 } | |
375 if (isset($annotations['dependencies'])) { | |
376 $info['requires']['module'] = array_map('trim', explode(',', $annotations['dependencies'])); | |
377 } | |
378 | |
379 return $info; | |
380 } | |
381 | |
382 /** | |
383 * Parses the phpDoc summary line of a test class. | |
384 * | |
385 * @param string $doc_comment | |
386 * | |
387 * @return string | |
388 * The parsed phpDoc summary line. An empty string is returned if no summary | |
389 * line can be parsed. | |
390 */ | |
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); | |
396 | |
397 $lines = explode("\n", $doc_comment); | |
398 $summary = []; | |
399 // Add every line to the summary until the first empty line or annotation | |
400 // is found. | |
401 foreach ($lines as $line) { | |
402 if (preg_match('/^[ ]*\*$/', $line) || preg_match('/^[ ]*\* \@/', $line)) { | |
403 break; | |
404 } | |
405 $summary[] = trim($line, ' *'); | |
406 } | |
407 return implode(' ', $summary); | |
408 } | |
409 | |
410 /** | |
411 * Parses annotations in the phpDoc of a test class. | |
412 * | |
413 * @param \ReflectionClass $class | |
414 * The reflected test class. | |
415 * | |
416 * @return array | |
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 | |
422 * exist. | |
423 * | |
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 | |
426 */ | |
427 public static function parseTestClassAnnotations(\ReflectionClass $class) { | |
428 $annotations = PHPUnit_Util_Test::parseTestMethodAnnotations($class->getName())['class']; | |
429 | |
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]); | |
440 } | |
441 } | |
442 } | |
443 return $annotations; | |
444 } | |
445 | |
446 /** | |
447 * Determines the phpunit testsuite for a given classname. | |
448 * | |
449 * @param string $classname | |
450 * The test classname. | |
451 * | |
452 * @return string|false | |
453 * The testsuite name or FALSE if its not a phpunit test. | |
454 */ | |
455 public static function getPhpunitTestSuite($classname) { | |
456 if (preg_match('/Drupal\\\\Tests\\\\Core\\\\(\w+)/', $classname, $matches)) { | |
457 return 'Unit'; | |
458 } | |
459 if (preg_match('/Drupal\\\\Tests\\\\Component\\\\(\w+)/', $classname, $matches)) { | |
460 return 'Unit'; | |
461 } | |
462 // Module tests. | |
463 if (preg_match('/Drupal\\\\Tests\\\\(\w+)\\\\(\w+)/', $classname, $matches)) { | |
464 return $matches[2]; | |
465 } | |
466 // Core tests. | |
467 elseif (preg_match('/Drupal\\\\(\w*)Tests\\\\/', $classname, $matches)) { | |
468 if ($matches[1] == '') { | |
469 return 'Unit'; | |
470 } | |
471 return $matches[1]; | |
472 } | |
473 return FALSE; | |
474 } | |
475 | |
476 /** | |
477 * Returns all available extensions. | |
478 * | |
479 * @return \Drupal\Core\Extension\Extension[] | |
480 * An array of Extension objects, keyed by extension name. | |
481 */ | |
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); | |
489 return $extensions; | |
490 } | |
491 | |
492 } |