WebTestBase.php 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061
  1. <?php
  2. namespace Drupal\simpletest;
  3. use Drupal\block\Entity\Block;
  4. use Drupal\Component\Serialization\Json;
  5. use Drupal\Component\Utility\Html;
  6. use Drupal\Component\Utility\NestedArray;
  7. use Drupal\Component\Utility\UrlHelper;
  8. use Drupal\Component\Utility\SafeMarkup;
  9. use Drupal\Core\EventSubscriber\AjaxResponseSubscriber;
  10. use Drupal\Core\EventSubscriber\MainContentViewSubscriber;
  11. use Drupal\Core\Session\AccountInterface;
  12. use Drupal\Core\Session\AnonymousUserSession;
  13. use Drupal\Core\Test\AssertMailTrait;
  14. use Drupal\Core\Test\FunctionalTestSetupTrait;
  15. use Drupal\Core\Url;
  16. use Drupal\system\Tests\Cache\AssertPageCacheContextsAndTagsTrait;
  17. use Drupal\Tests\EntityViewTrait;
  18. use Drupal\Tests\block\Traits\BlockCreationTrait as BaseBlockCreationTrait;
  19. use Drupal\Tests\node\Traits\ContentTypeCreationTrait;
  20. use Drupal\Tests\node\Traits\NodeCreationTrait;
  21. use Drupal\Tests\Traits\Core\CronRunTrait;
  22. use Drupal\Tests\TestFileCreationTrait;
  23. use Drupal\Tests\user\Traits\UserCreationTrait;
  24. use Drupal\Tests\XdebugRequestTrait;
  25. use Zend\Diactoros\Uri;
  26. /**
  27. * Test case for typical Drupal tests.
  28. *
  29. * @ingroup testing
  30. */
  31. abstract class WebTestBase extends TestBase {
  32. use FunctionalTestSetupTrait;
  33. use AssertContentTrait;
  34. use TestFileCreationTrait {
  35. getTestFiles as drupalGetTestFiles;
  36. compareFiles as drupalCompareFiles;
  37. }
  38. use AssertPageCacheContextsAndTagsTrait;
  39. use BaseBlockCreationTrait {
  40. placeBlock as drupalPlaceBlock;
  41. }
  42. use ContentTypeCreationTrait {
  43. createContentType as drupalCreateContentType;
  44. }
  45. use CronRunTrait;
  46. use AssertMailTrait {
  47. getMails as drupalGetMails;
  48. }
  49. use NodeCreationTrait {
  50. getNodeByTitle as drupalGetNodeByTitle;
  51. createNode as drupalCreateNode;
  52. }
  53. use UserCreationTrait {
  54. createUser as drupalCreateUser;
  55. createRole as drupalCreateRole;
  56. createAdminRole as drupalCreateAdminRole;
  57. }
  58. use XdebugRequestTrait;
  59. use EntityViewTrait {
  60. buildEntityView as drupalBuildEntityView;
  61. }
  62. /**
  63. * The profile to install as a basis for testing.
  64. *
  65. * @var string
  66. */
  67. protected $profile = 'testing';
  68. /**
  69. * The URL currently loaded in the internal browser.
  70. *
  71. * @var string
  72. */
  73. protected $url;
  74. /**
  75. * The handle of the current cURL connection.
  76. *
  77. * @var resource
  78. */
  79. protected $curlHandle;
  80. /**
  81. * Whether or not to assert the presence of the X-Drupal-Ajax-Token.
  82. *
  83. * @var bool
  84. */
  85. protected $assertAjaxHeader = TRUE;
  86. /**
  87. * The headers of the page currently loaded in the internal browser.
  88. *
  89. * @var array
  90. */
  91. protected $headers;
  92. /**
  93. * The cookies of the page currently loaded in the internal browser.
  94. *
  95. * @var array
  96. */
  97. protected $cookies = [];
  98. /**
  99. * Indicates that headers should be dumped if verbose output is enabled.
  100. *
  101. * Headers are dumped to verbose by drupalGet(), drupalHead(), and
  102. * drupalPostForm().
  103. *
  104. * @var bool
  105. */
  106. protected $dumpHeaders = FALSE;
  107. /**
  108. * The current user logged in using the internal browser.
  109. *
  110. * @var \Drupal\Core\Session\AccountInterface|bool
  111. */
  112. protected $loggedInUser = FALSE;
  113. /**
  114. * The current cookie file used by cURL.
  115. *
  116. * We do not reuse the cookies in further runs, so we do not need a file
  117. * but we still need cookie handling, so we set the jar to NULL.
  118. */
  119. protected $cookieFile = NULL;
  120. /**
  121. * Additional cURL options.
  122. *
  123. * \Drupal\simpletest\WebTestBase itself never sets this but always obeys what
  124. * is set.
  125. */
  126. protected $additionalCurlOptions = [];
  127. /**
  128. * The original batch, before it was changed for testing purposes.
  129. *
  130. * @var array
  131. */
  132. protected $originalBatch;
  133. /**
  134. * The original user, before it was changed to a clean uid = 1 for testing.
  135. *
  136. * @var object
  137. */
  138. protected $originalUser = NULL;
  139. /**
  140. * The original shutdown handlers array, before it was cleaned for testing.
  141. *
  142. * @var array
  143. */
  144. protected $originalShutdownCallbacks = [];
  145. /**
  146. * The current session ID, if available.
  147. */
  148. protected $sessionId = NULL;
  149. /**
  150. * The maximum number of redirects to follow when handling responses.
  151. *
  152. * @var int
  153. */
  154. protected $maximumRedirects = 5;
  155. /**
  156. * The number of redirects followed during the handling of a request.
  157. */
  158. protected $redirectCount;
  159. /**
  160. * The number of meta refresh redirects to follow, or NULL if unlimited.
  161. *
  162. * @var null|int
  163. */
  164. protected $maximumMetaRefreshCount = NULL;
  165. /**
  166. * The number of meta refresh redirects followed during ::drupalGet().
  167. *
  168. * @var int
  169. */
  170. protected $metaRefreshCount = 0;
  171. /**
  172. * Cookies to set on curl requests.
  173. *
  174. * @var array
  175. */
  176. protected $curlCookies = [];
  177. /**
  178. * An array of custom translations suitable for drupal_rewrite_settings().
  179. *
  180. * @var array
  181. */
  182. protected $customTranslations;
  183. /**
  184. * Constructor for \Drupal\simpletest\WebTestBase.
  185. */
  186. public function __construct($test_id = NULL) {
  187. parent::__construct($test_id);
  188. $this->skipClasses[__CLASS__] = TRUE;
  189. $this->classLoader = require DRUPAL_ROOT . '/autoload.php';
  190. }
  191. /**
  192. * Checks to see whether a block appears on the page.
  193. *
  194. * @param \Drupal\block\Entity\Block $block
  195. * The block entity to find on the page.
  196. */
  197. protected function assertBlockAppears(Block $block) {
  198. $result = $this->findBlockInstance($block);
  199. $this->assertTrue(!empty($result), format_string('Ensure the block @id appears on the page', ['@id' => $block->id()]));
  200. }
  201. /**
  202. * Checks to see whether a block does not appears on the page.
  203. *
  204. * @param \Drupal\block\Entity\Block $block
  205. * The block entity to find on the page.
  206. */
  207. protected function assertNoBlockAppears(Block $block) {
  208. $result = $this->findBlockInstance($block);
  209. $this->assertFalse(!empty($result), format_string('Ensure the block @id does not appear on the page', ['@id' => $block->id()]));
  210. }
  211. /**
  212. * Find a block instance on the page.
  213. *
  214. * @param \Drupal\block\Entity\Block $block
  215. * The block entity to find on the page.
  216. *
  217. * @return array
  218. * The result from the xpath query.
  219. */
  220. protected function findBlockInstance(Block $block) {
  221. return $this->xpath('//div[@id = :id]', [':id' => 'block-' . $block->id()]);
  222. }
  223. /**
  224. * Log in a user with the internal browser.
  225. *
  226. * If a user is already logged in, then the current user is logged out before
  227. * logging in the specified user.
  228. *
  229. * Please note that neither the current user nor the passed-in user object is
  230. * populated with data of the logged in user. If you need full access to the
  231. * user object after logging in, it must be updated manually. If you also need
  232. * access to the plain-text password of the user (set by drupalCreateUser()),
  233. * e.g. to log in the same user again, then it must be re-assigned manually.
  234. * For example:
  235. * @code
  236. * // Create a user.
  237. * $account = $this->drupalCreateUser(array());
  238. * $this->drupalLogin($account);
  239. * // Load real user object.
  240. * $pass_raw = $account->pass_raw;
  241. * $account = User::load($account->id());
  242. * $account->pass_raw = $pass_raw;
  243. * @endcode
  244. *
  245. * @param \Drupal\Core\Session\AccountInterface $account
  246. * User object representing the user to log in.
  247. *
  248. * @see drupalCreateUser()
  249. */
  250. protected function drupalLogin(AccountInterface $account) {
  251. if ($this->loggedInUser) {
  252. $this->drupalLogout();
  253. }
  254. $edit = [
  255. 'name' => $account->getUsername(),
  256. 'pass' => $account->pass_raw
  257. ];
  258. $this->drupalPostForm('user/login', $edit, t('Log in'));
  259. // @see WebTestBase::drupalUserIsLoggedIn()
  260. if (isset($this->sessionId)) {
  261. $account->session_id = $this->sessionId;
  262. }
  263. $pass = $this->assert($this->drupalUserIsLoggedIn($account), format_string('User %name successfully logged in.', ['%name' => $account->getUsername()]), 'User login');
  264. if ($pass) {
  265. $this->loggedInUser = $account;
  266. $this->container->get('current_user')->setAccount($account);
  267. }
  268. }
  269. /**
  270. * Returns whether a given user account is logged in.
  271. *
  272. * @param \Drupal\user\UserInterface $account
  273. * The user account object to check.
  274. */
  275. protected function drupalUserIsLoggedIn($account) {
  276. $logged_in = FALSE;
  277. if (isset($account->session_id)) {
  278. $session_handler = $this->container->get('session_handler.storage');
  279. $logged_in = (bool) $session_handler->read($account->session_id);
  280. }
  281. return $logged_in;
  282. }
  283. /**
  284. * Logs a user out of the internal browser and confirms.
  285. *
  286. * Confirms logout by checking the login page.
  287. */
  288. protected function drupalLogout() {
  289. // Make a request to the logout page, and redirect to the user page, the
  290. // idea being if you were properly logged out you should be seeing a login
  291. // screen.
  292. $this->drupalGet('user/logout', ['query' => ['destination' => 'user/login']]);
  293. $this->assertResponse(200, 'User was logged out.');
  294. $pass = $this->assertField('name', 'Username field found.', 'Logout');
  295. $pass = $pass && $this->assertField('pass', 'Password field found.', 'Logout');
  296. if ($pass) {
  297. // @see WebTestBase::drupalUserIsLoggedIn()
  298. unset($this->loggedInUser->session_id);
  299. $this->loggedInUser = FALSE;
  300. $this->container->get('current_user')->setAccount(new AnonymousUserSession());
  301. }
  302. }
  303. /**
  304. * Sets up a Drupal site for running functional and integration tests.
  305. *
  306. * Installs Drupal with the installation profile specified in
  307. * \Drupal\simpletest\WebTestBase::$profile into the prefixed database.
  308. *
  309. * Afterwards, installs any additional modules specified in the static
  310. * \Drupal\simpletest\WebTestBase::$modules property of each class in the
  311. * class hierarchy.
  312. *
  313. * After installation all caches are flushed and several configuration values
  314. * are reset to the values of the parent site executing the test, since the
  315. * default values may be incompatible with the environment in which tests are
  316. * being executed.
  317. */
  318. protected function setUp() {
  319. // Set an explicit time zone to not rely on the system one, which may vary
  320. // from setup to setup. The Australia/Sydney time zone is chosen so all
  321. // tests are run using an edge case scenario (UTC+10 and DST). This choice
  322. // is made to prevent time zone related regressions and reduce the
  323. // fragility of the testing system in general. This is also set in config in
  324. // \Drupal\simpletest\WebTestBase::initConfig().
  325. date_default_timezone_set('Australia/Sydney');
  326. // Preserve original batch for later restoration.
  327. $this->setBatch();
  328. // Initialize user 1 and session name.
  329. $this->initUserSession();
  330. // Prepare the child site settings.
  331. $this->prepareSettings();
  332. // Execute the non-interactive installer.
  333. $this->doInstall();
  334. // Import new settings.php written by the installer.
  335. $this->initSettings();
  336. // Initialize the request and container post-install.
  337. $container = $this->initKernel(\Drupal::request());
  338. // Initialize and override certain configurations.
  339. $this->initConfig($container);
  340. // Collect modules to install.
  341. $this->installModulesFromClassProperty($container);
  342. // Restore the original batch.
  343. $this->restoreBatch();
  344. // Reset/rebuild everything.
  345. $this->rebuildAll();
  346. }
  347. /**
  348. * Preserve the original batch, and instantiate the test batch.
  349. */
  350. protected function setBatch() {
  351. // When running tests through the Simpletest UI (vs. on the command line),
  352. // Simpletest's batch conflicts with the installer's batch. Batch API does
  353. // not support the concept of nested batches (in which the nested is not
  354. // progressive), so we need to temporarily pretend there was no batch.
  355. // Backup the currently running Simpletest batch.
  356. $this->originalBatch = batch_get();
  357. // Reset the static batch to remove Simpletest's batch operations.
  358. $batch = &batch_get();
  359. $batch = [];
  360. }
  361. /**
  362. * Restore the original batch.
  363. *
  364. * @see ::setBatch
  365. */
  366. protected function restoreBatch() {
  367. // Restore the original Simpletest batch.
  368. $batch = &batch_get();
  369. $batch = $this->originalBatch;
  370. }
  371. /**
  372. * Queues custom translations to be written to settings.php.
  373. *
  374. * Use WebTestBase::writeCustomTranslations() to apply and write the queued
  375. * translations.
  376. *
  377. * @param string $langcode
  378. * The langcode to add translations for.
  379. * @param array $values
  380. * Array of values containing the untranslated string and its translation.
  381. * For example:
  382. * @code
  383. * array(
  384. * '' => array('Sunday' => 'domingo'),
  385. * 'Long month name' => array('March' => 'marzo'),
  386. * );
  387. * @endcode
  388. * Pass an empty array to remove all existing custom translations for the
  389. * given $langcode.
  390. */
  391. protected function addCustomTranslations($langcode, array $values) {
  392. // If $values is empty, then the test expects all custom translations to be
  393. // cleared.
  394. if (empty($values)) {
  395. $this->customTranslations[$langcode] = [];
  396. }
  397. // Otherwise, $values are expected to be merged into previously passed
  398. // values, while retaining keys that are not explicitly set.
  399. else {
  400. foreach ($values as $context => $translations) {
  401. foreach ($translations as $original => $translation) {
  402. $this->customTranslations[$langcode][$context][$original] = $translation;
  403. }
  404. }
  405. }
  406. }
  407. /**
  408. * Writes custom translations to the test site's settings.php.
  409. *
  410. * Use TestBase::addCustomTranslations() to queue custom translations before
  411. * calling this method.
  412. */
  413. protected function writeCustomTranslations() {
  414. $settings = [];
  415. foreach ($this->customTranslations as $langcode => $values) {
  416. $settings_key = 'locale_custom_strings_' . $langcode;
  417. // Update in-memory settings directly.
  418. $this->settingsSet($settings_key, $values);
  419. $settings['settings'][$settings_key] = (object) [
  420. 'value' => $values,
  421. 'required' => TRUE,
  422. ];
  423. }
  424. // Only rewrite settings if there are any translation changes to write.
  425. if (!empty($settings)) {
  426. $this->writeSettings($settings);
  427. }
  428. }
  429. /**
  430. * Cleans up after testing.
  431. *
  432. * Deletes created files and temporary files directory, deletes the tables
  433. * created by setUp(), and resets the database prefix.
  434. */
  435. protected function tearDown() {
  436. // Destroy the testing kernel.
  437. if (isset($this->kernel)) {
  438. $this->kernel->shutdown();
  439. }
  440. parent::tearDown();
  441. // Ensure that the maximum meta refresh count is reset.
  442. $this->maximumMetaRefreshCount = NULL;
  443. // Ensure that internal logged in variable and cURL options are reset.
  444. $this->loggedInUser = FALSE;
  445. $this->additionalCurlOptions = [];
  446. // Close the CURL handler and reset the cookies array used for upgrade
  447. // testing so test classes containing multiple tests are not polluted.
  448. $this->curlClose();
  449. $this->curlCookies = [];
  450. $this->cookies = [];
  451. }
  452. /**
  453. * Initializes the cURL connection.
  454. *
  455. * If the simpletest_httpauth_credentials variable is set, this function will
  456. * add HTTP authentication headers. This is necessary for testing sites that
  457. * are protected by login credentials from public access.
  458. * See the description of $curl_options for other options.
  459. */
  460. protected function curlInitialize() {
  461. global $base_url;
  462. if (!isset($this->curlHandle)) {
  463. $this->curlHandle = curl_init();
  464. // Some versions/configurations of cURL break on a NULL cookie jar, so
  465. // supply a real file.
  466. if (empty($this->cookieFile)) {
  467. $this->cookieFile = $this->publicFilesDirectory . '/cookie.jar';
  468. }
  469. $curl_options = [
  470. CURLOPT_COOKIEJAR => $this->cookieFile,
  471. CURLOPT_URL => $base_url,
  472. CURLOPT_FOLLOWLOCATION => FALSE,
  473. CURLOPT_RETURNTRANSFER => TRUE,
  474. // Required to make the tests run on HTTPS.
  475. CURLOPT_SSL_VERIFYPEER => FALSE,
  476. // Required to make the tests run on HTTPS.
  477. CURLOPT_SSL_VERIFYHOST => FALSE,
  478. CURLOPT_HEADERFUNCTION => [&$this, 'curlHeaderCallback'],
  479. CURLOPT_USERAGENT => $this->databasePrefix,
  480. // Disable support for the @ prefix for uploading files.
  481. CURLOPT_SAFE_UPLOAD => TRUE,
  482. ];
  483. if (isset($this->httpAuthCredentials)) {
  484. $curl_options[CURLOPT_HTTPAUTH] = $this->httpAuthMethod;
  485. $curl_options[CURLOPT_USERPWD] = $this->httpAuthCredentials;
  486. }
  487. // curl_setopt_array() returns FALSE if any of the specified options
  488. // cannot be set, and stops processing any further options.
  489. $result = curl_setopt_array($this->curlHandle, $this->additionalCurlOptions + $curl_options);
  490. if (!$result) {
  491. throw new \UnexpectedValueException('One or more cURL options could not be set.');
  492. }
  493. }
  494. // We set the user agent header on each request so as to use the current
  495. // time and a new uniqid.
  496. curl_setopt($this->curlHandle, CURLOPT_USERAGENT, drupal_generate_test_ua($this->databasePrefix));
  497. }
  498. /**
  499. * Initializes and executes a cURL request.
  500. *
  501. * @param $curl_options
  502. * An associative array of cURL options to set, where the keys are constants
  503. * defined by the cURL library. For a list of valid options, see
  504. * http://php.net/manual/function.curl-setopt.php
  505. * @param $redirect
  506. * FALSE if this is an initial request, TRUE if this request is the result
  507. * of a redirect.
  508. *
  509. * @return
  510. * The content returned from the call to curl_exec().
  511. *
  512. * @see curlInitialize()
  513. */
  514. protected function curlExec($curl_options, $redirect = FALSE) {
  515. $this->curlInitialize();
  516. if (!empty($curl_options[CURLOPT_URL])) {
  517. // cURL incorrectly handles URLs with a fragment by including the
  518. // fragment in the request to the server, causing some web servers
  519. // to reject the request citing "400 - Bad Request". To prevent
  520. // this, we strip the fragment from the request.
  521. // TODO: Remove this for Drupal 8, since fixed in curl 7.20.0.
  522. if (strpos($curl_options[CURLOPT_URL], '#')) {
  523. $original_url = $curl_options[CURLOPT_URL];
  524. $curl_options[CURLOPT_URL] = strtok($curl_options[CURLOPT_URL], '#');
  525. }
  526. }
  527. $url = empty($curl_options[CURLOPT_URL]) ? curl_getinfo($this->curlHandle, CURLINFO_EFFECTIVE_URL) : $curl_options[CURLOPT_URL];
  528. if (!empty($curl_options[CURLOPT_POST])) {
  529. // This is a fix for the Curl library to prevent Expect: 100-continue
  530. // headers in POST requests, that may cause unexpected HTTP response
  531. // codes from some webservers (like lighttpd that returns a 417 error
  532. // code). It is done by setting an empty "Expect" header field that is
  533. // not overwritten by Curl.
  534. $curl_options[CURLOPT_HTTPHEADER][] = 'Expect:';
  535. }
  536. $cookies = [];
  537. if (!empty($this->curlCookies)) {
  538. $cookies = $this->curlCookies;
  539. }
  540. foreach ($this->extractCookiesFromRequest(\Drupal::request()) as $cookie_name => $values) {
  541. foreach ($values as $value) {
  542. $cookies[] = $cookie_name . '=' . $value;
  543. }
  544. }
  545. // Merge additional cookies in.
  546. if (!empty($cookies)) {
  547. $curl_options += [
  548. CURLOPT_COOKIE => '',
  549. ];
  550. // Ensure any existing cookie data string ends with the correct separator.
  551. if (!empty($curl_options[CURLOPT_COOKIE])) {
  552. $curl_options[CURLOPT_COOKIE] = rtrim($curl_options[CURLOPT_COOKIE], '; ') . '; ';
  553. }
  554. $curl_options[CURLOPT_COOKIE] .= implode('; ', $cookies) . ';';
  555. }
  556. curl_setopt_array($this->curlHandle, $this->additionalCurlOptions + $curl_options);
  557. if (!$redirect) {
  558. // Reset headers, the session ID and the redirect counter.
  559. $this->sessionId = NULL;
  560. $this->headers = [];
  561. $this->redirectCount = 0;
  562. }
  563. $content = curl_exec($this->curlHandle);
  564. $status = curl_getinfo($this->curlHandle, CURLINFO_HTTP_CODE);
  565. // cURL incorrectly handles URLs with fragments, so instead of
  566. // letting cURL handle redirects we take of them ourselves to
  567. // to prevent fragments being sent to the web server as part
  568. // of the request.
  569. // TODO: Remove this for Drupal 8, since fixed in curl 7.20.0.
  570. if (in_array($status, [300, 301, 302, 303, 305, 307]) && $this->redirectCount < $this->maximumRedirects) {
  571. if ($this->drupalGetHeader('location')) {
  572. $this->redirectCount++;
  573. $curl_options = [];
  574. $curl_options[CURLOPT_URL] = $this->drupalGetHeader('location');
  575. $curl_options[CURLOPT_HTTPGET] = TRUE;
  576. return $this->curlExec($curl_options, TRUE);
  577. }
  578. }
  579. $this->setRawContent($content);
  580. $this->url = isset($original_url) ? $original_url : curl_getinfo($this->curlHandle, CURLINFO_EFFECTIVE_URL);
  581. $message_vars = [
  582. '@method' => !empty($curl_options[CURLOPT_NOBODY]) ? 'HEAD' : (empty($curl_options[CURLOPT_POSTFIELDS]) ? 'GET' : 'POST'),
  583. '@url' => isset($original_url) ? $original_url : $url,
  584. '@status' => $status,
  585. '@length' => format_size(strlen($this->getRawContent()))
  586. ];
  587. $message = SafeMarkup::format('@method @url returned @status (@length).', $message_vars);
  588. $this->assertTrue($this->getRawContent() !== FALSE, $message, 'Browser');
  589. return $this->getRawContent();
  590. }
  591. /**
  592. * Reads headers and registers errors received from the tested site.
  593. *
  594. * @param $curlHandler
  595. * The cURL handler.
  596. * @param $header
  597. * An header.
  598. *
  599. * @see _drupal_log_error()
  600. */
  601. protected function curlHeaderCallback($curlHandler, $header) {
  602. // Header fields can be extended over multiple lines by preceding each
  603. // extra line with at least one SP or HT. They should be joined on receive.
  604. // Details are in RFC2616 section 4.
  605. if ($header[0] == ' ' || $header[0] == "\t") {
  606. // Normalize whitespace between chucks.
  607. $this->headers[] = array_pop($this->headers) . ' ' . trim($header);
  608. }
  609. else {
  610. $this->headers[] = $header;
  611. }
  612. // Errors are being sent via X-Drupal-Assertion-* headers,
  613. // generated by _drupal_log_error() in the exact form required
  614. // by \Drupal\simpletest\WebTestBase::error().
  615. if (preg_match('/^X-Drupal-Assertion-[0-9]+: (.*)$/', $header, $matches)) {
  616. // Call \Drupal\simpletest\WebTestBase::error() with the parameters from
  617. // the header.
  618. call_user_func_array([&$this, 'error'], unserialize(urldecode($matches[1])));
  619. }
  620. // Save cookies.
  621. if (preg_match('/^Set-Cookie: ([^=]+)=(.+)/', $header, $matches)) {
  622. $name = $matches[1];
  623. $parts = array_map('trim', explode(';', $matches[2]));
  624. $value = array_shift($parts);
  625. $this->cookies[$name] = ['value' => $value, 'secure' => in_array('secure', $parts)];
  626. if ($name === $this->getSessionName()) {
  627. if ($value != 'deleted') {
  628. $this->sessionId = $value;
  629. }
  630. else {
  631. $this->sessionId = NULL;
  632. }
  633. }
  634. }
  635. // This is required by cURL.
  636. return strlen($header);
  637. }
  638. /**
  639. * Close the cURL handler and unset the handler.
  640. */
  641. protected function curlClose() {
  642. if (isset($this->curlHandle)) {
  643. curl_close($this->curlHandle);
  644. unset($this->curlHandle);
  645. }
  646. }
  647. /**
  648. * Returns whether the test is being executed from within a test site.
  649. *
  650. * Mainly used by recursive tests (i.e. to test the testing framework).
  651. *
  652. * @return bool
  653. * TRUE if this test was instantiated in a request within the test site,
  654. * FALSE otherwise.
  655. *
  656. * @see \Drupal\Core\DrupalKernel::bootConfiguration()
  657. */
  658. protected function isInChildSite() {
  659. return DRUPAL_TEST_IN_CHILD_SITE;
  660. }
  661. /**
  662. * Retrieves a Drupal path or an absolute path.
  663. *
  664. * @param \Drupal\Core\Url|string $path
  665. * Drupal path or URL to load into internal browser
  666. * @param $options
  667. * Options to be forwarded to the url generator.
  668. * @param $headers
  669. * An array containing additional HTTP request headers, each formatted as
  670. * "name: value".
  671. *
  672. * @return string
  673. * The retrieved HTML string, also available as $this->getRawContent()
  674. */
  675. protected function drupalGet($path, array $options = [], array $headers = []) {
  676. // We re-using a CURL connection here. If that connection still has certain
  677. // options set, it might change the GET into a POST. Make sure we clear out
  678. // previous options.
  679. $out = $this->curlExec([CURLOPT_HTTPGET => TRUE, CURLOPT_URL => $this->buildUrl($path, $options), CURLOPT_NOBODY => FALSE, CURLOPT_HTTPHEADER => $headers]);
  680. // Ensure that any changes to variables in the other thread are picked up.
  681. $this->refreshVariables();
  682. // Replace original page output with new output from redirected page(s).
  683. if ($new = $this->checkForMetaRefresh()) {
  684. $out = $new;
  685. // We are finished with all meta refresh redirects, so reset the counter.
  686. $this->metaRefreshCount = 0;
  687. }
  688. if ($path instanceof Url) {
  689. $path = $path->setAbsolute()->toString(TRUE)->getGeneratedUrl();
  690. }
  691. $verbose = 'GET request to: ' . $path .
  692. '<hr />Ending URL: ' . $this->getUrl();
  693. if ($this->dumpHeaders) {
  694. $verbose .= '<hr />Headers: <pre>' . Html::escape(var_export(array_map('trim', $this->headers), TRUE)) . '</pre>';
  695. }
  696. $verbose .= '<hr />' . $out;
  697. $this->verbose($verbose);
  698. return $out;
  699. }
  700. /**
  701. * Retrieves a Drupal path or an absolute path and JSON decodes the result.
  702. *
  703. * @param \Drupal\Core\Url|string $path
  704. * Drupal path or URL to request AJAX from.
  705. * @param array $options
  706. * Array of URL options.
  707. * @param array $headers
  708. * Array of headers. Eg array('Accept: application/vnd.drupal-ajax').
  709. *
  710. * @return array
  711. * Decoded json.
  712. */
  713. protected function drupalGetJSON($path, array $options = [], array $headers = []) {
  714. return Json::decode($this->drupalGetWithFormat($path, 'json', $options, $headers));
  715. }
  716. /**
  717. * Retrieves a Drupal path or an absolute path for a given format.
  718. *
  719. * @param \Drupal\Core\Url|string $path
  720. * Drupal path or URL to request given format from.
  721. * @param string $format
  722. * The wanted request format.
  723. * @param array $options
  724. * Array of URL options.
  725. * @param array $headers
  726. * Array of headers.
  727. *
  728. * @return mixed
  729. * The result of the request.
  730. */
  731. protected function drupalGetWithFormat($path, $format, array $options = [], array $headers = []) {
  732. $options += ['query' => ['_format' => $format]];
  733. return $this->drupalGet($path, $options, $headers);
  734. }
  735. /**
  736. * Requests a path or URL in drupal_ajax format and JSON-decodes the response.
  737. *
  738. * @param \Drupal\Core\Url|string $path
  739. * Drupal path or URL to request from.
  740. * @param array $options
  741. * Array of URL options.
  742. * @param array $headers
  743. * Array of headers.
  744. *
  745. * @return array
  746. * Decoded JSON.
  747. */
  748. protected function drupalGetAjax($path, array $options = [], array $headers = []) {
  749. if (!isset($options['query'][MainContentViewSubscriber::WRAPPER_FORMAT])) {
  750. $options['query'][MainContentViewSubscriber::WRAPPER_FORMAT] = 'drupal_ajax';
  751. }
  752. return Json::decode($this->drupalGetXHR($path, $options, $headers));
  753. }
  754. /**
  755. * Requests a Drupal path or an absolute path as if it is a XMLHttpRequest.
  756. *
  757. * @param \Drupal\Core\Url|string $path
  758. * Drupal path or URL to request from.
  759. * @param array $options
  760. * Array of URL options.
  761. * @param array $headers
  762. * Array of headers.
  763. *
  764. * @return string
  765. * The retrieved content.
  766. */
  767. protected function drupalGetXHR($path, array $options = [], array $headers = []) {
  768. $headers[] = 'X-Requested-With: XMLHttpRequest';
  769. return $this->drupalGet($path, $options, $headers);
  770. }
  771. /**
  772. * Executes a form submission.
  773. *
  774. * It will be done as usual POST request with SimpleBrowser.
  775. *
  776. * @param \Drupal\Core\Url|string $path
  777. * Location of the post form. Either a Drupal path or an absolute path or
  778. * NULL to post to the current page. For multi-stage forms you can set the
  779. * path to NULL and have it post to the last received page. Example:
  780. *
  781. * @code
  782. * // First step in form.
  783. * $edit = array(...);
  784. * $this->drupalPostForm('some_url', $edit, t('Save'));
  785. *
  786. * // Second step in form.
  787. * $edit = array(...);
  788. * $this->drupalPostForm(NULL, $edit, t('Save'));
  789. * @endcode
  790. * @param $edit
  791. * Field data in an associative array. Changes the current input fields
  792. * (where possible) to the values indicated.
  793. *
  794. * When working with form tests, the keys for an $edit element should match
  795. * the 'name' parameter of the HTML of the form. For example, the 'body'
  796. * field for a node has the following HTML:
  797. * @code
  798. * <textarea id="edit-body-und-0-value" class="text-full form-textarea
  799. * resize-vertical" placeholder="" cols="60" rows="9"
  800. * name="body[0][value]"></textarea>
  801. * @endcode
  802. * When testing this field using an $edit parameter, the code becomes:
  803. * @code
  804. * $edit["body[0][value]"] = 'My test value';
  805. * @endcode
  806. *
  807. * A checkbox can be set to TRUE to be checked and should be set to FALSE to
  808. * be unchecked. Multiple select fields can be tested using 'name[]' and
  809. * setting each of the desired values in an array:
  810. * @code
  811. * $edit = array();
  812. * $edit['name[]'] = array('value1', 'value2');
  813. * @endcode
  814. * @param $submit
  815. * Value of the submit button whose click is to be emulated. For example,
  816. * t('Save'). The processing of the request depends on this value. For
  817. * example, a form may have one button with the value t('Save') and another
  818. * button with the value t('Delete'), and execute different code depending
  819. * on which one is clicked.
  820. *
  821. * This function can also be called to emulate an Ajax submission. In this
  822. * case, this value needs to be an array with the following keys:
  823. * - path: A path to submit the form values to for Ajax-specific processing.
  824. * - triggering_element: If the value for the 'path' key is a generic Ajax
  825. * processing path, this needs to be set to the name of the element. If
  826. * the name doesn't identify the element uniquely, then this should
  827. * instead be an array with a single key/value pair, corresponding to the
  828. * element name and value. The \Drupal\Core\Form\FormAjaxResponseBuilder
  829. * uses this to find the #ajax information for the element, including
  830. * which specific callback to use for processing the request.
  831. *
  832. * This can also be set to NULL in order to emulate an Internet Explorer
  833. * submission of a form with a single text field, and pressing ENTER in that
  834. * textfield: under these conditions, no button information is added to the
  835. * POST data.
  836. * @param $options
  837. * Options to be forwarded to the url generator.
  838. * @param $headers
  839. * An array containing additional HTTP request headers, each formatted as
  840. * "name: value".
  841. * @param $form_html_id
  842. * (optional) HTML ID of the form to be submitted. On some pages
  843. * there are many identical forms, so just using the value of the submit
  844. * button is not enough. For example: 'trigger-node-presave-assign-form'.
  845. * Note that this is not the Drupal $form_id, but rather the HTML ID of the
  846. * form, which is typically the same thing but with hyphens replacing the
  847. * underscores.
  848. * @param $extra_post
  849. * (optional) A string of additional data to append to the POST submission.
  850. * This can be used to add POST data for which there are no HTML fields, as
  851. * is done by drupalPostAjaxForm(). This string is literally appended to the
  852. * POST data, so it must already be urlencoded and contain a leading "&"
  853. * (e.g., "&extra_var1=hello+world&extra_var2=you%26me").
  854. */
  855. protected function drupalPostForm($path, $edit, $submit, array $options = [], array $headers = [], $form_html_id = NULL, $extra_post = NULL) {
  856. if (is_object($submit)) {
  857. // Cast MarkupInterface objects to string.
  858. $submit = (string) $submit;
  859. }
  860. if (is_array($edit)) {
  861. $edit = $this->castSafeStrings($edit);
  862. }
  863. $submit_matches = FALSE;
  864. $ajax = is_array($submit);
  865. if (isset($path)) {
  866. $this->drupalGet($path, $options);
  867. }
  868. if ($this->parse()) {
  869. $edit_save = $edit;
  870. // Let's iterate over all the forms.
  871. $xpath = "//form";
  872. if (!empty($form_html_id)) {
  873. $xpath .= "[@id='" . $form_html_id . "']";
  874. }
  875. $forms = $this->xpath($xpath);
  876. foreach ($forms as $form) {
  877. // We try to set the fields of this form as specified in $edit.
  878. $edit = $edit_save;
  879. $post = [];
  880. $upload = [];
  881. $submit_matches = $this->handleForm($post, $edit, $upload, $ajax ? NULL : $submit, $form);
  882. $action = isset($form['action']) ? $this->getAbsoluteUrl((string) $form['action']) : $this->getUrl();
  883. if ($ajax) {
  884. if (empty($submit['path'])) {
  885. throw new \Exception('No #ajax path specified.');
  886. }
  887. $action = $this->getAbsoluteUrl($submit['path']);
  888. // Ajax callbacks verify the triggering element if necessary, so while
  889. // we may eventually want extra code that verifies it in the
  890. // handleForm() function, it's not currently a requirement.
  891. $submit_matches = TRUE;
  892. }
  893. // We post only if we managed to handle every field in edit and the
  894. // submit button matches.
  895. if (!$edit && ($submit_matches || !isset($submit))) {
  896. $post_array = $post;
  897. if ($upload) {
  898. foreach ($upload as $key => $file) {
  899. if (is_array($file) && count($file)) {
  900. // There seems to be no way via php's API to cURL to upload
  901. // several files with the same post field name. However, Drupal
  902. // still sees array-index syntax in a similar way.
  903. for ($i = 0; $i < count($file); $i++) {
  904. $postfield = str_replace('[]', '', $key) . '[' . $i . ']';
  905. $file_path = $this->container->get('file_system')->realpath($file[$i]);
  906. $post[$postfield] = curl_file_create($file_path);
  907. }
  908. }
  909. else {
  910. $file = $this->container->get('file_system')->realpath($file);
  911. if ($file && is_file($file)) {
  912. $post[$key] = curl_file_create($file);
  913. }
  914. }
  915. }
  916. }
  917. else {
  918. $post = $this->serializePostValues($post) . $extra_post;
  919. }
  920. $out = $this->curlExec([CURLOPT_URL => $action, CURLOPT_POST => TRUE, CURLOPT_POSTFIELDS => $post, CURLOPT_HTTPHEADER => $headers]);
  921. // Ensure that any changes to variables in the other thread are picked
  922. // up.
  923. $this->refreshVariables();
  924. // Replace original page output with new output from redirected
  925. // page(s).
  926. if ($new = $this->checkForMetaRefresh()) {
  927. $out = $new;
  928. }
  929. if ($path instanceof Url) {
  930. $path = $path->toString();
  931. }
  932. $verbose = 'POST request to: ' . $path;
  933. $verbose .= '<hr />Ending URL: ' . $this->getUrl();
  934. if ($this->dumpHeaders) {
  935. $verbose .= '<hr />Headers: <pre>' . Html::escape(var_export(array_map('trim', $this->headers), TRUE)) . '</pre>';
  936. }
  937. $verbose .= '<hr />Fields: ' . highlight_string('<?php ' . var_export($post_array, TRUE), TRUE);
  938. $verbose .= '<hr />' . $out;
  939. $this->verbose($verbose);
  940. return $out;
  941. }
  942. }
  943. // We have not found a form which contained all fields of $edit.
  944. foreach ($edit as $name => $value) {
  945. $this->fail(SafeMarkup::format('Failed to set field @name to @value', ['@name' => $name, '@value' => $value]));
  946. }
  947. if (!$ajax && isset($submit)) {
  948. $this->assertTrue($submit_matches, format_string('Found the @submit button', ['@submit' => $submit]));
  949. }
  950. $this->fail(format_string('Found the requested form fields at @path', ['@path' => ($path instanceof Url) ? $path->toString() : $path]));
  951. }
  952. }
  953. /**
  954. * Executes an Ajax form submission.
  955. *
  956. * This executes a POST as ajax.js does. The returned JSON data is used to
  957. * update $this->content via drupalProcessAjaxResponse(). It also returns
  958. * the array of AJAX commands received.
  959. *
  960. * @param \Drupal\Core\Url|string $path
  961. * Location of the form containing the Ajax enabled element to test. Can be
  962. * either a Drupal path or an absolute path or NULL to use the current page.
  963. * @param $edit
  964. * Field data in an associative array. Changes the current input fields
  965. * (where possible) to the values indicated.
  966. * @param $triggering_element
  967. * The name of the form element that is responsible for triggering the Ajax
  968. * functionality to test. May be a string or, if the triggering element is
  969. * a button, an associative array where the key is the name of the button
  970. * and the value is the button label. i.e.) array('op' => t('Refresh')).
  971. * @param $ajax_path
  972. * (optional) Override the path set by the Ajax settings of the triggering
  973. * element.
  974. * @param $options
  975. * (optional) Options to be forwarded to the url generator.
  976. * @param $headers
  977. * (optional) An array containing additional HTTP request headers, each
  978. * formatted as "name: value". Forwarded to drupalPostForm().
  979. * @param $form_html_id
  980. * (optional) HTML ID of the form to be submitted, use when there is more
  981. * than one identical form on the same page and the value of the triggering
  982. * element is not enough to identify the form. Note this is not the Drupal
  983. * ID of the form but rather the HTML ID of the form.
  984. * @param $ajax_settings
  985. * (optional) An array of Ajax settings which if specified will be used in
  986. * place of the Ajax settings of the triggering element.
  987. *
  988. * @return
  989. * An array of Ajax commands.
  990. *
  991. * @see drupalPostForm()
  992. * @see drupalProcessAjaxResponse()
  993. * @see ajax.js
  994. */
  995. protected function drupalPostAjaxForm($path, $edit, $triggering_element, $ajax_path = NULL, array $options = [], array $headers = [], $form_html_id = NULL, $ajax_settings = NULL) {
  996. // Get the content of the initial page prior to calling drupalPostForm(),
  997. // since drupalPostForm() replaces $this->content.
  998. if (isset($path)) {
  999. // Avoid sending the wrapper query argument to drupalGet so we can fetch
  1000. // the form and populate the internal WebTest values.
  1001. $get_options = $options;
  1002. unset($get_options['query'][MainContentViewSubscriber::WRAPPER_FORMAT]);
  1003. $this->drupalGet($path, $get_options);
  1004. }
  1005. $content = $this->content;
  1006. $drupal_settings = $this->drupalSettings;
  1007. // Provide a default value for the wrapper envelope.
  1008. $options['query'][MainContentViewSubscriber::WRAPPER_FORMAT] =
  1009. isset($options['query'][MainContentViewSubscriber::WRAPPER_FORMAT]) ?
  1010. $options['query'][MainContentViewSubscriber::WRAPPER_FORMAT] :
  1011. 'drupal_ajax';
  1012. // Get the Ajax settings bound to the triggering element.
  1013. if (!isset($ajax_settings)) {
  1014. if (is_array($triggering_element)) {
  1015. $xpath = '//*[@name="' . key($triggering_element) . '" and @value="' . current($triggering_element) . '"]';
  1016. }
  1017. else {
  1018. $xpath = '//*[@name="' . $triggering_element . '"]';
  1019. }
  1020. if (isset($form_html_id)) {
  1021. $xpath = '//form[@id="' . $form_html_id . '"]' . $xpath;
  1022. }
  1023. $element = $this->xpath($xpath);
  1024. $element_id = (string) $element[0]['id'];
  1025. $ajax_settings = $drupal_settings['ajax'][$element_id];
  1026. }
  1027. // Add extra information to the POST data as ajax.js does.
  1028. $extra_post = [];
  1029. if (isset($ajax_settings['submit'])) {
  1030. foreach ($ajax_settings['submit'] as $key => $value) {
  1031. $extra_post[$key] = $value;
  1032. }
  1033. }
  1034. $extra_post[AjaxResponseSubscriber::AJAX_REQUEST_PARAMETER] = 1;
  1035. $extra_post += $this->getAjaxPageStatePostData();
  1036. // Now serialize all the $extra_post values, and prepend it with an '&'.
  1037. $extra_post = '&' . $this->serializePostValues($extra_post);
  1038. // Unless a particular path is specified, use the one specified by the
  1039. // Ajax settings.
  1040. if (!isset($ajax_path)) {
  1041. if (isset($ajax_settings['url'])) {
  1042. // In order to allow to set for example the wrapper envelope query
  1043. // parameter we need to get the system path again.
  1044. $parsed_url = UrlHelper::parse($ajax_settings['url']);
  1045. $options['query'] = $parsed_url['query'] + $options['query'];
  1046. $options += ['fragment' => $parsed_url['fragment']];
  1047. // We know that $parsed_url['path'] is already with the base path
  1048. // attached.
  1049. $ajax_path = preg_replace(
  1050. '/^' . preg_quote(base_path(), '/') . '/',
  1051. '',
  1052. $parsed_url['path']
  1053. );
  1054. }
  1055. }
  1056. if (empty($ajax_path)) {
  1057. throw new \Exception('No #ajax path specified.');
  1058. }
  1059. $ajax_path = $this->container->get('unrouted_url_assembler')->assemble('base://' . $ajax_path, $options);
  1060. // Submit the POST request.
  1061. $return = Json::decode($this->drupalPostForm(NULL, $edit, ['path' => $ajax_path, 'triggering_element' => $triggering_element], $options, $headers, $form_html_id, $extra_post));
  1062. if ($this->assertAjaxHeader) {
  1063. $this->assertIdentical($this->drupalGetHeader('X-Drupal-Ajax-Token'), '1', 'Ajax response header found.');
  1064. }
  1065. // Change the page content by applying the returned commands.
  1066. if (!empty($ajax_settings) && !empty($return)) {
  1067. $this->drupalProcessAjaxResponse($content, $return, $ajax_settings, $drupal_settings);
  1068. }
  1069. $verbose = 'AJAX POST request to: ' . $path;
  1070. $verbose .= '<br />AJAX controller path: ' . $ajax_path;
  1071. $verbose .= '<hr />Ending URL: ' . $this->getUrl();
  1072. $verbose .= '<hr />' . $this->content;
  1073. $this->verbose($verbose);
  1074. return $return;
  1075. }
  1076. /**
  1077. * Processes an AJAX response into current content.
  1078. *
  1079. * This processes the AJAX response as ajax.js does. It uses the response's
  1080. * JSON data, an array of commands, to update $this->content using equivalent
  1081. * DOM manipulation as is used by ajax.js.
  1082. * It does not apply custom AJAX commands though, because emulation is only
  1083. * implemented for the AJAX commands that ship with Drupal core.
  1084. *
  1085. * @param string $content
  1086. * The current HTML content.
  1087. * @param array $ajax_response
  1088. * An array of AJAX commands.
  1089. * @param array $ajax_settings
  1090. * An array of AJAX settings which will be used to process the response.
  1091. * @param array $drupal_settings
  1092. * An array of settings to update the value of drupalSettings for the
  1093. * currently-loaded page.
  1094. *
  1095. * @see drupalPostAjaxForm()
  1096. * @see ajax.js
  1097. */
  1098. protected function drupalProcessAjaxResponse($content, array $ajax_response, array $ajax_settings, array $drupal_settings) {
  1099. // ajax.js applies some defaults to the settings object, so do the same
  1100. // for what's used by this function.
  1101. $ajax_settings += [
  1102. 'method' => 'replaceWith',
  1103. ];
  1104. // DOM can load HTML soup. But, HTML soup can throw warnings, suppress
  1105. // them.
  1106. $dom = new \DOMDocument();
  1107. @$dom->loadHTML($content);
  1108. // XPath allows for finding wrapper nodes better than DOM does.
  1109. $xpath = new \DOMXPath($dom);
  1110. foreach ($ajax_response as $command) {
  1111. // Error messages might be not commands.
  1112. if (!is_array($command)) {
  1113. continue;
  1114. }
  1115. switch ($command['command']) {
  1116. case 'settings':
  1117. $drupal_settings = NestedArray::mergeDeepArray([$drupal_settings, $command['settings']], TRUE);
  1118. break;
  1119. case 'insert':
  1120. $wrapperNode = NULL;
  1121. // When a command doesn't specify a selector, use the
  1122. // #ajax['wrapper'] which is always an HTML ID.
  1123. if (!isset($command['selector'])) {
  1124. $wrapperNode = $xpath->query('//*[@id="' . $ajax_settings['wrapper'] . '"]')->item(0);
  1125. }
  1126. // @todo Ajax commands can target any jQuery selector, but these are
  1127. // hard to fully emulate with XPath. For now, just handle 'head'
  1128. // and 'body', since these are used by the Ajax renderer.
  1129. elseif (in_array($command['selector'], ['head', 'body'])) {
  1130. $wrapperNode = $xpath->query('//' . $command['selector'])->item(0);
  1131. }
  1132. if ($wrapperNode) {
  1133. // ajax.js adds an enclosing DIV to work around a Safari bug.
  1134. $newDom = new \DOMDocument();
  1135. // DOM can load HTML soup. But, HTML soup can throw warnings,
  1136. // suppress them.
  1137. @$newDom->loadHTML('<div>' . $command['data'] . '</div>');
  1138. // Suppress warnings thrown when duplicate HTML IDs are encountered.
  1139. // This probably means we are replacing an element with the same ID.
  1140. $newNode = @$dom->importNode($newDom->documentElement->firstChild->firstChild, TRUE);
  1141. $method = isset($command['method']) ? $command['method'] : $ajax_settings['method'];
  1142. // The "method" is a jQuery DOM manipulation function. Emulate
  1143. // each one using PHP's DOMNode API.
  1144. switch ($method) {
  1145. case 'replaceWith':
  1146. $wrapperNode->parentNode->replaceChild($newNode, $wrapperNode);
  1147. break;
  1148. case 'append':
  1149. $wrapperNode->appendChild($newNode);
  1150. break;
  1151. case 'prepend':
  1152. // If no firstChild, insertBefore() falls back to
  1153. // appendChild().
  1154. $wrapperNode->insertBefore($newNode, $wrapperNode->firstChild);
  1155. break;
  1156. case 'before':
  1157. $wrapperNode->parentNode->insertBefore($newNode, $wrapperNode);
  1158. break;
  1159. case 'after':
  1160. // If no nextSibling, insertBefore() falls back to
  1161. // appendChild().
  1162. $wrapperNode->parentNode->insertBefore($newNode, $wrapperNode->nextSibling);
  1163. break;
  1164. case 'html':
  1165. foreach ($wrapperNode->childNodes as $childNode) {
  1166. $wrapperNode->removeChild($childNode);
  1167. }
  1168. $wrapperNode->appendChild($newNode);
  1169. break;
  1170. }
  1171. }
  1172. break;
  1173. // @todo Add suitable implementations for these commands in order to
  1174. // have full test coverage of what ajax.js can do.
  1175. case 'remove':
  1176. break;
  1177. case 'changed':
  1178. break;
  1179. case 'css':
  1180. break;
  1181. case 'data':
  1182. break;
  1183. case 'restripe':
  1184. break;
  1185. case 'add_css':
  1186. break;
  1187. case 'update_build_id':
  1188. $buildId = $xpath->query('//input[@name="form_build_id" and @value="' . $command['old'] . '"]')->item(0);
  1189. if ($buildId) {
  1190. $buildId->setAttribute('value', $command['new']);
  1191. }
  1192. break;
  1193. }
  1194. }
  1195. $content = $dom->saveHTML();
  1196. $this->setRawContent($content);
  1197. $this->setDrupalSettings($drupal_settings);
  1198. }
  1199. /**
  1200. * Perform a POST HTTP request.
  1201. *
  1202. * @param string|\Drupal\Core\Url $path
  1203. * Drupal path or absolute path where the request should be POSTed.
  1204. * @param string $accept
  1205. * The value for the "Accept" header. Usually either 'application/json' or
  1206. * 'application/vnd.drupal-ajax'.
  1207. * @param array $post
  1208. * The POST data. When making a 'application/vnd.drupal-ajax' request, the
  1209. * Ajax page state data should be included. Use getAjaxPageStatePostData()
  1210. * for that.
  1211. * @param array $options
  1212. * (optional) Options to be forwarded to the url generator. The 'absolute'
  1213. * option will automatically be enabled.
  1214. *
  1215. * @return
  1216. * The content returned from the call to curl_exec().
  1217. *
  1218. * @see WebTestBase::getAjaxPageStatePostData()
  1219. * @see WebTestBase::curlExec()
  1220. */
  1221. protected function drupalPost($path, $accept, array $post, $options = []) {
  1222. return $this->curlExec([
  1223. CURLOPT_URL => $this->buildUrl($path, $options),
  1224. CURLOPT_POST => TRUE,
  1225. CURLOPT_POSTFIELDS => $this->serializePostValues($post),
  1226. CURLOPT_HTTPHEADER => [
  1227. 'Accept: ' . $accept,
  1228. 'Content-Type: application/x-www-form-urlencoded',
  1229. ],
  1230. ]);
  1231. }
  1232. /**
  1233. * Performs a POST HTTP request with a specific format.
  1234. *
  1235. * @param string|\Drupal\Core\Url $path
  1236. * Drupal path or absolute path where the request should be POSTed.
  1237. * @param string $format
  1238. * The request format.
  1239. * @param array $post
  1240. * The POST data. When making a 'application/vnd.drupal-ajax' request, the
  1241. * Ajax page state data should be included. Use getAjaxPageStatePostData()
  1242. * for that.
  1243. * @param array $options
  1244. * (optional) Options to be forwarded to the url generator. The 'absolute'
  1245. * option will automatically be enabled.
  1246. *
  1247. * @return string
  1248. * The content returned from the call to curl_exec().
  1249. *
  1250. * @see WebTestBase::drupalPost
  1251. * @see WebTestBase::getAjaxPageStatePostData()
  1252. * @see WebTestBase::curlExec()
  1253. */
  1254. protected function drupalPostWithFormat($path, $format, array $post, $options = []) {
  1255. $options['query']['_format'] = $format;
  1256. return $this->drupalPost($path, '', $post, $options);
  1257. }
  1258. /**
  1259. * Get the Ajax page state from drupalSettings and prepare it for POSTing.
  1260. *
  1261. * @return array
  1262. * The Ajax page state POST data.
  1263. */
  1264. protected function getAjaxPageStatePostData() {
  1265. $post = [];
  1266. $drupal_settings = $this->drupalSettings;
  1267. if (isset($drupal_settings['ajaxPageState']['theme'])) {
  1268. $post['ajax_page_state[theme]'] = $drupal_settings['ajaxPageState']['theme'];
  1269. }
  1270. if (isset($drupal_settings['ajaxPageState']['theme_token'])) {
  1271. $post['ajax_page_state[theme_token]'] = $drupal_settings['ajaxPageState']['theme_token'];
  1272. }
  1273. if (isset($drupal_settings['ajaxPageState']['libraries'])) {
  1274. $post['ajax_page_state[libraries]'] = $drupal_settings['ajaxPageState']['libraries'];
  1275. }
  1276. return $post;
  1277. }
  1278. /**
  1279. * Serialize POST HTTP request values.
  1280. *
  1281. * Encode according to application/x-www-form-urlencoded. Both names and
  1282. * values needs to be urlencoded, according to
  1283. * http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.1
  1284. *
  1285. * @param array $post
  1286. * The array of values to be POSTed.
  1287. *
  1288. * @return string
  1289. * The serialized result.
  1290. */
  1291. protected function serializePostValues($post = []) {
  1292. foreach ($post as $key => $value) {
  1293. $post[$key] = urlencode($key) . '=' . urlencode($value);
  1294. }
  1295. return implode('&', $post);
  1296. }
  1297. /**
  1298. * Transforms a nested array into a flat array suitable for WebTestBase::drupalPostForm().
  1299. *
  1300. * @param array $values
  1301. * A multi-dimensional form values array to convert.
  1302. *
  1303. * @return array
  1304. * The flattened $edit array suitable for WebTestBase::drupalPostForm().
  1305. */
  1306. protected function translatePostValues(array $values) {
  1307. $edit = [];
  1308. // The easiest and most straightforward way to translate values suitable for
  1309. // WebTestBase::drupalPostForm() is to actually build the POST data string
  1310. // and convert the resulting key/value pairs back into a flat array.
  1311. $query = http_build_query($values);
  1312. foreach (explode('&', $query) as $item) {
  1313. list($key, $value) = explode('=', $item);
  1314. $edit[urldecode($key)] = urldecode($value);
  1315. }
  1316. return $edit;
  1317. }
  1318. /**
  1319. * Checks for meta refresh tag and if found call drupalGet() recursively.
  1320. *
  1321. * This function looks for the http-equiv attribute to be set to "Refresh" and
  1322. * is case-sensitive.
  1323. *
  1324. * @return
  1325. * Either the new page content or FALSE.
  1326. */
  1327. protected function checkForMetaRefresh() {
  1328. if (strpos($this->getRawContent(), '<meta ') && $this->parse() && (!isset($this->maximumMetaRefreshCount) || $this->metaRefreshCount < $this->maximumMetaRefreshCount)) {
  1329. $refresh = $this->xpath('//meta[@http-equiv="Refresh"]');
  1330. if (!empty($refresh)) {
  1331. // Parse the content attribute of the meta tag for the format:
  1332. // "[delay]: URL=[page_to_redirect_to]".
  1333. if (preg_match('/\d+;\s*URL=(?<url>.*)/i', $refresh[0]['content'], $match)) {
  1334. $this->metaRefreshCount++;
  1335. return $this->drupalGet($this->getAbsoluteUrl(Html::decodeEntities($match['url'])));
  1336. }
  1337. }
  1338. }
  1339. return FALSE;
  1340. }
  1341. /**
  1342. * Retrieves only the headers for a Drupal path or an absolute path.
  1343. *
  1344. * @param $path
  1345. * Drupal path or URL to load into internal browser
  1346. * @param $options
  1347. * Options to be forwarded to the url generator.
  1348. * @param $headers
  1349. * An array containing additional HTTP request headers, each formatted as
  1350. * "name: value".
  1351. *
  1352. * @return
  1353. * The retrieved headers, also available as $this->getRawContent()
  1354. */
  1355. protected function drupalHead($path, array $options = [], array $headers = []) {
  1356. $options['absolute'] = TRUE;
  1357. $url = $this->buildUrl($path, $options);
  1358. $out = $this->curlExec([CURLOPT_NOBODY => TRUE, CURLOPT_URL => $url, CURLOPT_HTTPHEADER => $headers]);
  1359. // Ensure that any changes to variables in the other thread are picked up.
  1360. $this->refreshVariables();
  1361. if ($this->dumpHeaders) {
  1362. $this->verbose('GET request to: ' . $path .
  1363. '<hr />Ending URL: ' . $this->getUrl() .
  1364. '<hr />Headers: <pre>' . Html::escape(var_export(array_map('trim', $this->headers), TRUE)) . '</pre>');
  1365. }
  1366. return $out;
  1367. }
  1368. /**
  1369. * Handles form input related to drupalPostForm().
  1370. *
  1371. * Ensure that the specified fields exist and attempt to create POST data in
  1372. * the correct manner for the particular field type.
  1373. *
  1374. * @param $post
  1375. * Reference to array of post values.
  1376. * @param $edit
  1377. * Reference to array of edit values to be checked against the form.
  1378. * @param $submit
  1379. * Form submit button value.
  1380. * @param $form
  1381. * Array of form elements.
  1382. *
  1383. * @return
  1384. * Submit value matches a valid submit input in the form.
  1385. */
  1386. protected function handleForm(&$post, &$edit, &$upload, $submit, $form) {
  1387. // Retrieve the form elements.
  1388. $elements = $form->xpath('.//input[not(@disabled)]|.//textarea[not(@disabled)]|.//select[not(@disabled)]');
  1389. $submit_matches = FALSE;
  1390. foreach ($elements as $element) {
  1391. // SimpleXML objects need string casting all the time.
  1392. $name = (string) $element['name'];
  1393. // This can either be the type of <input> or the name of the tag itself
  1394. // for <select> or <textarea>.
  1395. $type = isset($element['type']) ? (string) $element['type'] : $element->getName();
  1396. $value = isset($element['value']) ? (string) $element['value'] : '';
  1397. $done = FALSE;
  1398. if (isset($edit[$name])) {
  1399. switch ($type) {
  1400. case 'text':
  1401. case 'tel':
  1402. case 'textarea':
  1403. case 'url':
  1404. case 'number':
  1405. case 'range':
  1406. case 'color':
  1407. case 'hidden':
  1408. case 'password':
  1409. case 'email':
  1410. case 'search':
  1411. case 'date':
  1412. case 'time':
  1413. case 'datetime':
  1414. case 'datetime-local';
  1415. $post[$name] = $edit[$name];
  1416. unset($edit[$name]);
  1417. break;
  1418. case 'radio':
  1419. if ($edit[$name] == $value) {
  1420. $post[$name] = $edit[$name];
  1421. unset($edit[$name]);
  1422. }
  1423. break;
  1424. case 'checkbox':
  1425. // To prevent checkbox from being checked.pass in a FALSE,
  1426. // otherwise the checkbox will be set to its value regardless
  1427. // of $edit.
  1428. if ($edit[$name] === FALSE) {
  1429. unset($edit[$name]);
  1430. continue 2;
  1431. }
  1432. else {
  1433. unset($edit[$name]);
  1434. $post[$name] = $value;
  1435. }
  1436. break;
  1437. case 'select':
  1438. $new_value = $edit[$name];
  1439. $options = $this->getAllOptions($element);
  1440. if (is_array($new_value)) {
  1441. // Multiple select box.
  1442. if (!empty($new_value)) {
  1443. $index = 0;
  1444. $key = preg_replace('/\[\]$/', '', $name);
  1445. foreach ($options as $option) {
  1446. $option_value = (string) $option['value'];
  1447. if (in_array($option_value, $new_value)) {
  1448. $post[$key . '[' . $index++ . ']'] = $option_value;
  1449. $done = TRUE;
  1450. unset($edit[$name]);
  1451. }
  1452. }
  1453. }
  1454. else {
  1455. // No options selected: do not include any POST data for the
  1456. // element.
  1457. $done = TRUE;
  1458. unset($edit[$name]);
  1459. }
  1460. }
  1461. else {
  1462. // Single select box.
  1463. foreach ($options as $option) {
  1464. if ($new_value == $option['value']) {
  1465. $post[$name] = $new_value;
  1466. unset($edit[$name]);
  1467. $done = TRUE;
  1468. break;
  1469. }
  1470. }
  1471. }
  1472. break;
  1473. case 'file':
  1474. $upload[$name] = $edit[$name];
  1475. unset($edit[$name]);
  1476. break;
  1477. }
  1478. }
  1479. if (!isset($post[$name]) && !$done) {
  1480. switch ($type) {
  1481. case 'textarea':
  1482. $post[$name] = (string) $element;
  1483. break;
  1484. case 'select':
  1485. $single = empty($element['multiple']);
  1486. $first = TRUE;
  1487. $index = 0;
  1488. $key = preg_replace('/\[\]$/', '', $name);
  1489. $options = $this->getAllOptions($element);
  1490. foreach ($options as $option) {
  1491. // For single select, we load the first option, if there is a
  1492. // selected option that will overwrite it later.
  1493. if ($option['selected'] || ($first && $single)) {
  1494. $first = FALSE;
  1495. if ($single) {
  1496. $post[$name] = (string) $option['value'];
  1497. }
  1498. else {
  1499. $post[$key . '[' . $index++ . ']'] = (string) $option['value'];
  1500. }
  1501. }
  1502. }
  1503. break;
  1504. case 'file':
  1505. break;
  1506. case 'submit':
  1507. case 'image':
  1508. if (isset($submit) && $submit == $value) {
  1509. $post[$name] = $value;
  1510. $submit_matches = TRUE;
  1511. }
  1512. break;
  1513. case 'radio':
  1514. case 'checkbox':
  1515. if (!isset($element['checked'])) {
  1516. break;
  1517. }
  1518. // Deliberate no break.
  1519. default:
  1520. $post[$name] = $value;
  1521. }
  1522. }
  1523. }
  1524. // An empty name means the value is not sent.
  1525. unset($post['']);
  1526. return $submit_matches;
  1527. }
  1528. /**
  1529. * Follows a link by complete name.
  1530. *
  1531. * Will click the first link found with this link text by default, or a later
  1532. * one if an index is given. Match is case sensitive with normalized space.
  1533. * The label is translated label.
  1534. *
  1535. * If the link is discovered and clicked, the test passes. Fail otherwise.
  1536. *
  1537. * @param string|\Drupal\Component\Render\MarkupInterface $label
  1538. * Text between the anchor tags.
  1539. * @param int $index
  1540. * Link position counting from zero.
  1541. *
  1542. * @return string|bool
  1543. * Page contents on success, or FALSE on failure.
  1544. */
  1545. protected function clickLink($label, $index = 0) {
  1546. return $this->clickLinkHelper($label, $index, '//a[normalize-space()=:label]');
  1547. }
  1548. /**
  1549. * Follows a link by partial name.
  1550. *
  1551. * If the link is discovered and clicked, the test passes. Fail otherwise.
  1552. *
  1553. * @param string|\Drupal\Component\Render\MarkupInterface $label
  1554. * Text between the anchor tags, uses starts-with().
  1555. * @param int $index
  1556. * Link position counting from zero.
  1557. *
  1558. * @return string|bool
  1559. * Page contents on success, or FALSE on failure.
  1560. *
  1561. * @see ::clickLink()
  1562. */
  1563. protected function clickLinkPartialName($label, $index = 0) {
  1564. return $this->clickLinkHelper($label, $index, '//a[starts-with(normalize-space(), :label)]');
  1565. }
  1566. /**
  1567. * Provides a helper for ::clickLink() and ::clickLinkPartialName().
  1568. *
  1569. * @param string|\Drupal\Component\Render\MarkupInterface $label
  1570. * Text between the anchor tags, uses starts-with().
  1571. * @param int $index
  1572. * Link position counting from zero.
  1573. * @param string $pattern
  1574. * A pattern to use for the XPath.
  1575. *
  1576. * @return bool|string
  1577. * Page contents on success, or FALSE on failure.
  1578. */
  1579. protected function clickLinkHelper($label, $index, $pattern) {
  1580. // Cast MarkupInterface objects to string.
  1581. $label = (string) $label;
  1582. $url_before = $this->getUrl();
  1583. $urls = $this->xpath($pattern, [':label' => $label]);
  1584. if (isset($urls[$index])) {
  1585. $url_target = $this->getAbsoluteUrl($urls[$index]['href']);
  1586. $this->pass(SafeMarkup::format('Clicked link %label (@url_target) from @url_before', ['%label' => $label, '@url_target' => $url_target, '@url_before' => $url_before]), 'Browser');
  1587. return $this->drupalGet($url_target);
  1588. }
  1589. $this->fail(SafeMarkup::format('Link %label does not exist on @url_before', ['%label' => $label, '@url_before' => $url_before]), 'Browser');
  1590. return FALSE;
  1591. }
  1592. /**
  1593. * Takes a path and returns an absolute path.
  1594. *
  1595. * This method is implemented in the way that browsers work, see
  1596. * https://url.spec.whatwg.org/#relative-state for more information about the
  1597. * possible cases.
  1598. *
  1599. * @param string $path
  1600. * A path from the internal browser content.
  1601. *
  1602. * @return string
  1603. * The $path with $base_url prepended, if necessary.
  1604. */
  1605. protected function getAbsoluteUrl($path) {
  1606. global $base_url, $base_path;
  1607. $parts = parse_url($path);
  1608. // In case the $path has a host, it is already an absolute URL and we are
  1609. // done.
  1610. if (!empty($parts['host'])) {
  1611. return $path;
  1612. }
  1613. // In case the $path contains just a query, we turn it into an absolute URL
  1614. // with the same scheme, host and path, see
  1615. // https://url.spec.whatwg.org/#relative-state.
  1616. if (array_keys($parts) === ['query']) {
  1617. $current_uri = new Uri($this->getUrl());
  1618. return (string) $current_uri->withQuery($parts['query']);
  1619. }
  1620. if (empty($parts['host'])) {
  1621. // Ensure that we have a string (and no xpath object).
  1622. $path = (string) $path;
  1623. // Strip $base_path, if existent.
  1624. $length = strlen($base_path);
  1625. if (substr($path, 0, $length) === $base_path) {
  1626. $path = substr($path, $length);
  1627. }
  1628. // Ensure that we have an absolute path.
  1629. if (empty($path) || $path[0] !== '/') {
  1630. $path = '/' . $path;
  1631. }
  1632. // Finally, prepend the $base_url.
  1633. $path = $base_url . $path;
  1634. }
  1635. return $path;
  1636. }
  1637. /**
  1638. * Gets the HTTP response headers of the requested page.
  1639. *
  1640. * Normally we are only interested in the headers returned by the last
  1641. * request. However, if a page is redirected or HTTP authentication is in use,
  1642. * multiple requests will be required to retrieve the page. Headers from all
  1643. * requests may be requested by passing TRUE to this function.
  1644. *
  1645. * @param $all_requests
  1646. * Boolean value specifying whether to return headers from all requests
  1647. * instead of just the last request. Defaults to FALSE.
  1648. *
  1649. * @return
  1650. * A name/value array if headers from only the last request are requested.
  1651. * If headers from all requests are requested, an array of name/value
  1652. * arrays, one for each request.
  1653. *
  1654. * The pseudonym ":status" is used for the HTTP status line.
  1655. *
  1656. * Values for duplicate headers are stored as a single comma-separated list.
  1657. */
  1658. protected function drupalGetHeaders($all_requests = FALSE) {
  1659. $request = 0;
  1660. $headers = [$request => []];
  1661. foreach ($this->headers as $header) {
  1662. $header = trim($header);
  1663. if ($header === '') {
  1664. $request++;
  1665. }
  1666. else {
  1667. if (strpos($header, 'HTTP/') === 0) {
  1668. $name = ':status';
  1669. $value = $header;
  1670. }
  1671. else {
  1672. list($name, $value) = explode(':', $header, 2);
  1673. $name = strtolower($name);
  1674. }
  1675. if (isset($headers[$request][$name])) {
  1676. $headers[$request][$name] .= ',' . trim($value);
  1677. }
  1678. else {
  1679. $headers[$request][$name] = trim($value);
  1680. }
  1681. }
  1682. }
  1683. if (!$all_requests) {
  1684. $headers = array_pop($headers);
  1685. }
  1686. return $headers;
  1687. }
  1688. /**
  1689. * Gets the value of an HTTP response header.
  1690. *
  1691. * If multiple requests were required to retrieve the page, only the headers
  1692. * from the last request will be checked by default. However, if TRUE is
  1693. * passed as the second argument, all requests will be processed from last to
  1694. * first until the header is found.
  1695. *
  1696. * @param $name
  1697. * The name of the header to retrieve. Names are case-insensitive (see RFC
  1698. * 2616 section 4.2).
  1699. * @param $all_requests
  1700. * Boolean value specifying whether to check all requests if the header is
  1701. * not found in the last request. Defaults to FALSE.
  1702. *
  1703. * @return
  1704. * The HTTP header value or FALSE if not found.
  1705. */
  1706. protected function drupalGetHeader($name, $all_requests = FALSE) {
  1707. $name = strtolower($name);
  1708. $header = FALSE;
  1709. if ($all_requests) {
  1710. foreach (array_reverse($this->drupalGetHeaders(TRUE)) as $headers) {
  1711. if (isset($headers[$name])) {
  1712. $header = $headers[$name];
  1713. break;
  1714. }
  1715. }
  1716. }
  1717. else {
  1718. $headers = $this->drupalGetHeaders();
  1719. if (isset($headers[$name])) {
  1720. $header = $headers[$name];
  1721. }
  1722. }
  1723. return $header;
  1724. }
  1725. /**
  1726. * Check if a HTTP response header exists and has the expected value.
  1727. *
  1728. * @param string $header
  1729. * The header key, example: Content-Type
  1730. * @param string $value
  1731. * The header value.
  1732. * @param string $message
  1733. * (optional) A message to display with the assertion.
  1734. * @param string $group
  1735. * (optional) The group this message is in, which is displayed in a column
  1736. * in test output. Use 'Debug' to indicate this is debugging output. Do not
  1737. * translate this string. Defaults to 'Other'; most tests do not override
  1738. * this default.
  1739. *
  1740. * @return bool
  1741. * TRUE if the assertion succeeded, FALSE otherwise.
  1742. */
  1743. protected function assertHeader($header, $value, $message = '', $group = 'Browser') {
  1744. $header_value = $this->drupalGetHeader($header);
  1745. return $this->assertTrue($header_value == $value, $message ? $message : 'HTTP response header ' . $header . ' with value ' . $value . ' found, actual value: ' . $header_value, $group);
  1746. }
  1747. /**
  1748. * Passes if the internal browser's URL matches the given path.
  1749. *
  1750. * @param \Drupal\Core\Url|string $path
  1751. * The expected system path or URL.
  1752. * @param $options
  1753. * (optional) Any additional options to pass for $path to the url generator.
  1754. * @param $message
  1755. * (optional) A message to display with the assertion. Do not translate
  1756. * messages: use \Drupal\Component\Utility\SafeMarkup::format() to embed
  1757. * variables in the message text, not t(). If left blank, a default message
  1758. * will be displayed.
  1759. * @param $group
  1760. * (optional) The group this message is in, which is displayed in a column
  1761. * in test output. Use 'Debug' to indicate this is debugging output. Do not
  1762. * translate this string. Defaults to 'Other'; most tests do not override
  1763. * this default.
  1764. *
  1765. * @return
  1766. * TRUE on pass, FALSE on fail.
  1767. */
  1768. protected function assertUrl($path, array $options = [], $message = '', $group = 'Other') {
  1769. if ($path instanceof Url) {
  1770. $url_obj = $path;
  1771. }
  1772. elseif (UrlHelper::isExternal($path)) {
  1773. $url_obj = Url::fromUri($path, $options);
  1774. }
  1775. else {
  1776. $uri = $path === '<front>' ? 'base:/' : 'base:/' . $path;
  1777. // This is needed for language prefixing.
  1778. $options['path_processing'] = TRUE;
  1779. $url_obj = Url::fromUri($uri, $options);
  1780. }
  1781. $url = $url_obj->setAbsolute()->toString();
  1782. if (!$message) {
  1783. $message = SafeMarkup::format('Expected @url matches current URL (@current_url).', [
  1784. '@url' => var_export($url, TRUE),
  1785. '@current_url' => $this->getUrl(),
  1786. ]);
  1787. }
  1788. // Paths in query strings can be encoded or decoded with no functional
  1789. // difference, decode them for comparison purposes.
  1790. $actual_url = urldecode($this->getUrl());
  1791. $expected_url = urldecode($url);
  1792. return $this->assertEqual($actual_url, $expected_url, $message, $group);
  1793. }
  1794. /**
  1795. * Asserts the page responds with the specified response code.
  1796. *
  1797. * @param $code
  1798. * Response code. For example 200 is a successful page request. For a list
  1799. * of all codes see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html.
  1800. * @param $message
  1801. * (optional) A message to display with the assertion. Do not translate
  1802. * messages: use \Drupal\Component\Utility\SafeMarkup::format() to embed
  1803. * variables in the message text, not t(). If left blank, a default message
  1804. * will be displayed.
  1805. * @param $group
  1806. * (optional) The group this message is in, which is displayed in a column
  1807. * in test output. Use 'Debug' to indicate this is debugging output. Do not
  1808. * translate this string. Defaults to 'Browser'; most tests do not override
  1809. * this default.
  1810. *
  1811. * @return
  1812. * Assertion result.
  1813. */
  1814. protected function assertResponse($code, $message = '', $group = 'Browser') {
  1815. $curl_code = curl_getinfo($this->curlHandle, CURLINFO_HTTP_CODE);
  1816. $match = is_array($code) ? in_array($curl_code, $code) : $curl_code == $code;
  1817. return $this->assertTrue($match, $message ? $message : SafeMarkup::format('HTTP response expected @code, actual @curl_code', ['@code' => $code, '@curl_code' => $curl_code]), $group);
  1818. }
  1819. /**
  1820. * Asserts the page did not return the specified response code.
  1821. *
  1822. * @param $code
  1823. * Response code. For example 200 is a successful page request. For a list
  1824. * of all codes see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html.
  1825. * @param $message
  1826. * (optional) A message to display with the assertion. Do not translate
  1827. * messages: use \Drupal\Component\Utility\SafeMarkup::format() to embed
  1828. * variables in the message text, not t(). If left blank, a default message
  1829. * will be displayed.
  1830. * @param $group
  1831. * (optional) The group this message is in, which is displayed in a column
  1832. * in test output. Use 'Debug' to indicate this is debugging output. Do not
  1833. * translate this string. Defaults to 'Browser'; most tests do not override
  1834. * this default.
  1835. *
  1836. * @return
  1837. * Assertion result.
  1838. */
  1839. protected function assertNoResponse($code, $message = '', $group = 'Browser') {
  1840. $curl_code = curl_getinfo($this->curlHandle, CURLINFO_HTTP_CODE);
  1841. $match = is_array($code) ? in_array($curl_code, $code) : $curl_code == $code;
  1842. return $this->assertFalse($match, $message ? $message : SafeMarkup::format('HTTP response not expected @code, actual @curl_code', ['@code' => $code, '@curl_code' => $curl_code]), $group);
  1843. }
  1844. /**
  1845. * Builds an a absolute URL from a system path or a URL object.
  1846. *
  1847. * @param string|\Drupal\Core\Url $path
  1848. * A system path or a URL.
  1849. * @param array $options
  1850. * Options to be passed to Url::fromUri().
  1851. *
  1852. * @return string
  1853. * An absolute URL string.
  1854. */
  1855. protected function buildUrl($path, array $options = []) {
  1856. if ($path instanceof Url) {
  1857. $url_options = $path->getOptions();
  1858. $options = $url_options + $options;
  1859. $path->setOptions($options);
  1860. return $path->setAbsolute()->toString(TRUE)->getGeneratedUrl();
  1861. }
  1862. // The URL generator service is not necessarily available yet; e.g., in
  1863. // interactive installer tests.
  1864. elseif ($this->container->has('url_generator')) {
  1865. $force_internal = isset($options['external']) && $options['external'] == FALSE;
  1866. if (!$force_internal && UrlHelper::isExternal($path)) {
  1867. return Url::fromUri($path, $options)->toString();
  1868. }
  1869. else {
  1870. $uri = $path === '<front>' ? 'base:/' : 'base:/' . $path;
  1871. // Path processing is needed for language prefixing. Skip it when a
  1872. // path that may look like an external URL is being used as internal.
  1873. $options['path_processing'] = !$force_internal;
  1874. return Url::fromUri($uri, $options)
  1875. ->setAbsolute()
  1876. ->toString();
  1877. }
  1878. }
  1879. else {
  1880. return $this->getAbsoluteUrl($path);
  1881. }
  1882. }
  1883. /**
  1884. * Asserts whether an expected cache tag was present in the last response.
  1885. *
  1886. * @param string $expected_cache_tag
  1887. * The expected cache tag.
  1888. */
  1889. protected function assertCacheTag($expected_cache_tag) {
  1890. $cache_tags = explode(' ', $this->drupalGetHeader('X-Drupal-Cache-Tags'));
  1891. $this->assertTrue(in_array($expected_cache_tag, $cache_tags), "'" . $expected_cache_tag . "' is present in the X-Drupal-Cache-Tags header.");
  1892. }
  1893. /**
  1894. * Asserts whether an expected cache tag was absent in the last response.
  1895. *
  1896. * @param string $cache_tag
  1897. * The cache tag to check.
  1898. */
  1899. protected function assertNoCacheTag($cache_tag) {
  1900. $cache_tags = explode(' ', $this->drupalGetHeader('X-Drupal-Cache-Tags'));
  1901. $this->assertFalse(in_array($cache_tag, $cache_tags), "'" . $cache_tag . "' is absent in the X-Drupal-Cache-Tags header.");
  1902. }
  1903. /**
  1904. * Enables/disables the cacheability headers.
  1905. *
  1906. * Sets the http.response.debug_cacheability_headers container parameter.
  1907. *
  1908. * @param bool $value
  1909. * (optional) Whether the debugging cacheability headers should be sent.
  1910. */
  1911. protected function setHttpResponseDebugCacheabilityHeaders($value = TRUE) {
  1912. $this->setContainerParameter('http.response.debug_cacheability_headers', $value);
  1913. $this->rebuildContainer();
  1914. $this->resetAll();
  1915. }
  1916. }