BrowserTestBase.php 42 KB

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