BrowserTestBase.php 43 KB

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