Updated to Drupal 8.5. Core Media not yet in use.
[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\Render\FormattableMarkup;
11 use Drupal\Component\Serialization\Json;
12 use Drupal\Component\Utility\Html;
13 use Drupal\Component\Utility\UrlHelper;
14 use Drupal\Core\Database\Database;
15 use Drupal\Core\Session\AccountInterface;
16 use Drupal\Core\Session\AnonymousUserSession;
17 use Drupal\Core\Test\FunctionalTestSetupTrait;
18 use Drupal\Core\Test\TestSetupTrait;
19 use Drupal\Core\Url;
20 use Drupal\Core\Utility\Error;
21 use Drupal\FunctionalTests\AssertLegacyTrait;
22 use Drupal\Tests\block\Traits\BlockCreationTrait;
23 use Drupal\Tests\node\Traits\ContentTypeCreationTrait;
24 use Drupal\Tests\node\Traits\NodeCreationTrait;
25 use Drupal\Tests\user\Traits\UserCreationTrait;
26 use PHPUnit\Framework\TestCase;
27 use Psr\Http\Message\RequestInterface;
28 use Psr\Http\Message\ResponseInterface;
29 use Symfony\Component\CssSelector\CssSelectorConverter;
30
31 /**
32  * Provides a test case for functional Drupal tests.
33  *
34  * Tests extending BrowserTestBase must exist in the
35  * Drupal\Tests\yourmodule\Functional namespace and live in the
36  * modules/yourmodule/tests/src/Functional directory.
37  *
38  * Tests extending this base class should only translate text when testing
39  * translation functionality. For example, avoid wrapping test text with t()
40  * or TranslatableMarkup().
41  *
42  * @ingroup testing
43  */
44 abstract class BrowserTestBase extends TestCase {
45
46   use FunctionalTestSetupTrait;
47   use TestSetupTrait;
48   use AssertHelperTrait;
49   use BlockCreationTrait {
50     placeBlock as drupalPlaceBlock;
51   }
52   use AssertLegacyTrait;
53   use RandomGeneratorTrait;
54   use SessionTestTrait;
55   use NodeCreationTrait {
56     getNodeByTitle as drupalGetNodeByTitle;
57     createNode as drupalCreateNode;
58   }
59   use ContentTypeCreationTrait {
60     createContentType as drupalCreateContentType;
61   }
62   use ConfigTestTrait;
63   use TestRequirementsTrait;
64   use UserCreationTrait {
65     createRole as drupalCreateRole;
66     createUser as drupalCreateUser;
67   }
68   use XdebugRequestTrait;
69   use PhpunitCompatibilityTrait;
70
71   /**
72    * The database prefix of this test run.
73    *
74    * @var string
75    */
76   protected $databasePrefix;
77
78   /**
79    * Time limit in seconds for the test.
80    *
81    * @var int
82    */
83   protected $timeLimit = 500;
84
85   /**
86    * The translation file directory for the test environment.
87    *
88    * This is set in BrowserTestBase::prepareEnvironment().
89    *
90    * @var string
91    */
92   protected $translationFilesDirectory;
93
94   /**
95    * The config importer that can be used in a test.
96    *
97    * @var \Drupal\Core\Config\ConfigImporter
98    */
99   protected $configImporter;
100
101   /**
102    * Modules to enable.
103    *
104    * The test runner will merge the $modules lists from this class, the class
105    * it extends, and so on up the class hierarchy. It is not necessary to
106    * include modules in your list that a parent class has already declared.
107    *
108    * @var string[]
109    *
110    * @see \Drupal\Tests\BrowserTestBase::installDrupal()
111    */
112   protected static $modules = [];
113
114   /**
115    * The profile to install as a basis for testing.
116    *
117    * @var string
118    */
119   protected $profile = 'testing';
120
121   /**
122    * The current user logged in using the Mink controlled browser.
123    *
124    * @var \Drupal\user\UserInterface
125    */
126   protected $loggedInUser = FALSE;
127
128   /**
129    * An array of custom translations suitable for drupal_rewrite_settings().
130    *
131    * @var array
132    */
133   protected $customTranslations;
134
135   /*
136    * Mink class for the default driver to use.
137    *
138    * Shoud be a fully qualified class name that implements
139    * Behat\Mink\Driver\DriverInterface.
140    *
141    * Value can be overridden using the environment variable MINK_DRIVER_CLASS.
142    *
143    * @var string.
144    */
145   protected $minkDefaultDriverClass = GoutteDriver::class;
146
147   /*
148    * Mink default driver params.
149    *
150    * If it's an array its contents are used as constructor params when default
151    * Mink driver class is instantiated.
152    *
153    * Can be overridden using the environment variable MINK_DRIVER_ARGS. In this
154    * case that variable should be a JSON array, for example:
155    * '["firefox", null, "http://localhost:4444/wd/hub"]'.
156    *
157    *
158    * @var array
159    */
160   protected $minkDefaultDriverArgs;
161
162   /**
163    * Mink session manager.
164    *
165    * This will not be initialized if there was an error during the test setup.
166    *
167    * @var \Behat\Mink\Mink|null
168    */
169   protected $mink;
170
171   /**
172    * {@inheritdoc}
173    *
174    * Browser tests are run in separate processes to prevent collisions between
175    * code that may be loaded by tests.
176    */
177   protected $runTestInSeparateProcess = TRUE;
178
179   /**
180    * {@inheritdoc}
181    */
182   protected $preserveGlobalState = FALSE;
183
184   /**
185    * Class name for HTML output logging.
186    *
187    * @var string
188    */
189   protected $htmlOutputClassName;
190
191   /**
192    * Directory name for HTML output logging.
193    *
194    * @var string
195    */
196   protected $htmlOutputDirectory;
197
198   /**
199    * Counter storage for HTML output logging.
200    *
201    * @var string
202    */
203   protected $htmlOutputCounterStorage;
204
205   /**
206    * Counter for HTML output logging.
207    *
208    * @var int
209    */
210   protected $htmlOutputCounter = 1;
211
212   /**
213    * HTML output output enabled.
214    *
215    * @var bool
216    */
217   protected $htmlOutputEnabled = FALSE;
218
219   /**
220    * The file name to write the list of URLs to.
221    *
222    * This file is read by the PHPUnit result printer.
223    *
224    * @var string
225    *
226    * @see \Drupal\Tests\Listeners\HtmlOutputPrinter
227    */
228   protected $htmlOutputFile;
229
230   /**
231    * HTML output test ID.
232    *
233    * @var int
234    */
235   protected $htmlOutputTestId;
236
237   /**
238    * The base URL.
239    *
240    * @var string
241    */
242   protected $baseUrl;
243
244   /**
245    * The original array of shutdown function callbacks.
246    *
247    * @var array
248    */
249   protected $originalShutdownCallbacks = [];
250
251   /**
252    * The number of meta refresh redirects to follow, or NULL if unlimited.
253    *
254    * @var null|int
255    */
256   protected $maximumMetaRefreshCount = NULL;
257
258   /**
259    * The number of meta refresh redirects followed during ::drupalGet().
260    *
261    * @var int
262    */
263   protected $metaRefreshCount = 0;
264
265   /**
266    * The app root.
267    *
268    * @var string
269    */
270   protected $root;
271
272   /**
273    * The original container.
274    *
275    * Move this to \Drupal\Core\Test\FunctionalTestSetupTrait once TestBase no
276    * longer provides the same value.
277    *
278    * @var \Symfony\Component\DependencyInjection\ContainerInterface
279    */
280   protected $originalContainer;
281
282   /**
283    * {@inheritdoc}
284    */
285   public function __construct($name = NULL, array $data = [], $dataName = '') {
286     parent::__construct($name, $data, $dataName);
287
288     $this->root = dirname(dirname(substr(__DIR__, 0, -strlen(__NAMESPACE__))));
289   }
290
291   /**
292    * Initializes Mink sessions.
293    */
294   protected function initMink() {
295     $driver = $this->getDefaultDriverInstance();
296
297     if ($driver instanceof GoutteDriver) {
298       // Turn off curl timeout. Having a timeout is not a problem in a normal
299       // test running, but it is a problem when debugging. Also, disable SSL
300       // peer verification so that testing under HTTPS always works.
301       /** @var \GuzzleHttp\Client $client */
302       $client = $this->container->get('http_client_factory')->fromOptions([
303         'timeout' => NULL,
304         'verify' => FALSE,
305       ]);
306
307       // Inject a Guzzle middleware to generate debug output for every request
308       // performed in the test.
309       $handler_stack = $client->getConfig('handler');
310       $handler_stack->push($this->getResponseLogHandler());
311
312       $driver->getClient()->setClient($client);
313     }
314
315     $selectors_handler = new SelectorsHandler([
316       'hidden_field_selector' => new HiddenFieldSelector()
317     ]);
318     $session = new Session($driver, $selectors_handler);
319     $this->mink = new Mink();
320     $this->mink->registerSession('default', $session);
321     $this->mink->setDefaultSessionName('default');
322     $this->registerSessions();
323
324     // According to the W3C WebDriver specification a cookie can only be set if
325     // the cookie domain is equal to the domain of the active document. When the
326     // browser starts up the active document is not our domain but 'about:blank'
327     // or similar. To be able to set our User-Agent and Xdebug cookies at the
328     // start of the test we now do a request to the front page so the active
329     // document matches the domain.
330     // @see https://w3c.github.io/webdriver/webdriver-spec.html#add-cookie
331     // @see https://www.w3.org/Bugs/Public/show_bug.cgi?id=20975
332     $session = $this->getSession();
333     $session->visit($this->baseUrl);
334
335     return $session;
336   }
337
338   /**
339    * Gets an instance of the default Mink driver.
340    *
341    * @return Behat\Mink\Driver\DriverInterface
342    *   Instance of default Mink driver.
343    *
344    * @throws \InvalidArgumentException
345    *   When provided default Mink driver class can't be instantiated.
346    */
347   protected function getDefaultDriverInstance() {
348     // Get default driver params from environment if available.
349     if ($arg_json = $this->getMinkDriverArgs()) {
350       $this->minkDefaultDriverArgs = json_decode($arg_json, TRUE);
351     }
352
353     // Get and check default driver class from environment if available.
354     if ($minkDriverClass = getenv('MINK_DRIVER_CLASS')) {
355       if (class_exists($minkDriverClass)) {
356         $this->minkDefaultDriverClass = $minkDriverClass;
357       }
358       else {
359         throw new \InvalidArgumentException("Can't instantiate provided $minkDriverClass class by environment as default driver class.");
360       }
361     }
362
363     if (is_array($this->minkDefaultDriverArgs)) {
364       // Use ReflectionClass to instantiate class with received params.
365       $reflector = new \ReflectionClass($this->minkDefaultDriverClass);
366       $driver = $reflector->newInstanceArgs($this->minkDefaultDriverArgs);
367     }
368     else {
369       $driver = new $this->minkDefaultDriverClass();
370     }
371     return $driver;
372   }
373
374   /**
375    * Creates the directory to store browser output.
376    *
377    * Creates the directory to store browser output in if a file to write
378    * URLs to has been created by \Drupal\Tests\Listeners\HtmlOutputPrinter.
379    */
380   protected function initBrowserOutputFile() {
381     $browser_output_file = getenv('BROWSERTEST_OUTPUT_FILE');
382     $this->htmlOutputEnabled = is_file($browser_output_file);
383     if ($this->htmlOutputEnabled) {
384       $this->htmlOutputFile = $browser_output_file;
385       $this->htmlOutputClassName = str_replace("\\", "_", get_called_class());
386       $this->htmlOutputDirectory = DRUPAL_ROOT . '/sites/simpletest/browser_output';
387       if (file_prepare_directory($this->htmlOutputDirectory, FILE_CREATE_DIRECTORY) && !file_exists($this->htmlOutputDirectory . '/.htaccess')) {
388         file_put_contents($this->htmlOutputDirectory . '/.htaccess', "<IfModule mod_expires.c>\nExpiresActive Off\n</IfModule>\n");
389       }
390       $this->htmlOutputCounterStorage = $this->htmlOutputDirectory . '/' . $this->htmlOutputClassName . '.counter';
391       $this->htmlOutputTestId = str_replace('sites/simpletest/', '', $this->siteDirectory);
392       if (is_file($this->htmlOutputCounterStorage)) {
393         $this->htmlOutputCounter = max(1, (int) file_get_contents($this->htmlOutputCounterStorage)) + 1;
394       }
395     }
396   }
397
398   /**
399    * Get the Mink driver args from an environment variable, if it is set. Can
400    * be overridden in a derived class so it is possible to use a different
401    * value for a subset of tests, e.g. the JavaScript tests.
402    *
403    *  @return string|false
404    *   The JSON-encoded argument string. False if it is not set.
405    */
406   protected function getMinkDriverArgs() {
407     return getenv('MINK_DRIVER_ARGS');
408   }
409
410   /**
411    * Provides a Guzzle middleware handler to log every response received.
412    *
413    * @return callable
414    *   The callable handler that will do the logging.
415    */
416   protected function getResponseLogHandler() {
417     return function (callable $handler) {
418       return function (RequestInterface $request, array $options) use ($handler) {
419         return $handler($request, $options)
420           ->then(function (ResponseInterface $response) use ($request) {
421             if ($this->htmlOutputEnabled) {
422
423               $caller = $this->getTestMethodCaller();
424               $html_output = 'Called from ' . $caller['function'] . ' line ' . $caller['line'];
425               $html_output .= '<hr />' . $request->getMethod() . ' request to: ' . $request->getUri();
426
427               // On redirect responses (status code starting with '3') we need
428               // to remove the meta tag that would do a browser refresh. We
429               // don't want to redirect developers away when they look at the
430               // debug output file in their browser.
431               $body = $response->getBody();
432               $status_code = (string) $response->getStatusCode();
433               if ($status_code[0] === '3') {
434                 $body = preg_replace('#<meta http-equiv="refresh" content=.+/>#', '', $body, 1);
435               }
436               $html_output .= '<hr />' . $body;
437               $html_output .= $this->formatHtmlOutputHeaders($response->getHeaders());
438
439               $this->htmlOutput($html_output);
440             }
441             return $response;
442           });
443       };
444     };
445   }
446
447   /**
448    * Registers additional Mink sessions.
449    *
450    * Tests wishing to use a different driver or change the default driver should
451    * override this method.
452    *
453    * @code
454    *   // Register a new session that uses the MinkPonyDriver.
455    *   $pony = new MinkPonyDriver();
456    *   $session = new Session($pony);
457    *   $this->mink->registerSession('pony', $session);
458    * @endcode
459    */
460   protected function registerSessions() {}
461
462   /**
463    * {@inheritdoc}
464    */
465   protected function setUp() {
466     // Installing Drupal creates 1000s of objects. Garbage collection of these
467     // objects is expensive. This appears to be causing random segmentation
468     // faults in PHP 5.x due to https://bugs.php.net/bug.php?id=72286. Once
469     // Drupal is installed is rebuilt, garbage collection is re-enabled.
470     $disable_gc = version_compare(PHP_VERSION, '7', '<') && gc_enabled();
471     if ($disable_gc) {
472       gc_collect_cycles();
473       gc_disable();
474     }
475     parent::setUp();
476
477     $this->setupBaseUrl();
478
479     // Install Drupal test site.
480     $this->prepareEnvironment();
481     $this->installDrupal();
482
483     // Setup Mink.
484     $session = $this->initMink();
485
486     $cookies = $this->extractCookiesFromRequest(\Drupal::request());
487     foreach ($cookies as $cookie_name => $values) {
488       foreach ($values as $value) {
489         $session->setCookie($cookie_name, $value);
490       }
491     }
492
493     // Set up the browser test output file.
494     $this->initBrowserOutputFile();
495     // If garbage collection was disabled prior to rebuilding container,
496     // re-enable it.
497     if ($disable_gc) {
498       gc_enable();
499     }
500
501     // Ensure that the test is not marked as risky because of no assertions. In
502     // PHPUnit 6 tests that only make assertions using $this->assertSession()
503     // can be marked as risky.
504     $this->addToAssertionCount(1);
505   }
506
507   /**
508    * Ensures test files are deletable within file_unmanaged_delete_recursive().
509    *
510    * Some tests chmod generated files to be read only. During
511    * BrowserTestBase::cleanupEnvironment() and other cleanup operations,
512    * these files need to get deleted too.
513    *
514    * @param string $path
515    *   The file path.
516    */
517   public static function filePreDeleteCallback($path) {
518     // When the webserver runs with the same system user as phpunit, we can
519     // make read-only files writable again. If not, chmod will fail while the
520     // file deletion still works if file permissions have been configured
521     // correctly. Thus, we ignore any problems while running chmod.
522     @chmod($path, 0700);
523   }
524
525   /**
526    * Clean up the Simpletest environment.
527    */
528   protected function cleanupEnvironment() {
529     // Remove all prefixed tables.
530     $original_connection_info = Database::getConnectionInfo('simpletest_original_default');
531     $original_prefix = $original_connection_info['default']['prefix']['default'];
532     $test_connection_info = Database::getConnectionInfo('default');
533     $test_prefix = $test_connection_info['default']['prefix']['default'];
534     if ($original_prefix != $test_prefix) {
535       $tables = Database::getConnection()->schema()->findTables('%');
536       foreach ($tables as $table) {
537         if (Database::getConnection()->schema()->dropTable($table)) {
538           unset($tables[$table]);
539         }
540       }
541     }
542
543     // Delete test site directory.
544     file_unmanaged_delete_recursive($this->siteDirectory, [$this, 'filePreDeleteCallback']);
545   }
546
547   /**
548    * {@inheritdoc}
549    */
550   protected function tearDown() {
551     parent::tearDown();
552
553     // Destroy the testing kernel.
554     if (isset($this->kernel)) {
555       $this->cleanupEnvironment();
556       $this->kernel->shutdown();
557     }
558
559     // Ensure that internal logged in variable is reset.
560     $this->loggedInUser = FALSE;
561
562     if ($this->mink) {
563       $this->mink->stopSessions();
564     }
565
566     // Restore original shutdown callbacks.
567     if (function_exists('drupal_register_shutdown_function')) {
568       $callbacks = &drupal_register_shutdown_function();
569       $callbacks = $this->originalShutdownCallbacks;
570     }
571   }
572
573   /**
574    * Returns Mink session.
575    *
576    * @param string $name
577    *   (optional) Name of the session. Defaults to the active session.
578    *
579    * @return \Behat\Mink\Session
580    *   The active Mink session object.
581    */
582   public function getSession($name = NULL) {
583     return $this->mink->getSession($name);
584   }
585
586   /**
587    * Returns WebAssert object.
588    *
589    * @param string $name
590    *   (optional) Name of the session. Defaults to the active session.
591    *
592    * @return \Drupal\Tests\WebAssert
593    *   A new web-assert option for asserting the presence of elements with.
594    */
595   public function assertSession($name = NULL) {
596     return new WebAssert($this->getSession($name), $this->baseUrl);
597   }
598
599   /**
600    * Prepare for a request to testing site.
601    *
602    * The testing site is protected via a SIMPLETEST_USER_AGENT cookie that is
603    * checked by drupal_valid_test_ua().
604    *
605    * @see drupal_valid_test_ua()
606    */
607   protected function prepareRequest() {
608     $session = $this->getSession();
609     $session->setCookie('SIMPLETEST_USER_AGENT', drupal_generate_test_ua($this->databasePrefix));
610   }
611
612   /**
613    * Builds an a absolute URL from a system path or a URL object.
614    *
615    * @param string|\Drupal\Core\Url $path
616    *   A system path or a URL.
617    * @param array $options
618    *   Options to be passed to Url::fromUri().
619    *
620    * @return string
621    *   An absolute URL stsring.
622    */
623   protected function buildUrl($path, array $options = []) {
624     if ($path instanceof Url) {
625       $url_options = $path->getOptions();
626       $options = $url_options + $options;
627       $path->setOptions($options);
628       return $path->setAbsolute()->toString();
629     }
630     // The URL generator service is not necessarily available yet; e.g., in
631     // interactive installer tests.
632     elseif ($this->container->has('url_generator')) {
633       $force_internal = isset($options['external']) && $options['external'] == FALSE;
634       if (!$force_internal && UrlHelper::isExternal($path)) {
635         return Url::fromUri($path, $options)->toString();
636       }
637       else {
638         $uri = $path === '<front>' ? 'base:/' : 'base:/' . $path;
639         // Path processing is needed for language prefixing.  Skip it when a
640         // path that may look like an external URL is being used as internal.
641         $options['path_processing'] = !$force_internal;
642         return Url::fromUri($uri, $options)
643           ->setAbsolute()
644           ->toString();
645       }
646     }
647     else {
648       return $this->getAbsoluteUrl($path);
649     }
650   }
651
652   /**
653    * Retrieves a Drupal path or an absolute path.
654    *
655    * @param string|\Drupal\Core\Url $path
656    *   Drupal path or URL to load into Mink controlled browser.
657    * @param array $options
658    *   (optional) Options to be forwarded to the url generator.
659    * @param string[] $headers
660    *   An array containing additional HTTP request headers, the array keys are
661    *   the header names and the array values the header values. This is useful
662    *   to set for example the "Accept-Language" header for requesting the page
663    *   in a different language. Note that not all headers are supported, for
664    *   example the "Accept" header is always overridden by the browser. For
665    *   testing REST APIs it is recommended to directly use an HTTP client such
666    *   as Guzzle instead.
667    *
668    * @return string
669    *   The retrieved HTML string, also available as $this->getRawContent()
670    */
671   protected function drupalGet($path, array $options = [], array $headers = []) {
672     $options['absolute'] = TRUE;
673     $url = $this->buildUrl($path, $options);
674
675     $session = $this->getSession();
676
677     $this->prepareRequest();
678     foreach ($headers as $header_name => $header_value) {
679       $session->setRequestHeader($header_name, $header_value);
680     }
681
682     $session->visit($url);
683     $out = $session->getPage()->getContent();
684
685     // Ensure that any changes to variables in the other thread are picked up.
686     $this->refreshVariables();
687
688     // Replace original page output with new output from redirected page(s).
689     if ($new = $this->checkForMetaRefresh()) {
690       $out = $new;
691       // We are finished with all meta refresh redirects, so reset the counter.
692       $this->metaRefreshCount = 0;
693     }
694
695     // Log only for JavascriptTestBase tests because for Goutte we log with
696     // ::getResponseLogHandler.
697     if ($this->htmlOutputEnabled && !($this->getSession()->getDriver() instanceof GoutteDriver)) {
698       $html_output = 'GET request to: ' . $url .
699         '<hr />Ending URL: ' . $this->getSession()->getCurrentUrl();
700       $html_output .= '<hr />' . $out;
701       $html_output .= $this->getHtmlOutputHeaders();
702       $this->htmlOutput($html_output);
703     }
704
705     return $out;
706   }
707
708   /**
709    * Takes a path and returns an absolute path.
710    *
711    * @param string $path
712    *   A path from the Mink controlled browser content.
713    *
714    * @return string
715    *   The $path with $base_url prepended, if necessary.
716    */
717   protected function getAbsoluteUrl($path) {
718     global $base_url, $base_path;
719
720     $parts = parse_url($path);
721     if (empty($parts['host'])) {
722       // Ensure that we have a string (and no xpath object).
723       $path = (string) $path;
724       // Strip $base_path, if existent.
725       $length = strlen($base_path);
726       if (substr($path, 0, $length) === $base_path) {
727         $path = substr($path, $length);
728       }
729       // Ensure that we have an absolute path.
730       if (empty($path) || $path[0] !== '/') {
731         $path = '/' . $path;
732       }
733       // Finally, prepend the $base_url.
734       $path = $base_url . $path;
735     }
736     return $path;
737   }
738
739   /**
740    * Logs in a user using the Mink controlled browser.
741    *
742    * If a user is already logged in, then the current user is logged out before
743    * logging in the specified user.
744    *
745    * Please note that neither the current user nor the passed-in user object is
746    * populated with data of the logged in user. If you need full access to the
747    * user object after logging in, it must be updated manually. If you also need
748    * access to the plain-text password of the user (set by drupalCreateUser()),
749    * e.g. to log in the same user again, then it must be re-assigned manually.
750    * For example:
751    * @code
752    *   // Create a user.
753    *   $account = $this->drupalCreateUser(array());
754    *   $this->drupalLogin($account);
755    *   // Load real user object.
756    *   $pass_raw = $account->passRaw;
757    *   $account = User::load($account->id());
758    *   $account->passRaw = $pass_raw;
759    * @endcode
760    *
761    * @param \Drupal\Core\Session\AccountInterface $account
762    *   User object representing the user to log in.
763    *
764    * @see drupalCreateUser()
765    */
766   protected function drupalLogin(AccountInterface $account) {
767     if ($this->loggedInUser) {
768       $this->drupalLogout();
769     }
770
771     $this->drupalGet('user/login');
772     $this->submitForm([
773       'name' => $account->getUsername(),
774       'pass' => $account->passRaw,
775     ], t('Log in'));
776
777     // @see BrowserTestBase::drupalUserIsLoggedIn()
778     $account->sessionId = $this->getSession()->getCookie($this->getSessionName());
779     $this->assertTrue($this->drupalUserIsLoggedIn($account), new FormattableMarkup('User %name successfully logged in.', ['%name' => $account->getAccountName()]));
780
781     $this->loggedInUser = $account;
782     $this->container->get('current_user')->setAccount($account);
783   }
784
785   /**
786    * Logs a user out of the Mink controlled browser and confirms.
787    *
788    * Confirms logout by checking the login page.
789    */
790   protected function drupalLogout() {
791     // Make a request to the logout page, and redirect to the user page, the
792     // idea being if you were properly logged out you should be seeing a login
793     // screen.
794     $assert_session = $this->assertSession();
795     $this->drupalGet('user/logout', ['query' => ['destination' => 'user']]);
796     $assert_session->fieldExists('name');
797     $assert_session->fieldExists('pass');
798
799     // @see BrowserTestBase::drupalUserIsLoggedIn()
800     unset($this->loggedInUser->sessionId);
801     $this->loggedInUser = FALSE;
802     $this->container->get('current_user')->setAccount(new AnonymousUserSession());
803   }
804
805   /**
806    * Fills and submits a form.
807    *
808    * @param array $edit
809    *   Field data in an associative array. Changes the current input fields
810    *   (where possible) to the values indicated.
811    *
812    *   A checkbox can be set to TRUE to be checked and should be set to FALSE to
813    *   be unchecked.
814    * @param string $submit
815    *   Value of the submit button whose click is to be emulated. For example,
816    *   'Save'. The processing of the request depends on this value. For example,
817    *   a form may have one button with the value 'Save' and another button with
818    *   the value 'Delete', and execute different code depending on which one is
819    *   clicked.
820    * @param string $form_html_id
821    *   (optional) HTML ID of the form to be submitted. On some pages
822    *   there are many identical forms, so just using the value of the submit
823    *   button is not enough. For example: 'trigger-node-presave-assign-form'.
824    *   Note that this is not the Drupal $form_id, but rather the HTML ID of the
825    *   form, which is typically the same thing but with hyphens replacing the
826    *   underscores.
827    */
828   protected function submitForm(array $edit, $submit, $form_html_id = NULL) {
829     $assert_session = $this->assertSession();
830
831     // Get the form.
832     if (isset($form_html_id)) {
833       $form = $assert_session->elementExists('xpath', "//form[@id='$form_html_id']");
834       $submit_button = $assert_session->buttonExists($submit, $form);
835       $action = $form->getAttribute('action');
836     }
837     else {
838       $submit_button = $assert_session->buttonExists($submit);
839       $form = $assert_session->elementExists('xpath', './ancestor::form', $submit_button);
840       $action = $form->getAttribute('action');
841     }
842
843     // Edit the form values.
844     foreach ($edit as $name => $value) {
845       $field = $assert_session->fieldExists($name, $form);
846
847       // Provide support for the values '1' and '0' for checkboxes instead of
848       // TRUE and FALSE.
849       // @todo Get rid of supporting 1/0 by converting all tests cases using
850       // this to boolean values.
851       $field_type = $field->getAttribute('type');
852       if ($field_type === 'checkbox') {
853         $value = (bool) $value;
854       }
855
856       $field->setValue($value);
857     }
858
859     // Submit form.
860     $this->prepareRequest();
861     $submit_button->press();
862
863     // Ensure that any changes to variables in the other thread are picked up.
864     $this->refreshVariables();
865
866     // Check if there are any meta refresh redirects (like Batch API pages).
867     if ($this->checkForMetaRefresh()) {
868       // We are finished with all meta refresh redirects, so reset the counter.
869       $this->metaRefreshCount = 0;
870     }
871
872     // Log only for JavascriptTestBase tests because for Goutte we log with
873     // ::getResponseLogHandler.
874     if ($this->htmlOutputEnabled && !($this->getSession()->getDriver() instanceof GoutteDriver)) {
875       $out = $this->getSession()->getPage()->getContent();
876       $html_output = 'POST request to: ' . $action .
877         '<hr />Ending URL: ' . $this->getSession()->getCurrentUrl();
878       $html_output .= '<hr />' . $out;
879       $html_output .= $this->getHtmlOutputHeaders();
880       $this->htmlOutput($html_output);
881     }
882
883   }
884
885   /**
886    * Executes a form submission.
887    *
888    * It will be done as usual POST request with Mink.
889    *
890    * @param \Drupal\Core\Url|string $path
891    *   Location of the post form. Either a Drupal path or an absolute path or
892    *   NULL to post to the current page. For multi-stage forms you can set the
893    *   path to NULL and have it post to the last received page. Example:
894    *
895    *   @code
896    *   // First step in form.
897    *   $edit = array(...);
898    *   $this->drupalPostForm('some_url', $edit, 'Save');
899    *
900    *   // Second step in form.
901    *   $edit = array(...);
902    *   $this->drupalPostForm(NULL, $edit, 'Save');
903    *   @endcode
904    * @param array $edit
905    *   Field data in an associative array. Changes the current input fields
906    *   (where possible) to the values indicated.
907    *
908    *   When working with form tests, the keys for an $edit element should match
909    *   the 'name' parameter of the HTML of the form. For example, the 'body'
910    *   field for a node has the following HTML:
911    *   @code
912    *   <textarea id="edit-body-und-0-value" class="text-full form-textarea
913    *    resize-vertical" placeholder="" cols="60" rows="9"
914    *    name="body[0][value]"></textarea>
915    *   @endcode
916    *   When testing this field using an $edit parameter, the code becomes:
917    *   @code
918    *   $edit["body[0][value]"] = 'My test value';
919    *   @endcode
920    *
921    *   A checkbox can be set to TRUE to be checked and should be set to FALSE to
922    *   be unchecked. Multiple select fields can be tested using 'name[]' and
923    *   setting each of the desired values in an array:
924    *   @code
925    *   $edit = array();
926    *   $edit['name[]'] = array('value1', 'value2');
927    *   @endcode
928    *   @todo change $edit to disallow NULL as a value for Drupal 9.
929    *     https://www.drupal.org/node/2802401
930    * @param string $submit
931    *   Value of the submit button whose click is to be emulated. For example,
932    *   'Save'. The processing of the request depends on this value. For example,
933    *   a form may have one button with the value 'Save' and another button with
934    *   the value 'Delete', and execute different code depending on which one is
935    *   clicked.
936    *
937    *   This function can also be called to emulate an Ajax submission. In this
938    *   case, this value needs to be an array with the following keys:
939    *   - path: A path to submit the form values to for Ajax-specific processing.
940    *   - triggering_element: If the value for the 'path' key is a generic Ajax
941    *     processing path, this needs to be set to the name of the element. If
942    *     the name doesn't identify the element uniquely, then this should
943    *     instead be an array with a single key/value pair, corresponding to the
944    *     element name and value. The \Drupal\Core\Form\FormAjaxResponseBuilder
945    *     uses this to find the #ajax information for the element, including
946    *     which specific callback to use for processing the request.
947    *
948    *   This can also be set to NULL in order to emulate an Internet Explorer
949    *   submission of a form with a single text field, and pressing ENTER in that
950    *   textfield: under these conditions, no button information is added to the
951    *   POST data.
952    * @param array $options
953    *   Options to be forwarded to the url generator.
954    *
955    * @return string
956    *   (deprecated) The response content after submit form. It is necessary for
957    *   backwards compatibility and will be removed before Drupal 9.0. You should
958    *   just use the webAssert object for your assertions.
959    */
960   protected function drupalPostForm($path, $edit, $submit, array $options = []) {
961     if (is_object($submit)) {
962       // Cast MarkupInterface objects to string.
963       $submit = (string) $submit;
964     }
965     if ($edit === NULL) {
966       $edit = [];
967     }
968     if (is_array($edit)) {
969       $edit = $this->castSafeStrings($edit);
970     }
971
972     if (isset($path)) {
973       $this->drupalGet($path, $options);
974     }
975
976     $this->submitForm($edit, $submit);
977
978     return $this->getSession()->getPage()->getContent();
979   }
980
981   /**
982    * Helper function to get the options of select field.
983    *
984    * @param \Behat\Mink\Element\NodeElement|string $select
985    *   Name, ID, or Label of select field to assert.
986    * @param \Behat\Mink\Element\Element $container
987    *   (optional) Container element to check against. Defaults to current page.
988    *
989    * @return array
990    *   Associative array of option keys and values.
991    */
992   protected function getOptions($select, Element $container = NULL) {
993     if (is_string($select)) {
994       $select = $this->assertSession()->selectExists($select, $container);
995     }
996     $options = [];
997     /* @var \Behat\Mink\Element\NodeElement $option */
998     foreach ($select->findAll('xpath', '//option') as $option) {
999       $label = $option->getText();
1000       $value = $option->getAttribute('value') ?: $label;
1001       $options[$value] = $label;
1002     }
1003     return $options;
1004   }
1005
1006   /**
1007    * Installs Drupal into the Simpletest site.
1008    */
1009   public function installDrupal() {
1010     $this->initUserSession();
1011     $this->prepareSettings();
1012     $this->doInstall();
1013     $this->initSettings();
1014     $container = $this->initKernel(\Drupal::request());
1015     $this->initConfig($container);
1016     $this->installModulesFromClassProperty($container);
1017     $this->rebuildAll();
1018   }
1019
1020   /**
1021    * Returns whether a given user account is logged in.
1022    *
1023    * @param \Drupal\Core\Session\AccountInterface $account
1024    *   The user account object to check.
1025    *
1026    * @return bool
1027    *   Return TRUE if the user is logged in, FALSE otherwise.
1028    */
1029   protected function drupalUserIsLoggedIn(AccountInterface $account) {
1030     $logged_in = FALSE;
1031
1032     if (isset($account->sessionId)) {
1033       $session_handler = $this->container->get('session_handler.storage');
1034       $logged_in = (bool) $session_handler->read($account->sessionId);
1035     }
1036
1037     return $logged_in;
1038   }
1039
1040   /**
1041    * Clicks the element with the given CSS selector.
1042    *
1043    * @param string $css_selector
1044    *   The CSS selector identifying the element to click.
1045    */
1046   protected function click($css_selector) {
1047     $this->getSession()->getDriver()->click($this->cssSelectToXpath($css_selector));
1048   }
1049
1050   /**
1051    * Prevents serializing any properties.
1052    *
1053    * Browser tests are run in a separate process. To do this PHPUnit creates a
1054    * script to run the test. If it fails, the test result object will contain a
1055    * stack trace which includes the test object. It will attempt to serialize
1056    * it. Returning an empty array prevents it from serializing anything it
1057    * should not.
1058    *
1059    * @return array
1060    *   An empty array.
1061    *
1062    * @see vendor/phpunit/phpunit/src/Util/PHP/Template/TestCaseMethod.tpl.dist
1063    */
1064   public function __sleep() {
1065     return [];
1066   }
1067
1068   /**
1069    * Logs a HTML output message in a text file.
1070    *
1071    * The link to the HTML output message will be printed by the results printer.
1072    *
1073    * @param string $message
1074    *   The HTML output message to be stored.
1075    *
1076    * @see \Drupal\Tests\Listeners\VerbosePrinter::printResult()
1077    */
1078   protected function htmlOutput($message) {
1079     if (!$this->htmlOutputEnabled) {
1080       return;
1081     }
1082     $message = '<hr />ID #' . $this->htmlOutputCounter . ' (<a href="' . $this->htmlOutputClassName . '-' . ($this->htmlOutputCounter - 1) . '-' . $this->htmlOutputTestId . '.html">Previous</a> | <a href="' . $this->htmlOutputClassName . '-' . ($this->htmlOutputCounter + 1) . '-' . $this->htmlOutputTestId . '.html">Next</a>)<hr />' . $message;
1083     $html_output_filename = $this->htmlOutputClassName . '-' . $this->htmlOutputCounter . '-' . $this->htmlOutputTestId . '.html';
1084     file_put_contents($this->htmlOutputDirectory . '/' . $html_output_filename, $message);
1085     file_put_contents($this->htmlOutputCounterStorage, $this->htmlOutputCounter++);
1086     file_put_contents($this->htmlOutputFile, file_create_url('sites/simpletest/browser_output/' . $html_output_filename) . "\n", FILE_APPEND);
1087   }
1088
1089   /**
1090    * Returns headers in HTML output format.
1091    *
1092    * @return string
1093    *   HTML output headers.
1094    */
1095   protected function getHtmlOutputHeaders() {
1096     return $this->formatHtmlOutputHeaders($this->getSession()->getResponseHeaders());
1097   }
1098
1099   /**
1100    * Formats HTTP headers as string for HTML output logging.
1101    *
1102    * @param array[] $headers
1103    *   Headers that should be formatted.
1104    *
1105    * @return string
1106    *   The formatted HTML string.
1107    */
1108   protected function formatHtmlOutputHeaders(array $headers) {
1109     $flattened_headers = array_map(function ($header) {
1110       if (is_array($header)) {
1111         return implode(';', array_map('trim', $header));
1112       }
1113       else {
1114         return $header;
1115       }
1116     }, $headers);
1117     return '<hr />Headers: <pre>' . Html::escape(var_export($flattened_headers, TRUE)) . '</pre>';
1118   }
1119
1120   /**
1121    * Translates a CSS expression to its XPath equivalent.
1122    *
1123    * The search is relative to the root element (HTML tag normally) of the page.
1124    *
1125    * @param string $selector
1126    *   CSS selector to use in the search.
1127    * @param bool $html
1128    *   (optional) Enables HTML support. Disable it for XML documents.
1129    * @param string $prefix
1130    *   (optional) The prefix for the XPath expression.
1131    *
1132    * @return string
1133    *   The equivalent XPath of a CSS expression.
1134    */
1135   protected function cssSelectToXpath($selector, $html = TRUE, $prefix = 'descendant-or-self::') {
1136     return (new CssSelectorConverter($html))->toXPath($selector, $prefix);
1137   }
1138
1139   /**
1140    * Searches elements using a CSS selector in the raw content.
1141    *
1142    * The search is relative to the root element (HTML tag normally) of the page.
1143    *
1144    * @param string $selector
1145    *   CSS selector to use in the search.
1146    *
1147    * @return \Behat\Mink\Element\NodeElement[]
1148    *   The list of elements on the page that match the selector.
1149    */
1150   protected function cssSelect($selector) {
1151     return $this->getSession()->getPage()->findAll('css', $selector);
1152   }
1153
1154   /**
1155    * Follows a link by complete name.
1156    *
1157    * Will click the first link found with this link text.
1158    *
1159    * If the link is discovered and clicked, the test passes. Fail otherwise.
1160    *
1161    * @param string|\Drupal\Component\Render\MarkupInterface $label
1162    *   Text between the anchor tags.
1163    * @param int $index
1164    *   (optional) The index number for cases where multiple links have the same
1165    *   text. Defaults to 0.
1166    */
1167   protected function clickLink($label, $index = 0) {
1168     $label = (string) $label;
1169     $links = $this->getSession()->getPage()->findAll('named', ['link', $label]);
1170     $links[$index]->click();
1171   }
1172
1173   /**
1174    * Retrieves the plain-text content from the current page.
1175    */
1176   protected function getTextContent() {
1177     return $this->getSession()->getPage()->getText();
1178   }
1179
1180   /**
1181    * Performs an xpath search on the contents of the internal browser.
1182    *
1183    * The search is relative to the root element (HTML tag normally) of the page.
1184    *
1185    * @param string $xpath
1186    *   The xpath string to use in the search.
1187    * @param array $arguments
1188    *   An array of arguments with keys in the form ':name' matching the
1189    *   placeholders in the query. The values may be either strings or numeric
1190    *   values.
1191    *
1192    * @return \Behat\Mink\Element\NodeElement[]
1193    *   The list of elements matching the xpath expression.
1194    */
1195   protected function xpath($xpath, array $arguments = []) {
1196     $xpath = $this->assertSession()->buildXPathQuery($xpath, $arguments);
1197     return $this->getSession()->getPage()->findAll('xpath', $xpath);
1198   }
1199
1200   /**
1201    * Configuration accessor for tests. Returns non-overridden configuration.
1202    *
1203    * @param string $name
1204    *   Configuration name.
1205    *
1206    * @return \Drupal\Core\Config\Config
1207    *   The configuration object with original configuration data.
1208    */
1209   protected function config($name) {
1210     return $this->container->get('config.factory')->getEditable($name);
1211   }
1212
1213   /**
1214    * Returns all response headers.
1215    *
1216    * @return array
1217    *   The HTTP headers values.
1218    *
1219    * @deprecated Scheduled for removal in Drupal 9.0.0.
1220    *   Use $this->getSession()->getResponseHeaders() instead.
1221    */
1222   protected function drupalGetHeaders() {
1223     return $this->getSession()->getResponseHeaders();
1224   }
1225
1226   /**
1227    * Gets the value of an HTTP response header.
1228    *
1229    * If multiple requests were required to retrieve the page, only the headers
1230    * from the last request will be checked by default.
1231    *
1232    * @param string $name
1233    *   The name of the header to retrieve. Names are case-insensitive (see RFC
1234    *   2616 section 4.2).
1235    *
1236    * @return string|null
1237    *   The HTTP header value or NULL if not found.
1238    */
1239   protected function drupalGetHeader($name) {
1240     return $this->getSession()->getResponseHeader($name);
1241   }
1242
1243   /**
1244    * Get the current URL from the browser.
1245    *
1246    * @return string
1247    *   The current URL.
1248    */
1249   protected function getUrl() {
1250     return $this->getSession()->getCurrentUrl();
1251   }
1252
1253   /**
1254    * Gets the JavaScript drupalSettings variable for the currently-loaded page.
1255    *
1256    * @return array
1257    *   The JSON decoded drupalSettings value from the current page.
1258    */
1259   protected function getDrupalSettings() {
1260     $html = $this->getSession()->getPage()->getHtml();
1261     if (preg_match('@<script type="application/json" data-drupal-selector="drupal-settings-json">([^<]*)</script>@', $html, $matches)) {
1262       return Json::decode($matches[1]);
1263     }
1264     return [];
1265   }
1266
1267   /**
1268    * {@inheritdoc}
1269    */
1270   public static function assertEquals($expected, $actual, $message = '', $delta = 0.0, $maxDepth = 10, $canonicalize = FALSE, $ignoreCase = FALSE) {
1271     // Cast objects implementing MarkupInterface to string instead of
1272     // relying on PHP casting them to string depending on what they are being
1273     // comparing with.
1274     $expected = static::castSafeStrings($expected);
1275     $actual = static::castSafeStrings($actual);
1276     parent::assertEquals($expected, $actual, $message, $delta, $maxDepth, $canonicalize, $ignoreCase);
1277   }
1278
1279   /**
1280    * Retrieves the current calling line in the class under test.
1281    *
1282    * @return array
1283    *   An associative array with keys 'file', 'line' and 'function'.
1284    */
1285   protected function getTestMethodCaller() {
1286     $backtrace = debug_backtrace();
1287     // Find the test class that has the test method.
1288     while ($caller = Error::getLastCaller($backtrace)) {
1289       if (isset($caller['class']) && $caller['class'] === get_class($this)) {
1290         break;
1291       }
1292       // If the test method is implemented by a test class's parent then the
1293       // class name of $this will not be part of the backtrace.
1294       // In that case we process the backtrace until the caller is not a
1295       // subclass of $this and return the previous caller.
1296       if (isset($last_caller) && (!isset($caller['class']) || !is_subclass_of($this, $caller['class']))) {
1297         // Return the last caller since that has to be the test class.
1298         $caller = $last_caller;
1299         break;
1300       }
1301       // Otherwise we have not reached our test class yet: save the last caller
1302       // and remove an element from to backtrace to process the next call.
1303       $last_caller = $caller;
1304       array_shift($backtrace);
1305     }
1306
1307     return $caller;
1308   }
1309
1310   /**
1311    * Checks for meta refresh tag and if found call drupalGet() recursively.
1312    *
1313    * This function looks for the http-equiv attribute to be set to "Refresh" and
1314    * is case-insensitive.
1315    *
1316    * @return string|false
1317    *   Either the new page content or FALSE.
1318    */
1319   protected function checkForMetaRefresh() {
1320     $refresh = $this->cssSelect('meta[http-equiv="Refresh"], meta[http-equiv="refresh"]');
1321     if (!empty($refresh) && (!isset($this->maximumMetaRefreshCount) || $this->metaRefreshCount < $this->maximumMetaRefreshCount)) {
1322       // Parse the content attribute of the meta tag for the format:
1323       // "[delay]: URL=[page_to_redirect_to]".
1324       if (preg_match('/\d+;\s*URL=(?<url>.*)/i', $refresh[0]->getAttribute('content'), $match)) {
1325         $this->metaRefreshCount++;
1326         return $this->drupalGet($this->getAbsoluteUrl(Html::decodeEntities($match['url'])));
1327       }
1328     }
1329     return FALSE;
1330   }
1331
1332 }