3 namespace Drupal\Tests;
5 use Drupal\Core\Extension\ExtensionDiscovery;
8 * Allows test classes to require Drupal modules as dependencies.
10 * This trait is assumed to be on a subclass of \PHPUnit_Framework_TestCase, and
11 * overrides \PHPUnit_Framework_TestCase::checkRequirements(). This allows the
12 * test to be marked as skipped before any kernel boot processes have happened.
14 trait TestRequirementsTrait {
17 * Returns the Drupal root directory.
21 protected static function getDrupalRoot() {
22 return dirname(dirname(substr(__DIR__, 0, -strlen(__NAMESPACE__))));
26 * Check module requirements for the Drupal use case.
28 * This method is assumed to override
29 * \PHPUnit_Framework_TestCase::checkRequirements().
31 * @throws \PHPUnit_Framework_SkippedTestError
32 * Thrown when the requirements are not met, and this test should be
33 * skipped. Callers should not catch this exception.
35 protected function checkRequirements() {
36 parent::checkRequirements();
38 $root = static::getDrupalRoot();
40 // Check if required dependencies exist.
41 $annotations = $this->getAnnotations();
42 if (!empty($annotations['class']['requires'])) {
43 $this->checkModuleRequirements($root, $annotations['class']['requires']);
45 if (!empty($annotations['method']['requires'])) {
46 $this->checkModuleRequirements($root, $annotations['method']['requires']);
51 * Checks missing module requirements.
53 * Iterates through a list of requires annotations and looks for missing
54 * modules. The test will be skipped if any of the required modules is
58 * The path to the root of the Drupal installation to scan.
59 * @param string[] $annotations
60 * A list of requires annotations from either a method or class annotation.
62 * @throws \PHPUnit_Framework_SkippedTestError
63 * Thrown when the requirements are not met, and this test should be
64 * skipped. Callers should not catch this exception.
66 private function checkModuleRequirements($root, array $annotations) {
67 // drupal_valid_ua() might not be loaded.
68 require_once $root . '/core/includes/bootstrap.inc';
70 // Make a list of required modules.
71 $required_modules = [];
72 foreach ($annotations as $requirement) {
73 if (strpos($requirement, 'module ') === 0) {
74 $required_modules[] = trim(str_replace('module ', '', $requirement));
78 // If there are required modules, check if they're available.
79 if (!empty($required_modules)) {
81 $discovery = new ExtensionDiscovery($root, FALSE);
82 $discovery->setProfileDirectories([]);
83 $list = array_keys($discovery->scan('module'));
84 $not_available = array_diff($required_modules, $list);
85 if (!empty($not_available)) {
86 throw new \PHPUnit_Framework_SkippedTestError('Required modules: ' . implode(', ', $not_available));