BrowserTestBase.php 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332
  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 available.
  309. if ($arg_json = $this->getMinkDriverArgs()) {
  310. $this->minkDefaultDriverArgs = json_decode($arg_json, TRUE);
  311. }
  312. // Get and check default driver class from environment if available.
  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. * Get the Mink driver args from an environment variable, if it is set. Can
  356. * be overridden in a derived class so it is possible to use a different
  357. * value for a subset of tests, e.g. the JavaScript tests.
  358. *
  359. * @return string|false
  360. * The JSON-encoded argument string. False if it is not set.
  361. */
  362. protected function getMinkDriverArgs() {
  363. return getenv('MINK_DRIVER_ARGS');
  364. }
  365. /**
  366. * Provides a Guzzle middleware handler to log every response received.
  367. *
  368. * @return callable
  369. * The callable handler that will do the logging.
  370. */
  371. protected function getResponseLogHandler() {
  372. return function (callable $handler) {
  373. return function (RequestInterface $request, array $options) use ($handler) {
  374. return $handler($request, $options)
  375. ->then(function (ResponseInterface $response) use ($request) {
  376. if ($this->htmlOutputEnabled) {
  377. $caller = $this->getTestMethodCaller();
  378. $html_output = 'Called from ' . $caller['function'] . ' line ' . $caller['line'];
  379. $html_output .= '<hr />' . $request->getMethod() . ' request to: ' . $request->getUri();
  380. // On redirect responses (status code starting with '3') we need
  381. // to remove the meta tag that would do a browser refresh. We
  382. // don't want to redirect developers away when they look at the
  383. // debug output file in their browser.
  384. $body = $response->getBody();
  385. $status_code = (string) $response->getStatusCode();
  386. if ($status_code[0] === '3') {
  387. $body = preg_replace('#<meta http-equiv="refresh" content=.+/>#', '', $body, 1);
  388. }
  389. $html_output .= '<hr />' . $body;
  390. $html_output .= $this->formatHtmlOutputHeaders($response->getHeaders());
  391. $this->htmlOutput($html_output);
  392. }
  393. return $response;
  394. });
  395. };
  396. };
  397. }
  398. /**
  399. * Registers additional Mink sessions.
  400. *
  401. * Tests wishing to use a different driver or change the default driver should
  402. * override this method.
  403. *
  404. * @code
  405. * // Register a new session that uses the MinkPonyDriver.
  406. * $pony = new MinkPonyDriver();
  407. * $session = new Session($pony);
  408. * $this->mink->registerSession('pony', $session);
  409. * @endcode
  410. */
  411. protected function registerSessions() {}
  412. /**
  413. * {@inheritdoc}
  414. */
  415. protected function setUp() {
  416. // Installing Drupal creates 1000s of objects. Garbage collection of these
  417. // objects is expensive. This appears to be causing random segmentation
  418. // faults in PHP 5.x due to https://bugs.php.net/bug.php?id=72286. Once
  419. // Drupal is installed is rebuilt, garbage collection is re-enabled.
  420. $disable_gc = version_compare(PHP_VERSION, '7', '<') && gc_enabled();
  421. if ($disable_gc) {
  422. gc_collect_cycles();
  423. gc_disable();
  424. }
  425. parent::setUp();
  426. $this->setupBaseUrl();
  427. // Install Drupal test site.
  428. $this->prepareEnvironment();
  429. $this->installDrupal();
  430. // Setup Mink.
  431. $session = $this->initMink();
  432. $cookies = $this->extractCookiesFromRequest(\Drupal::request());
  433. foreach ($cookies as $cookie_name => $values) {
  434. foreach ($values as $value) {
  435. $session->setCookie($cookie_name, $value);
  436. }
  437. }
  438. // Set up the browser test output file.
  439. $this->initBrowserOutputFile();
  440. // If garbage collection was disabled prior to rebuilding container,
  441. // re-enable it.
  442. if ($disable_gc) {
  443. gc_enable();
  444. }
  445. // Ensure that the test is not marked as risky because of no assertions. In
  446. // PHPUnit 6 tests that only make assertions using $this->assertSession()
  447. // can be marked as risky.
  448. $this->addToAssertionCount(1);
  449. }
  450. /**
  451. * Ensures test files are deletable within file_unmanaged_delete_recursive().
  452. *
  453. * Some tests chmod generated files to be read only. During
  454. * BrowserTestBase::cleanupEnvironment() and other cleanup operations,
  455. * these files need to get deleted too.
  456. *
  457. * @param string $path
  458. * The file path.
  459. */
  460. public static function filePreDeleteCallback($path) {
  461. // When the webserver runs with the same system user as phpunit, we can
  462. // make read-only files writable again. If not, chmod will fail while the
  463. // file deletion still works if file permissions have been configured
  464. // correctly. Thus, we ignore any problems while running chmod.
  465. @chmod($path, 0700);
  466. }
  467. /**
  468. * Clean up the Simpletest environment.
  469. */
  470. protected function cleanupEnvironment() {
  471. // Remove all prefixed tables.
  472. $original_connection_info = Database::getConnectionInfo('simpletest_original_default');
  473. $original_prefix = $original_connection_info['default']['prefix']['default'];
  474. $test_connection_info = Database::getConnectionInfo('default');
  475. $test_prefix = $test_connection_info['default']['prefix']['default'];
  476. if ($original_prefix != $test_prefix) {
  477. $tables = Database::getConnection()->schema()->findTables('%');
  478. foreach ($tables as $table) {
  479. if (Database::getConnection()->schema()->dropTable($table)) {
  480. unset($tables[$table]);
  481. }
  482. }
  483. }
  484. // Delete test site directory.
  485. file_unmanaged_delete_recursive($this->siteDirectory, [$this, 'filePreDeleteCallback']);
  486. }
  487. /**
  488. * {@inheritdoc}
  489. */
  490. protected function tearDown() {
  491. parent::tearDown();
  492. // Destroy the testing kernel.
  493. if (isset($this->kernel)) {
  494. $this->cleanupEnvironment();
  495. $this->kernel->shutdown();
  496. }
  497. // Ensure that internal logged in variable is reset.
  498. $this->loggedInUser = FALSE;
  499. if ($this->mink) {
  500. $this->mink->stopSessions();
  501. }
  502. // Restore original shutdown callbacks.
  503. if (function_exists('drupal_register_shutdown_function')) {
  504. $callbacks = &drupal_register_shutdown_function();
  505. $callbacks = $this->originalShutdownCallbacks;
  506. }
  507. }
  508. /**
  509. * Returns Mink session.
  510. *
  511. * @param string $name
  512. * (optional) Name of the session. Defaults to the active session.
  513. *
  514. * @return \Behat\Mink\Session
  515. * The active Mink session object.
  516. */
  517. public function getSession($name = NULL) {
  518. return $this->mink->getSession($name);
  519. }
  520. /**
  521. * Returns WebAssert object.
  522. *
  523. * @param string $name
  524. * (optional) Name of the session. Defaults to the active session.
  525. *
  526. * @return \Drupal\Tests\WebAssert
  527. * A new web-assert option for asserting the presence of elements with.
  528. */
  529. public function assertSession($name = NULL) {
  530. return new WebAssert($this->getSession($name), $this->baseUrl);
  531. }
  532. /**
  533. * Prepare for a request to testing site.
  534. *
  535. * The testing site is protected via a SIMPLETEST_USER_AGENT cookie that is
  536. * checked by drupal_valid_test_ua().
  537. *
  538. * @see drupal_valid_test_ua()
  539. */
  540. protected function prepareRequest() {
  541. $session = $this->getSession();
  542. $session->setCookie('SIMPLETEST_USER_AGENT', drupal_generate_test_ua($this->databasePrefix));
  543. }
  544. /**
  545. * Builds an a absolute URL from a system path or a URL object.
  546. *
  547. * @param string|\Drupal\Core\Url $path
  548. * A system path or a URL.
  549. * @param array $options
  550. * Options to be passed to Url::fromUri().
  551. *
  552. * @return string
  553. * An absolute URL stsring.
  554. */
  555. protected function buildUrl($path, array $options = []) {
  556. if ($path instanceof Url) {
  557. $url_options = $path->getOptions();
  558. $options = $url_options + $options;
  559. $path->setOptions($options);
  560. return $path->setAbsolute()->toString();
  561. }
  562. // The URL generator service is not necessarily available yet; e.g., in
  563. // interactive installer tests.
  564. elseif ($this->container->has('url_generator')) {
  565. $force_internal = isset($options['external']) && $options['external'] == FALSE;
  566. if (!$force_internal && UrlHelper::isExternal($path)) {
  567. return Url::fromUri($path, $options)->toString();
  568. }
  569. else {
  570. $uri = $path === '<front>' ? 'base:/' : 'base:/' . $path;
  571. // Path processing is needed for language prefixing. Skip it when a
  572. // path that may look like an external URL is being used as internal.
  573. $options['path_processing'] = !$force_internal;
  574. return Url::fromUri($uri, $options)
  575. ->setAbsolute()
  576. ->toString();
  577. }
  578. }
  579. else {
  580. return $this->getAbsoluteUrl($path);
  581. }
  582. }
  583. /**
  584. * Retrieves a Drupal path or an absolute path.
  585. *
  586. * @param string|\Drupal\Core\Url $path
  587. * Drupal path or URL to load into Mink controlled browser.
  588. * @param array $options
  589. * (optional) Options to be forwarded to the url generator.
  590. * @param string[] $headers
  591. * An array containing additional HTTP request headers, the array keys are
  592. * the header names and the array values the header values. This is useful
  593. * to set for example the "Accept-Language" header for requesting the page
  594. * in a different language. Note that not all headers are supported, for
  595. * example the "Accept" header is always overridden by the browser. For
  596. * testing REST APIs it is recommended to directly use an HTTP client such
  597. * as Guzzle instead.
  598. *
  599. * @return string
  600. * The retrieved HTML string, also available as $this->getRawContent()
  601. */
  602. protected function drupalGet($path, array $options = [], array $headers = []) {
  603. $options['absolute'] = TRUE;
  604. $url = $this->buildUrl($path, $options);
  605. $session = $this->getSession();
  606. $this->prepareRequest();
  607. foreach ($headers as $header_name => $header_value) {
  608. $session->setRequestHeader($header_name, $header_value);
  609. }
  610. $session->visit($url);
  611. $out = $session->getPage()->getContent();
  612. // Ensure that any changes to variables in the other thread are picked up.
  613. $this->refreshVariables();
  614. // Replace original page output with new output from redirected page(s).
  615. if ($new = $this->checkForMetaRefresh()) {
  616. $out = $new;
  617. // We are finished with all meta refresh redirects, so reset the counter.
  618. $this->metaRefreshCount = 0;
  619. }
  620. // Log only for JavascriptTestBase tests because for Goutte we log with
  621. // ::getResponseLogHandler.
  622. if ($this->htmlOutputEnabled && !($this->getSession()->getDriver() instanceof GoutteDriver)) {
  623. $html_output = 'GET request to: ' . $url .
  624. '<hr />Ending URL: ' . $this->getSession()->getCurrentUrl();
  625. $html_output .= '<hr />' . $out;
  626. $html_output .= $this->getHtmlOutputHeaders();
  627. $this->htmlOutput($html_output);
  628. }
  629. return $out;
  630. }
  631. /**
  632. * Takes a path and returns an absolute path.
  633. *
  634. * @param string $path
  635. * A path from the Mink controlled browser content.
  636. *
  637. * @return string
  638. * The $path with $base_url prepended, if necessary.
  639. */
  640. protected function getAbsoluteUrl($path) {
  641. global $base_url, $base_path;
  642. $parts = parse_url($path);
  643. if (empty($parts['host'])) {
  644. // Ensure that we have a string (and no xpath object).
  645. $path = (string) $path;
  646. // Strip $base_path, if existent.
  647. $length = strlen($base_path);
  648. if (substr($path, 0, $length) === $base_path) {
  649. $path = substr($path, $length);
  650. }
  651. // Ensure that we have an absolute path.
  652. if (empty($path) || $path[0] !== '/') {
  653. $path = '/' . $path;
  654. }
  655. // Finally, prepend the $base_url.
  656. $path = $base_url . $path;
  657. }
  658. return $path;
  659. }
  660. /**
  661. * Logs in a user using the Mink controlled browser.
  662. *
  663. * If a user is already logged in, then the current user is logged out before
  664. * logging in the specified user.
  665. *
  666. * Please note that neither the current user nor the passed-in user object is
  667. * populated with data of the logged in user. If you need full access to the
  668. * user object after logging in, it must be updated manually. If you also need
  669. * access to the plain-text password of the user (set by drupalCreateUser()),
  670. * e.g. to log in the same user again, then it must be re-assigned manually.
  671. * For example:
  672. * @code
  673. * // Create a user.
  674. * $account = $this->drupalCreateUser(array());
  675. * $this->drupalLogin($account);
  676. * // Load real user object.
  677. * $pass_raw = $account->passRaw;
  678. * $account = User::load($account->id());
  679. * $account->passRaw = $pass_raw;
  680. * @endcode
  681. *
  682. * @param \Drupal\Core\Session\AccountInterface $account
  683. * User object representing the user to log in.
  684. *
  685. * @see drupalCreateUser()
  686. */
  687. protected function drupalLogin(AccountInterface $account) {
  688. if ($this->loggedInUser) {
  689. $this->drupalLogout();
  690. }
  691. $this->drupalGet('user/login');
  692. $this->submitForm([
  693. 'name' => $account->getUsername(),
  694. 'pass' => $account->passRaw,
  695. ], t('Log in'));
  696. // @see BrowserTestBase::drupalUserIsLoggedIn()
  697. $account->sessionId = $this->getSession()->getCookie($this->getSessionName());
  698. $this->assertTrue($this->drupalUserIsLoggedIn($account), new FormattableMarkup('User %name successfully logged in.', ['%name' => $account->getAccountName()]));
  699. $this->loggedInUser = $account;
  700. $this->container->get('current_user')->setAccount($account);
  701. }
  702. /**
  703. * Logs a user out of the Mink controlled browser and confirms.
  704. *
  705. * Confirms logout by checking the login page.
  706. */
  707. protected function drupalLogout() {
  708. // Make a request to the logout page, and redirect to the user page, the
  709. // idea being if you were properly logged out you should be seeing a login
  710. // screen.
  711. $assert_session = $this->assertSession();
  712. $this->drupalGet('user/logout', ['query' => ['destination' => 'user']]);
  713. $assert_session->fieldExists('name');
  714. $assert_session->fieldExists('pass');
  715. // @see BrowserTestBase::drupalUserIsLoggedIn()
  716. unset($this->loggedInUser->sessionId);
  717. $this->loggedInUser = FALSE;
  718. $this->container->get('current_user')->setAccount(new AnonymousUserSession());
  719. }
  720. /**
  721. * Fills and submits a form.
  722. *
  723. * @param array $edit
  724. * Field data in an associative array. Changes the current input fields
  725. * (where possible) to the values indicated.
  726. *
  727. * A checkbox can be set to TRUE to be checked and should be set to FALSE to
  728. * be unchecked.
  729. * @param string $submit
  730. * Value of the submit button whose click is to be emulated. For example,
  731. * 'Save'. The processing of the request depends on this value. For example,
  732. * a form may have one button with the value 'Save' and another button with
  733. * the value 'Delete', and execute different code depending on which one is
  734. * clicked.
  735. * @param string $form_html_id
  736. * (optional) HTML ID of the form to be submitted. On some pages
  737. * there are many identical forms, so just using the value of the submit
  738. * button is not enough. For example: 'trigger-node-presave-assign-form'.
  739. * Note that this is not the Drupal $form_id, but rather the HTML ID of the
  740. * form, which is typically the same thing but with hyphens replacing the
  741. * underscores.
  742. */
  743. protected function submitForm(array $edit, $submit, $form_html_id = NULL) {
  744. $assert_session = $this->assertSession();
  745. // Get the form.
  746. if (isset($form_html_id)) {
  747. $form = $assert_session->elementExists('xpath', "//form[@id='$form_html_id']");
  748. $submit_button = $assert_session->buttonExists($submit, $form);
  749. $action = $form->getAttribute('action');
  750. }
  751. else {
  752. $submit_button = $assert_session->buttonExists($submit);
  753. $form = $assert_session->elementExists('xpath', './ancestor::form', $submit_button);
  754. $action = $form->getAttribute('action');
  755. }
  756. // Edit the form values.
  757. foreach ($edit as $name => $value) {
  758. $field = $assert_session->fieldExists($name, $form);
  759. // Provide support for the values '1' and '0' for checkboxes instead of
  760. // TRUE and FALSE.
  761. // @todo Get rid of supporting 1/0 by converting all tests cases using
  762. // this to boolean values.
  763. $field_type = $field->getAttribute('type');
  764. if ($field_type === 'checkbox') {
  765. $value = (bool) $value;
  766. }
  767. $field->setValue($value);
  768. }
  769. // Submit form.
  770. $this->prepareRequest();
  771. $submit_button->press();
  772. // Ensure that any changes to variables in the other thread are picked up.
  773. $this->refreshVariables();
  774. // Check if there are any meta refresh redirects (like Batch API pages).
  775. if ($this->checkForMetaRefresh()) {
  776. // We are finished with all meta refresh redirects, so reset the counter.
  777. $this->metaRefreshCount = 0;
  778. }
  779. // Log only for JavascriptTestBase tests because for Goutte we log with
  780. // ::getResponseLogHandler.
  781. if ($this->htmlOutputEnabled && !($this->getSession()->getDriver() instanceof GoutteDriver)) {
  782. $out = $this->getSession()->getPage()->getContent();
  783. $html_output = 'POST request to: ' . $action .
  784. '<hr />Ending URL: ' . $this->getSession()->getCurrentUrl();
  785. $html_output .= '<hr />' . $out;
  786. $html_output .= $this->getHtmlOutputHeaders();
  787. $this->htmlOutput($html_output);
  788. }
  789. }
  790. /**
  791. * Executes a form submission.
  792. *
  793. * It will be done as usual POST request with Mink.
  794. *
  795. * @param \Drupal\Core\Url|string $path
  796. * Location of the post form. Either a Drupal path or an absolute path or
  797. * NULL to post to the current page. For multi-stage forms you can set the
  798. * path to NULL and have it post to the last received page. Example:
  799. *
  800. * @code
  801. * // First step in form.
  802. * $edit = array(...);
  803. * $this->drupalPostForm('some_url', $edit, 'Save');
  804. *
  805. * // Second step in form.
  806. * $edit = array(...);
  807. * $this->drupalPostForm(NULL, $edit, 'Save');
  808. * @endcode
  809. * @param array $edit
  810. * Field data in an associative array. Changes the current input fields
  811. * (where possible) to the values indicated.
  812. *
  813. * When working with form tests, the keys for an $edit element should match
  814. * the 'name' parameter of the HTML of the form. For example, the 'body'
  815. * field for a node has the following HTML:
  816. * @code
  817. * <textarea id="edit-body-und-0-value" class="text-full form-textarea
  818. * resize-vertical" placeholder="" cols="60" rows="9"
  819. * name="body[0][value]"></textarea>
  820. * @endcode
  821. * When testing this field using an $edit parameter, the code becomes:
  822. * @code
  823. * $edit["body[0][value]"] = 'My test value';
  824. * @endcode
  825. *
  826. * A checkbox can be set to TRUE to be checked and should be set to FALSE to
  827. * be unchecked. Multiple select fields can be tested using 'name[]' and
  828. * setting each of the desired values in an array:
  829. * @code
  830. * $edit = array();
  831. * $edit['name[]'] = array('value1', 'value2');
  832. * @endcode
  833. * @todo change $edit to disallow NULL as a value for Drupal 9.
  834. * https://www.drupal.org/node/2802401
  835. * @param string $submit
  836. * Value of the submit button whose click is to be emulated. For example,
  837. * 'Save'. The processing of the request depends on this value. For example,
  838. * a form may have one button with the value 'Save' and another button with
  839. * the value 'Delete', and execute different code depending on which one is
  840. * clicked.
  841. *
  842. * This function can also be called to emulate an Ajax submission. In this
  843. * case, this value needs to be an array with the following keys:
  844. * - path: A path to submit the form values to for Ajax-specific processing.
  845. * - triggering_element: If the value for the 'path' key is a generic Ajax
  846. * processing path, this needs to be set to the name of the element. If
  847. * the name doesn't identify the element uniquely, then this should
  848. * instead be an array with a single key/value pair, corresponding to the
  849. * element name and value. The \Drupal\Core\Form\FormAjaxResponseBuilder
  850. * uses this to find the #ajax information for the element, including
  851. * which specific callback to use for processing the request.
  852. *
  853. * This can also be set to NULL in order to emulate an Internet Explorer
  854. * submission of a form with a single text field, and pressing ENTER in that
  855. * textfield: under these conditions, no button information is added to the
  856. * POST data.
  857. * @param array $options
  858. * Options to be forwarded to the url generator.
  859. *
  860. * @return string
  861. * (deprecated) The response content after submit form. It is necessary for
  862. * backwards compatibility and will be removed before Drupal 9.0. You should
  863. * just use the webAssert object for your assertions.
  864. */
  865. protected function drupalPostForm($path, $edit, $submit, array $options = []) {
  866. if (is_object($submit)) {
  867. // Cast MarkupInterface objects to string.
  868. $submit = (string) $submit;
  869. }
  870. if ($edit === NULL) {
  871. $edit = [];
  872. }
  873. if (is_array($edit)) {
  874. $edit = $this->castSafeStrings($edit);
  875. }
  876. if (isset($path)) {
  877. $this->drupalGet($path, $options);
  878. }
  879. $this->submitForm($edit, $submit);
  880. return $this->getSession()->getPage()->getContent();
  881. }
  882. /**
  883. * Helper function to get the options of select field.
  884. *
  885. * @param \Behat\Mink\Element\NodeElement|string $select
  886. * Name, ID, or Label of select field to assert.
  887. * @param \Behat\Mink\Element\Element $container
  888. * (optional) Container element to check against. Defaults to current page.
  889. *
  890. * @return array
  891. * Associative array of option keys and values.
  892. */
  893. protected function getOptions($select, Element $container = NULL) {
  894. if (is_string($select)) {
  895. $select = $this->assertSession()->selectExists($select, $container);
  896. }
  897. $options = [];
  898. /* @var \Behat\Mink\Element\NodeElement $option */
  899. foreach ($select->findAll('xpath', '//option') as $option) {
  900. $label = $option->getText();
  901. $value = $option->getAttribute('value') ?: $label;
  902. $options[$value] = $label;
  903. }
  904. return $options;
  905. }
  906. /**
  907. * Installs Drupal into the Simpletest site.
  908. */
  909. public function installDrupal() {
  910. $this->initUserSession();
  911. $this->prepareSettings();
  912. $this->doInstall();
  913. $this->initSettings();
  914. $container = $this->initKernel(\Drupal::request());
  915. $this->initConfig($container);
  916. $this->installModulesFromClassProperty($container);
  917. $this->rebuildAll();
  918. }
  919. /**
  920. * Returns whether a given user account is logged in.
  921. *
  922. * @param \Drupal\Core\Session\AccountInterface $account
  923. * The user account object to check.
  924. *
  925. * @return bool
  926. * Return TRUE if the user is logged in, FALSE otherwise.
  927. */
  928. protected function drupalUserIsLoggedIn(AccountInterface $account) {
  929. $logged_in = FALSE;
  930. if (isset($account->sessionId)) {
  931. $session_handler = $this->container->get('session_handler.storage');
  932. $logged_in = (bool) $session_handler->read($account->sessionId);
  933. }
  934. return $logged_in;
  935. }
  936. /**
  937. * Clicks the element with the given CSS selector.
  938. *
  939. * @param string $css_selector
  940. * The CSS selector identifying the element to click.
  941. */
  942. protected function click($css_selector) {
  943. $this->getSession()->getDriver()->click($this->cssSelectToXpath($css_selector));
  944. }
  945. /**
  946. * Prevents serializing any properties.
  947. *
  948. * Browser tests are run in a separate process. To do this PHPUnit creates a
  949. * script to run the test. If it fails, the test result object will contain a
  950. * stack trace which includes the test object. It will attempt to serialize
  951. * it. Returning an empty array prevents it from serializing anything it
  952. * should not.
  953. *
  954. * @return array
  955. * An empty array.
  956. *
  957. * @see vendor/phpunit/phpunit/src/Util/PHP/Template/TestCaseMethod.tpl.dist
  958. */
  959. public function __sleep() {
  960. return [];
  961. }
  962. /**
  963. * Logs a HTML output message in a text file.
  964. *
  965. * The link to the HTML output message will be printed by the results printer.
  966. *
  967. * @param string $message
  968. * The HTML output message to be stored.
  969. *
  970. * @see \Drupal\Tests\Listeners\VerbosePrinter::printResult()
  971. */
  972. protected function htmlOutput($message) {
  973. if (!$this->htmlOutputEnabled) {
  974. return;
  975. }
  976. $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;
  977. $html_output_filename = $this->htmlOutputClassName . '-' . $this->htmlOutputCounter . '-' . $this->htmlOutputTestId . '.html';
  978. file_put_contents($this->htmlOutputDirectory . '/' . $html_output_filename, $message);
  979. file_put_contents($this->htmlOutputCounterStorage, $this->htmlOutputCounter++);
  980. file_put_contents($this->htmlOutputFile, file_create_url('sites/simpletest/browser_output/' . $html_output_filename) . "\n", FILE_APPEND);
  981. }
  982. /**
  983. * Returns headers in HTML output format.
  984. *
  985. * @return string
  986. * HTML output headers.
  987. */
  988. protected function getHtmlOutputHeaders() {
  989. return $this->formatHtmlOutputHeaders($this->getSession()->getResponseHeaders());
  990. }
  991. /**
  992. * Formats HTTP headers as string for HTML output logging.
  993. *
  994. * @param array[] $headers
  995. * Headers that should be formatted.
  996. *
  997. * @return string
  998. * The formatted HTML string.
  999. */
  1000. protected function formatHtmlOutputHeaders(array $headers) {
  1001. $flattened_headers = array_map(function ($header) {
  1002. if (is_array($header)) {
  1003. return implode(';', array_map('trim', $header));
  1004. }
  1005. else {
  1006. return $header;
  1007. }
  1008. }, $headers);
  1009. return '<hr />Headers: <pre>' . Html::escape(var_export($flattened_headers, TRUE)) . '</pre>';
  1010. }
  1011. /**
  1012. * Translates a CSS expression to its XPath equivalent.
  1013. *
  1014. * The search is relative to the root element (HTML tag normally) of the page.
  1015. *
  1016. * @param string $selector
  1017. * CSS selector to use in the search.
  1018. * @param bool $html
  1019. * (optional) Enables HTML support. Disable it for XML documents.
  1020. * @param string $prefix
  1021. * (optional) The prefix for the XPath expression.
  1022. *
  1023. * @return string
  1024. * The equivalent XPath of a CSS expression.
  1025. */
  1026. protected function cssSelectToXpath($selector, $html = TRUE, $prefix = 'descendant-or-self::') {
  1027. return (new CssSelectorConverter($html))->toXPath($selector, $prefix);
  1028. }
  1029. /**
  1030. * Searches elements using a CSS selector in the raw content.
  1031. *
  1032. * The search is relative to the root element (HTML tag normally) of the page.
  1033. *
  1034. * @param string $selector
  1035. * CSS selector to use in the search.
  1036. *
  1037. * @return \Behat\Mink\Element\NodeElement[]
  1038. * The list of elements on the page that match the selector.
  1039. */
  1040. protected function cssSelect($selector) {
  1041. return $this->getSession()->getPage()->findAll('css', $selector);
  1042. }
  1043. /**
  1044. * Follows a link by complete name.
  1045. *
  1046. * Will click the first link found with this link text.
  1047. *
  1048. * If the link is discovered and clicked, the test passes. Fail otherwise.
  1049. *
  1050. * @param string|\Drupal\Component\Render\MarkupInterface $label
  1051. * Text between the anchor tags.
  1052. * @param int $index
  1053. * (optional) The index number for cases where multiple links have the same
  1054. * text. Defaults to 0.
  1055. */
  1056. protected function clickLink($label, $index = 0) {
  1057. $label = (string) $label;
  1058. $links = $this->getSession()->getPage()->findAll('named', ['link', $label]);
  1059. $links[$index]->click();
  1060. }
  1061. /**
  1062. * Retrieves the plain-text content from the current page.
  1063. */
  1064. protected function getTextContent() {
  1065. return $this->getSession()->getPage()->getText();
  1066. }
  1067. /**
  1068. * Performs an xpath search on the contents of the internal browser.
  1069. *
  1070. * The search is relative to the root element (HTML tag normally) of the page.
  1071. *
  1072. * @param string $xpath
  1073. * The xpath string to use in the search.
  1074. * @param array $arguments
  1075. * An array of arguments with keys in the form ':name' matching the
  1076. * placeholders in the query. The values may be either strings or numeric
  1077. * values.
  1078. *
  1079. * @return \Behat\Mink\Element\NodeElement[]
  1080. * The list of elements matching the xpath expression.
  1081. */
  1082. protected function xpath($xpath, array $arguments = []) {
  1083. $xpath = $this->assertSession()->buildXPathQuery($xpath, $arguments);
  1084. return $this->getSession()->getPage()->findAll('xpath', $xpath);
  1085. }
  1086. /**
  1087. * Configuration accessor for tests. Returns non-overridden configuration.
  1088. *
  1089. * @param string $name
  1090. * Configuration name.
  1091. *
  1092. * @return \Drupal\Core\Config\Config
  1093. * The configuration object with original configuration data.
  1094. */
  1095. protected function config($name) {
  1096. return $this->container->get('config.factory')->getEditable($name);
  1097. }
  1098. /**
  1099. * Returns all response headers.
  1100. *
  1101. * @return array
  1102. * The HTTP headers values.
  1103. *
  1104. * @deprecated Scheduled for removal in Drupal 9.0.0.
  1105. * Use $this->getSession()->getResponseHeaders() instead.
  1106. */
  1107. protected function drupalGetHeaders() {
  1108. return $this->getSession()->getResponseHeaders();
  1109. }
  1110. /**
  1111. * Gets the value of an HTTP response header.
  1112. *
  1113. * If multiple requests were required to retrieve the page, only the headers
  1114. * from the last request will be checked by default.
  1115. *
  1116. * @param string $name
  1117. * The name of the header to retrieve. Names are case-insensitive (see RFC
  1118. * 2616 section 4.2).
  1119. *
  1120. * @return string|null
  1121. * The HTTP header value or NULL if not found.
  1122. */
  1123. protected function drupalGetHeader($name) {
  1124. return $this->getSession()->getResponseHeader($name);
  1125. }
  1126. /**
  1127. * Get the current URL from the browser.
  1128. *
  1129. * @return string
  1130. * The current URL.
  1131. */
  1132. protected function getUrl() {
  1133. return $this->getSession()->getCurrentUrl();
  1134. }
  1135. /**
  1136. * Gets the JavaScript drupalSettings variable for the currently-loaded page.
  1137. *
  1138. * @return array
  1139. * The JSON decoded drupalSettings value from the current page.
  1140. */
  1141. protected function getDrupalSettings() {
  1142. $html = $this->getSession()->getPage()->getHtml();
  1143. if (preg_match('@<script type="application/json" data-drupal-selector="drupal-settings-json">([^<]*)</script>@', $html, $matches)) {
  1144. return Json::decode($matches[1]);
  1145. }
  1146. return [];
  1147. }
  1148. /**
  1149. * {@inheritdoc}
  1150. */
  1151. public static function assertEquals($expected, $actual, $message = '', $delta = 0.0, $maxDepth = 10, $canonicalize = FALSE, $ignoreCase = FALSE) {
  1152. // Cast objects implementing MarkupInterface to string instead of
  1153. // relying on PHP casting them to string depending on what they are being
  1154. // comparing with.
  1155. $expected = static::castSafeStrings($expected);
  1156. $actual = static::castSafeStrings($actual);
  1157. parent::assertEquals($expected, $actual, $message, $delta, $maxDepth, $canonicalize, $ignoreCase);
  1158. }
  1159. /**
  1160. * Retrieves the current calling line in the class under test.
  1161. *
  1162. * @return array
  1163. * An associative array with keys 'file', 'line' and 'function'.
  1164. */
  1165. protected function getTestMethodCaller() {
  1166. $backtrace = debug_backtrace();
  1167. // Find the test class that has the test method.
  1168. while ($caller = Error::getLastCaller($backtrace)) {
  1169. if (isset($caller['class']) && $caller['class'] === get_class($this)) {
  1170. break;
  1171. }
  1172. // If the test method is implemented by a test class's parent then the
  1173. // class name of $this will not be part of the backtrace.
  1174. // In that case we process the backtrace until the caller is not a
  1175. // subclass of $this and return the previous caller.
  1176. if (isset($last_caller) && (!isset($caller['class']) || !is_subclass_of($this, $caller['class']))) {
  1177. // Return the last caller since that has to be the test class.
  1178. $caller = $last_caller;
  1179. break;
  1180. }
  1181. // Otherwise we have not reached our test class yet: save the last caller
  1182. // and remove an element from to backtrace to process the next call.
  1183. $last_caller = $caller;
  1184. array_shift($backtrace);
  1185. }
  1186. return $caller;
  1187. }
  1188. /**
  1189. * Checks for meta refresh tag and if found call drupalGet() recursively.
  1190. *
  1191. * This function looks for the http-equiv attribute to be set to "Refresh" and
  1192. * is case-insensitive.
  1193. *
  1194. * @return string|false
  1195. * Either the new page content or FALSE.
  1196. */
  1197. protected function checkForMetaRefresh() {
  1198. $refresh = $this->cssSelect('meta[http-equiv="Refresh"], meta[http-equiv="refresh"]');
  1199. if (!empty($refresh) && (!isset($this->maximumMetaRefreshCount) || $this->metaRefreshCount < $this->maximumMetaRefreshCount)) {
  1200. // Parse the content attribute of the meta tag for the format:
  1201. // "[delay]: URL=[page_to_redirect_to]".
  1202. if (preg_match('/\d+;\s*URL=(?<url>.*)/i', $refresh[0]->getAttribute('content'), $match)) {
  1203. $this->metaRefreshCount++;
  1204. return $this->drupalGet($this->getAbsoluteUrl(Html::decodeEntities($match['url'])));
  1205. }
  1206. }
  1207. return FALSE;
  1208. }
  1209. }