Drupal investigation

BrowserTestBase.php 46KB

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