Updated to Drupal 8.6.4, which is PHP 7.3 friendly. Also updated HTMLaw library....
[yaffs-website] / web / core / tests / Drupal / Tests / BrowserTestBase.php
1 <?php
2
3 namespace Drupal\Tests;
4
5 use Behat\Mink\Driver\GoutteDriver;
6 use Behat\Mink\Element\Element;
7 use Behat\Mink\Mink;
8 use Behat\Mink\Selector\SelectorsHandler;
9 use Behat\Mink\Session;
10 use Drupal\Component\Serialization\Json;
11 use Drupal\Core\Database\Database;
12 use Drupal\Core\Test\FunctionalTestSetupTrait;
13 use Drupal\Core\Test\TestSetupTrait;
14 use Drupal\Core\Utility\Error;
15 use Drupal\FunctionalTests\AssertLegacyTrait;
16 use Drupal\Tests\block\Traits\BlockCreationTrait;
17 use Drupal\Tests\node\Traits\ContentTypeCreationTrait;
18 use Drupal\Tests\node\Traits\NodeCreationTrait;
19 use Drupal\Tests\user\Traits\UserCreationTrait;
20 use GuzzleHttp\Cookie\CookieJar;
21 use PHPUnit\Framework\TestCase;
22 use Psr\Http\Message\RequestInterface;
23 use Psr\Http\Message\ResponseInterface;
24 use Symfony\Component\CssSelector\CssSelectorConverter;
25
26 /**
27  * Provides a test case for functional Drupal tests.
28  *
29  * Tests extending BrowserTestBase must exist in the
30  * Drupal\Tests\yourmodule\Functional namespace and live in the
31  * modules/yourmodule/tests/src/Functional directory.
32  *
33  * Tests extending this base class should only translate text when testing
34  * translation functionality. For example, avoid wrapping test text with t()
35  * or TranslatableMarkup().
36  *
37  * @ingroup testing
38  */
39 abstract class BrowserTestBase extends TestCase {
40
41   use FunctionalTestSetupTrait;
42   use UiHelperTrait {
43     FunctionalTestSetupTrait::refreshVariables insteadof UiHelperTrait;
44   }
45   use TestSetupTrait;
46   use BlockCreationTrait {
47     placeBlock as drupalPlaceBlock;
48   }
49   use AssertLegacyTrait;
50   use RandomGeneratorTrait;
51   use NodeCreationTrait {
52     getNodeByTitle as drupalGetNodeByTitle;
53     createNode as drupalCreateNode;
54   }
55   use ContentTypeCreationTrait {
56     createContentType as drupalCreateContentType;
57   }
58   use ConfigTestTrait;
59   use TestRequirementsTrait;
60   use UserCreationTrait {
61     createRole as drupalCreateRole;
62     createUser as drupalCreateUser;
63   }
64   use XdebugRequestTrait;
65   use PhpunitCompatibilityTrait;
66
67   /**
68    * The database prefix of this test run.
69    *
70    * @var string
71    */
72   protected $databasePrefix;
73
74   /**
75    * Time limit in seconds for the test.
76    *
77    * @var int
78    */
79   protected $timeLimit = 500;
80
81   /**
82    * The translation file directory for the test environment.
83    *
84    * This is set in BrowserTestBase::prepareEnvironment().
85    *
86    * @var string
87    */
88   protected $translationFilesDirectory;
89
90   /**
91    * The config importer that can be used in a test.
92    *
93    * @var \Drupal\Core\Config\ConfigImporter
94    */
95   protected $configImporter;
96
97   /**
98    * Modules to enable.
99    *
100    * The test runner will merge the $modules lists from this class, the class
101    * it extends, and so on up the class hierarchy. It is not necessary to
102    * include modules in your list that a parent class has already declared.
103    *
104    * @var string[]
105    *
106    * @see \Drupal\Tests\BrowserTestBase::installDrupal()
107    */
108   protected static $modules = [];
109
110   /**
111    * The profile to install as a basis for testing.
112    *
113    * @var string
114    */
115   protected $profile = 'testing';
116
117   /**
118    * An array of custom translations suitable for drupal_rewrite_settings().
119    *
120    * @var array
121    */
122   protected $customTranslations;
123
124   /*
125    * Mink class for the default driver to use.
126    *
127    * Should be a fully-qualified class name that implements
128    * Behat\Mink\Driver\DriverInterface.
129    *
130    * Value can be overridden using the environment variable MINK_DRIVER_CLASS.
131    *
132    * @var string
133    */
134   protected $minkDefaultDriverClass = GoutteDriver::class;
135
136   /*
137    * Mink default driver params.
138    *
139    * If it's an array its contents are used as constructor params when default
140    * Mink driver class is instantiated.
141    *
142    * Can be overridden using the environment variable MINK_DRIVER_ARGS. In this
143    * case that variable should be a JSON array, for example:
144    * '["firefox", null, "http://localhost:4444/wd/hub"]'.
145    *
146    *
147    * @var array
148    */
149   protected $minkDefaultDriverArgs;
150
151   /**
152    * Mink session manager.
153    *
154    * This will not be initialized if there was an error during the test setup.
155    *
156    * @var \Behat\Mink\Mink|null
157    */
158   protected $mink;
159
160   /**
161    * {@inheritdoc}
162    *
163    * Browser tests are run in separate processes to prevent collisions between
164    * code that may be loaded by tests.
165    */
166   protected $runTestInSeparateProcess = TRUE;
167
168   /**
169    * {@inheritdoc}
170    */
171   protected $preserveGlobalState = FALSE;
172
173   /**
174    * The base URL.
175    *
176    * @var string
177    */
178   protected $baseUrl;
179
180   /**
181    * The original array of shutdown function callbacks.
182    *
183    * @var array
184    */
185   protected $originalShutdownCallbacks = [];
186
187   /**
188    * The app root.
189    *
190    * @var string
191    */
192   protected $root;
193
194   /**
195    * The original container.
196    *
197    * Move this to \Drupal\Core\Test\FunctionalTestSetupTrait once TestBase no
198    * longer provides the same value.
199    *
200    * @var \Symfony\Component\DependencyInjection\ContainerInterface
201    */
202   protected $originalContainer;
203
204   /**
205    * {@inheritdoc}
206    */
207   public function __construct($name = NULL, array $data = [], $dataName = '') {
208     parent::__construct($name, $data, $dataName);
209
210     $this->root = dirname(dirname(substr(__DIR__, 0, -strlen(__NAMESPACE__))));
211   }
212
213   /**
214    * Initializes Mink sessions.
215    */
216   protected function initMink() {
217     $driver = $this->getDefaultDriverInstance();
218
219     if ($driver instanceof GoutteDriver) {
220       // Turn off curl timeout. Having a timeout is not a problem in a normal
221       // test running, but it is a problem when debugging. Also, disable SSL
222       // peer verification so that testing under HTTPS always works.
223       /** @var \GuzzleHttp\Client $client */
224       $client = $this->container->get('http_client_factory')->fromOptions([
225         'timeout' => NULL,
226         'verify' => FALSE,
227       ]);
228
229       // Inject a Guzzle middleware to generate debug output for every request
230       // performed in the test.
231       $handler_stack = $client->getConfig('handler');
232       $handler_stack->push($this->getResponseLogHandler());
233
234       $driver->getClient()->setClient($client);
235     }
236
237     $selectors_handler = new SelectorsHandler([
238       'hidden_field_selector' => new HiddenFieldSelector(),
239     ]);
240     $session = new Session($driver, $selectors_handler);
241     $cookies = $this->extractCookiesFromRequest(\Drupal::request());
242     foreach ($cookies as $cookie_name => $values) {
243       foreach ($values as $value) {
244         $session->setCookie($cookie_name, $value);
245       }
246     }
247     $this->mink = new Mink();
248     $this->mink->registerSession('default', $session);
249     $this->mink->setDefaultSessionName('default');
250     $this->registerSessions();
251
252     $this->initFrontPage();
253
254     return $session;
255   }
256
257   /**
258    * Visits the front page when initializing Mink.
259    *
260    * According to the W3C WebDriver specification a cookie can only be set if
261    * the cookie domain is equal to the domain of the active document. When the
262    * browser starts up the active document is not our domain but 'about:blank'
263    * or similar. To be able to set our User-Agent and Xdebug cookies at the
264    * start of the test we now do a request to the front page so the active
265    * document matches the domain.
266    *
267    * @see https://w3c.github.io/webdriver/webdriver-spec.html#add-cookie
268    * @see https://www.w3.org/Bugs/Public/show_bug.cgi?id=20975
269    */
270   protected function initFrontPage() {
271     $session = $this->getSession();
272     $session->visit($this->baseUrl);
273   }
274
275   /**
276    * Gets an instance of the default Mink driver.
277    *
278    * @return Behat\Mink\Driver\DriverInterface
279    *   Instance of default Mink driver.
280    *
281    * @throws \InvalidArgumentException
282    *   When provided default Mink driver class can't be instantiated.
283    */
284   protected function getDefaultDriverInstance() {
285     // Get default driver params from environment if available.
286     if ($arg_json = $this->getMinkDriverArgs()) {
287       $this->minkDefaultDriverArgs = json_decode($arg_json, TRUE);
288     }
289
290     // Get and check default driver class from environment if available.
291     if ($minkDriverClass = getenv('MINK_DRIVER_CLASS')) {
292       if (class_exists($minkDriverClass)) {
293         $this->minkDefaultDriverClass = $minkDriverClass;
294       }
295       else {
296         throw new \InvalidArgumentException("Can't instantiate provided $minkDriverClass class by environment as default driver class.");
297       }
298     }
299
300     if (is_array($this->minkDefaultDriverArgs)) {
301       // Use ReflectionClass to instantiate class with received params.
302       $reflector = new \ReflectionClass($this->minkDefaultDriverClass);
303       $driver = $reflector->newInstanceArgs($this->minkDefaultDriverArgs);
304     }
305     else {
306       $driver = new $this->minkDefaultDriverClass();
307     }
308     return $driver;
309   }
310
311   /**
312    * Get the Mink driver args from an environment variable, if it is set. Can
313    * be overridden in a derived class so it is possible to use a different
314    * value for a subset of tests, e.g. the JavaScript tests.
315    *
316    *  @return string|false
317    *   The JSON-encoded argument string. False if it is not set.
318    */
319   protected function getMinkDriverArgs() {
320     return getenv('MINK_DRIVER_ARGS');
321   }
322
323   /**
324    * Provides a Guzzle middleware handler to log every response received.
325    *
326    * @return callable
327    *   The callable handler that will do the logging.
328    */
329   protected function getResponseLogHandler() {
330     return function (callable $handler) {
331       return function (RequestInterface $request, array $options) use ($handler) {
332         return $handler($request, $options)
333           ->then(function (ResponseInterface $response) use ($request) {
334             if ($this->htmlOutputEnabled) {
335
336               $caller = $this->getTestMethodCaller();
337               $html_output = 'Called from ' . $caller['function'] . ' line ' . $caller['line'];
338               $html_output .= '<hr />' . $request->getMethod() . ' request to: ' . $request->getUri();
339
340               // On redirect responses (status code starting with '3') we need
341               // to remove the meta tag that would do a browser refresh. We
342               // don't want to redirect developers away when they look at the
343               // debug output file in their browser.
344               $body = $response->getBody();
345               $status_code = (string) $response->getStatusCode();
346               if ($status_code[0] === '3') {
347                 $body = preg_replace('#<meta http-equiv="refresh" content=.+/>#', '', $body, 1);
348               }
349               $html_output .= '<hr />' . $body;
350               $html_output .= $this->formatHtmlOutputHeaders($response->getHeaders());
351
352               $this->htmlOutput($html_output);
353             }
354             return $response;
355           });
356       };
357     };
358   }
359
360   /**
361    * Registers additional Mink sessions.
362    *
363    * Tests wishing to use a different driver or change the default driver should
364    * override this method.
365    *
366    * @code
367    *   // Register a new session that uses the MinkPonyDriver.
368    *   $pony = new MinkPonyDriver();
369    *   $session = new Session($pony);
370    *   $this->mink->registerSession('pony', $session);
371    * @endcode
372    */
373   protected function registerSessions() {}
374
375   /**
376    * {@inheritdoc}
377    */
378   protected function setUp() {
379     // Installing Drupal creates 1000s of objects. Garbage collection of these
380     // objects is expensive. This appears to be causing random segmentation
381     // faults in PHP 5.x due to https://bugs.php.net/bug.php?id=72286. Once
382     // Drupal is installed is rebuilt, garbage collection is re-enabled.
383     $disable_gc = version_compare(PHP_VERSION, '7', '<') && gc_enabled();
384     if ($disable_gc) {
385       gc_collect_cycles();
386       gc_disable();
387     }
388     parent::setUp();
389
390     $this->setupBaseUrl();
391
392     // Install Drupal test site.
393     $this->prepareEnvironment();
394     $this->installDrupal();
395
396     // Setup Mink.
397     $this->initMink();
398
399     // Set up the browser test output file.
400     $this->initBrowserOutputFile();
401     // If garbage collection was disabled prior to rebuilding container,
402     // re-enable it.
403     if ($disable_gc) {
404       gc_enable();
405     }
406
407     // Ensure that the test is not marked as risky because of no assertions. In
408     // PHPUnit 6 tests that only make assertions using $this->assertSession()
409     // can be marked as risky.
410     $this->addToAssertionCount(1);
411   }
412
413   /**
414    * Ensures test files are deletable within file_unmanaged_delete_recursive().
415    *
416    * Some tests chmod generated files to be read only. During
417    * BrowserTestBase::cleanupEnvironment() and other cleanup operations,
418    * these files need to get deleted too.
419    *
420    * @param string $path
421    *   The file path.
422    */
423   public static function filePreDeleteCallback($path) {
424     // When the webserver runs with the same system user as phpunit, we can
425     // make read-only files writable again. If not, chmod will fail while the
426     // file deletion still works if file permissions have been configured
427     // correctly. Thus, we ignore any problems while running chmod.
428     @chmod($path, 0700);
429   }
430
431   /**
432    * Clean up the Simpletest environment.
433    */
434   protected function cleanupEnvironment() {
435     // Remove all prefixed tables.
436     $original_connection_info = Database::getConnectionInfo('simpletest_original_default');
437     $original_prefix = $original_connection_info['default']['prefix']['default'];
438     $test_connection_info = Database::getConnectionInfo('default');
439     $test_prefix = $test_connection_info['default']['prefix']['default'];
440     if ($original_prefix != $test_prefix) {
441       $tables = Database::getConnection()->schema()->findTables('%');
442       foreach ($tables as $table) {
443         if (Database::getConnection()->schema()->dropTable($table)) {
444           unset($tables[$table]);
445         }
446       }
447     }
448
449     // Delete test site directory.
450     file_unmanaged_delete_recursive($this->siteDirectory, [$this, 'filePreDeleteCallback']);
451   }
452
453   /**
454    * {@inheritdoc}
455    */
456   protected function tearDown() {
457     parent::tearDown();
458
459     // Destroy the testing kernel.
460     if (isset($this->kernel)) {
461       $this->cleanupEnvironment();
462       $this->kernel->shutdown();
463     }
464
465     // Ensure that internal logged in variable is reset.
466     $this->loggedInUser = FALSE;
467
468     if ($this->mink) {
469       $this->mink->stopSessions();
470     }
471
472     // Restore original shutdown callbacks.
473     if (function_exists('drupal_register_shutdown_function')) {
474       $callbacks = &drupal_register_shutdown_function();
475       $callbacks = $this->originalShutdownCallbacks;
476     }
477   }
478
479   /**
480    * Returns Mink session.
481    *
482    * @param string $name
483    *   (optional) Name of the session. Defaults to the active session.
484    *
485    * @return \Behat\Mink\Session
486    *   The active Mink session object.
487    */
488   public function getSession($name = NULL) {
489     return $this->mink->getSession($name);
490   }
491
492   /**
493    * Get session cookies from current session.
494    *
495    * @return \GuzzleHttp\Cookie\CookieJar
496    *   A cookie jar with the current session.
497    */
498   protected function getSessionCookies() {
499     $domain = parse_url($this->getUrl(), PHP_URL_HOST);
500     $session_id = $this->getSession()->getCookie($this->getSessionName());
501     $cookies = CookieJar::fromArray([$this->getSessionName() => $session_id], $domain);
502
503     return $cookies;
504   }
505
506   /**
507    * Obtain the HTTP client for the system under test.
508    *
509    * Use this method for arbitrary HTTP requests to the site under test. For
510    * most tests, you should not get the HTTP client and instead use navigation
511    * methods such as drupalGet() and clickLink() in order to benefit from
512    * assertions.
513    *
514    * Subclasses which substitute a different Mink driver should override this
515    * method and provide a Guzzle client if the Mink driver provides one.
516    *
517    * @return \GuzzleHttp\ClientInterface
518    *   The client with BrowserTestBase configuration.
519    *
520    * @throws \RuntimeException
521    *   If the Mink driver does not support a Guzzle HTTP client, throw an
522    *   exception.
523    */
524   protected function getHttpClient() {
525     /* @var $mink_driver \Behat\Mink\Driver\DriverInterface */
526     $mink_driver = $this->getSession()->getDriver();
527     if ($mink_driver instanceof GoutteDriver) {
528       return $mink_driver->getClient()->getClient();
529     }
530     throw new \RuntimeException('The Mink client type ' . get_class($mink_driver) . ' does not support getHttpClient().');
531   }
532
533   /**
534    * Helper function to get the options of select field.
535    *
536    * @param \Behat\Mink\Element\NodeElement|string $select
537    *   Name, ID, or Label of select field to assert.
538    * @param \Behat\Mink\Element\Element $container
539    *   (optional) Container element to check against. Defaults to current page.
540    *
541    * @return array
542    *   Associative array of option keys and values.
543    */
544   protected function getOptions($select, Element $container = NULL) {
545     if (is_string($select)) {
546       $select = $this->assertSession()->selectExists($select, $container);
547     }
548     $options = [];
549     /* @var \Behat\Mink\Element\NodeElement $option */
550     foreach ($select->findAll('xpath', '//option') as $option) {
551       $label = $option->getText();
552       $value = $option->getAttribute('value') ?: $label;
553       $options[$value] = $label;
554     }
555     return $options;
556   }
557
558   /**
559    * Installs Drupal into the Simpletest site.
560    */
561   public function installDrupal() {
562     $this->initUserSession();
563     $this->prepareSettings();
564     $this->doInstall();
565     $this->initSettings();
566     $container = $this->initKernel(\Drupal::request());
567     $this->initConfig($container);
568     $this->installModulesFromClassProperty($container);
569     $this->rebuildAll();
570   }
571
572   /**
573    * Prevents serializing any properties.
574    *
575    * Browser tests are run in a separate process. To do this PHPUnit creates a
576    * script to run the test. If it fails, the test result object will contain a
577    * stack trace which includes the test object. It will attempt to serialize
578    * it. Returning an empty array prevents it from serializing anything it
579    * should not.
580    *
581    * @return array
582    *   An empty array.
583    *
584    * @see vendor/phpunit/phpunit/src/Util/PHP/Template/TestCaseMethod.tpl.dist
585    */
586   public function __sleep() {
587     return [];
588   }
589
590   /**
591    * Translates a CSS expression to its XPath equivalent.
592    *
593    * The search is relative to the root element (HTML tag normally) of the page.
594    *
595    * @param string $selector
596    *   CSS selector to use in the search.
597    * @param bool $html
598    *   (optional) Enables HTML support. Disable it for XML documents.
599    * @param string $prefix
600    *   (optional) The prefix for the XPath expression.
601    *
602    * @return string
603    *   The equivalent XPath of a CSS expression.
604    */
605   protected function cssSelectToXpath($selector, $html = TRUE, $prefix = 'descendant-or-self::') {
606     return (new CssSelectorConverter($html))->toXPath($selector, $prefix);
607   }
608
609   /**
610    * Performs an xpath search on the contents of the internal browser.
611    *
612    * The search is relative to the root element (HTML tag normally) of the page.
613    *
614    * @param string $xpath
615    *   The xpath string to use in the search.
616    * @param array $arguments
617    *   An array of arguments with keys in the form ':name' matching the
618    *   placeholders in the query. The values may be either strings or numeric
619    *   values.
620    *
621    * @return \Behat\Mink\Element\NodeElement[]
622    *   The list of elements matching the xpath expression.
623    */
624   protected function xpath($xpath, array $arguments = []) {
625     $xpath = $this->assertSession()->buildXPathQuery($xpath, $arguments);
626     return $this->getSession()->getPage()->findAll('xpath', $xpath);
627   }
628
629   /**
630    * Configuration accessor for tests. Returns non-overridden configuration.
631    *
632    * @param string $name
633    *   Configuration name.
634    *
635    * @return \Drupal\Core\Config\Config
636    *   The configuration object with original configuration data.
637    */
638   protected function config($name) {
639     return $this->container->get('config.factory')->getEditable($name);
640   }
641
642   /**
643    * Returns all response headers.
644    *
645    * @return array
646    *   The HTTP headers values.
647    *
648    * @deprecated Scheduled for removal in Drupal 9.0.0.
649    *   Use $this->getSession()->getResponseHeaders() instead.
650    */
651   protected function drupalGetHeaders() {
652     return $this->getSession()->getResponseHeaders();
653   }
654
655   /**
656    * Gets the value of an HTTP response header.
657    *
658    * If multiple requests were required to retrieve the page, only the headers
659    * from the last request will be checked by default.
660    *
661    * @param string $name
662    *   The name of the header to retrieve. Names are case-insensitive (see RFC
663    *   2616 section 4.2).
664    *
665    * @return string|null
666    *   The HTTP header value or NULL if not found.
667    */
668   protected function drupalGetHeader($name) {
669     return $this->getSession()->getResponseHeader($name);
670   }
671
672   /**
673    * Gets the JavaScript drupalSettings variable for the currently-loaded page.
674    *
675    * @return array
676    *   The JSON decoded drupalSettings value from the current page.
677    */
678   protected function getDrupalSettings() {
679     $html = $this->getSession()->getPage()->getHtml();
680     if (preg_match('@<script type="application/json" data-drupal-selector="drupal-settings-json">([^<]*)</script>@', $html, $matches)) {
681       return Json::decode($matches[1]);
682     }
683     return [];
684   }
685
686   /**
687    * {@inheritdoc}
688    */
689   public static function assertEquals($expected, $actual, $message = '', $delta = 0.0, $maxDepth = 10, $canonicalize = FALSE, $ignoreCase = FALSE) {
690     // Cast objects implementing MarkupInterface to string instead of
691     // relying on PHP casting them to string depending on what they are being
692     // comparing with.
693     $expected = static::castSafeStrings($expected);
694     $actual = static::castSafeStrings($actual);
695     parent::assertEquals($expected, $actual, $message, $delta, $maxDepth, $canonicalize, $ignoreCase);
696   }
697
698   /**
699    * Retrieves the current calling line in the class under test.
700    *
701    * @return array
702    *   An associative array with keys 'file', 'line' and 'function'.
703    */
704   protected function getTestMethodCaller() {
705     $backtrace = debug_backtrace();
706     // Find the test class that has the test method.
707     while ($caller = Error::getLastCaller($backtrace)) {
708       if (isset($caller['class']) && $caller['class'] === get_class($this)) {
709         break;
710       }
711       // If the test method is implemented by a test class's parent then the
712       // class name of $this will not be part of the backtrace.
713       // In that case we process the backtrace until the caller is not a
714       // subclass of $this and return the previous caller.
715       if (isset($last_caller) && (!isset($caller['class']) || !is_subclass_of($this, $caller['class']))) {
716         // Return the last caller since that has to be the test class.
717         $caller = $last_caller;
718         break;
719       }
720       // Otherwise we have not reached our test class yet: save the last caller
721       // and remove an element from to backtrace to process the next call.
722       $last_caller = $caller;
723       array_shift($backtrace);
724     }
725
726     return $caller;
727   }
728
729   /**
730    * Transforms a nested array into a flat array suitable for drupalPostForm().
731    *
732    * @param array $values
733    *   A multi-dimensional form values array to convert.
734    *
735    * @return array
736    *   The flattened $edit array suitable for BrowserTestBase::drupalPostForm().
737    */
738   protected function translatePostValues(array $values) {
739     $edit = [];
740     // The easiest and most straightforward way to translate values suitable for
741     // BrowserTestBase::drupalPostForm() is to actually build the POST data
742     // string and convert the resulting key/value pairs back into a flat array.
743     $query = http_build_query($values);
744     foreach (explode('&', $query) as $item) {
745       list($key, $value) = explode('=', $item);
746       $edit[urldecode($key)] = urldecode($value);
747     }
748     return $edit;
749   }
750
751 }