BrowserTestBase.php 47 KB

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