WebTestBase.php 73 KB

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