WebTestBase.php 74 KB

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