WebTestBase.php 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075
  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\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 as BaseContentTypeCreationTrait;
  21. use Drupal\Tests\node\Traits\NodeCreationTrait as BaseNodeCreationTrait;
  22. use Drupal\Tests\Traits\Core\CronRunTrait;
  23. use Drupal\Tests\TestFileCreationTrait;
  24. use Drupal\Tests\user\Traits\UserCreationTrait as BaseUserCreationTrait;
  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 BaseContentTypeCreationTrait {
  44. createContentType as drupalCreateContentType;
  45. }
  46. use CronRunTrait;
  47. use AssertMailTrait {
  48. getMails as drupalGetMails;
  49. }
  50. use BaseNodeCreationTrait {
  51. getNodeByTitle as drupalGetNodeByTitle;
  52. createNode as drupalCreateNode;
  53. }
  54. use BaseUserCreationTrait {
  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 = new FormattableMarkup('@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. $test_info = TestDiscovery::getTestInfo(get_called_class());
  623. if ($test_info['group'] !== 'legacy' && !in_array($message, DeprecationListenerTrait::getSkippedDeprecations())) {
  624. call_user_func_array([&$this, 'error'], $parameters);
  625. }
  626. }
  627. }
  628. else {
  629. // Call \Drupal\simpletest\WebTestBase::error() with the parameters from
  630. // the header.
  631. call_user_func_array([&$this, 'error'], $parameters);
  632. }
  633. }
  634. // Save cookies.
  635. if (preg_match('/^Set-Cookie: ([^=]+)=(.+)/', $header, $matches)) {
  636. $name = $matches[1];
  637. $parts = array_map('trim', explode(';', $matches[2]));
  638. $value = array_shift($parts);
  639. $this->cookies[$name] = ['value' => $value, 'secure' => in_array('secure', $parts)];
  640. if ($name === $this->getSessionName()) {
  641. if ($value != 'deleted') {
  642. $this->sessionId = $value;
  643. }
  644. else {
  645. $this->sessionId = NULL;
  646. }
  647. }
  648. }
  649. // This is required by cURL.
  650. return strlen($header);
  651. }
  652. /**
  653. * Close the cURL handler and unset the handler.
  654. */
  655. protected function curlClose() {
  656. if (isset($this->curlHandle)) {
  657. curl_close($this->curlHandle);
  658. unset($this->curlHandle);
  659. }
  660. }
  661. /**
  662. * Returns whether the test is being executed from within a test site.
  663. *
  664. * Mainly used by recursive tests (i.e. to test the testing framework).
  665. *
  666. * @return bool
  667. * TRUE if this test was instantiated in a request within the test site,
  668. * FALSE otherwise.
  669. *
  670. * @see \Drupal\Core\DrupalKernel::bootConfiguration()
  671. */
  672. protected function isInChildSite() {
  673. return DRUPAL_TEST_IN_CHILD_SITE;
  674. }
  675. /**
  676. * Retrieves a Drupal path or an absolute path.
  677. *
  678. * @param \Drupal\Core\Url|string $path
  679. * Drupal path or URL to load into internal browser
  680. * @param $options
  681. * Options to be forwarded to the url generator.
  682. * @param $headers
  683. * An array containing additional HTTP request headers, each formatted as
  684. * "name: value".
  685. *
  686. * @return string
  687. * The retrieved HTML string, also available as $this->getRawContent()
  688. */
  689. protected function drupalGet($path, array $options = [], array $headers = []) {
  690. // We re-using a CURL connection here. If that connection still has certain
  691. // options set, it might change the GET into a POST. Make sure we clear out
  692. // previous options.
  693. $out = $this->curlExec([CURLOPT_HTTPGET => TRUE, CURLOPT_URL => $this->buildUrl($path, $options), CURLOPT_NOBODY => FALSE, CURLOPT_HTTPHEADER => $headers]);
  694. // Ensure that any changes to variables in the other thread are picked up.
  695. $this->refreshVariables();
  696. // Replace original page output with new output from redirected page(s).
  697. if ($new = $this->checkForMetaRefresh()) {
  698. $out = $new;
  699. // We are finished with all meta refresh redirects, so reset the counter.
  700. $this->metaRefreshCount = 0;
  701. }
  702. if ($path instanceof Url) {
  703. $path = $path->setAbsolute()->toString(TRUE)->getGeneratedUrl();
  704. }
  705. $verbose = 'GET request to: ' . $path .
  706. '<hr />Ending URL: ' . $this->getUrl();
  707. if ($this->dumpHeaders) {
  708. $verbose .= '<hr />Headers: <pre>' . Html::escape(var_export(array_map('trim', $this->headers), TRUE)) . '</pre>';
  709. }
  710. $verbose .= '<hr />' . $out;
  711. $this->verbose($verbose);
  712. return $out;
  713. }
  714. /**
  715. * Retrieves a Drupal path or an absolute path and JSON decodes the result.
  716. *
  717. * @param \Drupal\Core\Url|string $path
  718. * Drupal path or URL to request AJAX from.
  719. * @param array $options
  720. * Array of URL options.
  721. * @param array $headers
  722. * Array of headers. Eg array('Accept: application/vnd.drupal-ajax').
  723. *
  724. * @return array
  725. * Decoded json.
  726. */
  727. protected function drupalGetJSON($path, array $options = [], array $headers = []) {
  728. return Json::decode($this->drupalGetWithFormat($path, 'json', $options, $headers));
  729. }
  730. /**
  731. * Retrieves a Drupal path or an absolute path for a given format.
  732. *
  733. * @param \Drupal\Core\Url|string $path
  734. * Drupal path or URL to request given format from.
  735. * @param string $format
  736. * The wanted request format.
  737. * @param array $options
  738. * Array of URL options.
  739. * @param array $headers
  740. * Array of headers.
  741. *
  742. * @return mixed
  743. * The result of the request.
  744. */
  745. protected function drupalGetWithFormat($path, $format, array $options = [], array $headers = []) {
  746. $options = array_merge_recursive(['query' => ['_format' => $format]], $options);
  747. return $this->drupalGet($path, $options, $headers);
  748. }
  749. /**
  750. * Requests a path or URL in drupal_ajax format and JSON-decodes the response.
  751. *
  752. * @param \Drupal\Core\Url|string $path
  753. * Drupal path or URL to request from.
  754. * @param array $options
  755. * Array of URL options.
  756. * @param array $headers
  757. * Array of headers.
  758. *
  759. * @return array
  760. * Decoded JSON.
  761. */
  762. protected function drupalGetAjax($path, array $options = [], array $headers = []) {
  763. if (!isset($options['query'][MainContentViewSubscriber::WRAPPER_FORMAT])) {
  764. $options['query'][MainContentViewSubscriber::WRAPPER_FORMAT] = 'drupal_ajax';
  765. }
  766. return Json::decode($this->drupalGetXHR($path, $options, $headers));
  767. }
  768. /**
  769. * Requests a Drupal path or an absolute path as if it is a XMLHttpRequest.
  770. *
  771. * @param \Drupal\Core\Url|string $path
  772. * Drupal path or URL to request from.
  773. * @param array $options
  774. * Array of URL options.
  775. * @param array $headers
  776. * Array of headers.
  777. *
  778. * @return string
  779. * The retrieved content.
  780. */
  781. protected function drupalGetXHR($path, array $options = [], array $headers = []) {
  782. $headers[] = 'X-Requested-With: XMLHttpRequest';
  783. return $this->drupalGet($path, $options, $headers);
  784. }
  785. /**
  786. * Executes a form submission.
  787. *
  788. * It will be done as usual POST request with SimpleBrowser.
  789. *
  790. * @param \Drupal\Core\Url|string $path
  791. * Location of the post form. Either a Drupal path or an absolute path or
  792. * NULL to post to the current page. For multi-stage forms you can set the
  793. * path to NULL and have it post to the last received page. Example:
  794. *
  795. * @code
  796. * // First step in form.
  797. * $edit = array(...);
  798. * $this->drupalPostForm('some_url', $edit, t('Save'));
  799. *
  800. * // Second step in form.
  801. * $edit = array(...);
  802. * $this->drupalPostForm(NULL, $edit, t('Save'));
  803. * @endcode
  804. * @param $edit
  805. * Field data in an associative array. Changes the current input fields
  806. * (where possible) to the values indicated.
  807. *
  808. * When working with form tests, the keys for an $edit element should match
  809. * the 'name' parameter of the HTML of the form. For example, the 'body'
  810. * field for a node has the following HTML:
  811. * @code
  812. * <textarea id="edit-body-und-0-value" class="text-full form-textarea
  813. * resize-vertical" placeholder="" cols="60" rows="9"
  814. * name="body[0][value]"></textarea>
  815. * @endcode
  816. * When testing this field using an $edit parameter, the code becomes:
  817. * @code
  818. * $edit["body[0][value]"] = 'My test value';
  819. * @endcode
  820. *
  821. * A checkbox can be set to TRUE to be checked and should be set to FALSE to
  822. * be unchecked. Multiple select fields can be tested using 'name[]' and
  823. * setting each of the desired values in an array:
  824. * @code
  825. * $edit = array();
  826. * $edit['name[]'] = array('value1', 'value2');
  827. * @endcode
  828. * @param $submit
  829. * Value of the submit button whose click is to be emulated. For example,
  830. * t('Save'). The processing of the request depends on this value. For
  831. * example, a form may have one button with the value t('Save') and another
  832. * button with the value t('Delete'), and execute different code depending
  833. * on which one is clicked.
  834. *
  835. * This function can also be called to emulate an Ajax submission. In this
  836. * case, this value needs to be an array with the following keys:
  837. * - path: A path to submit the form values to for Ajax-specific processing.
  838. * - triggering_element: If the value for the 'path' key is a generic Ajax
  839. * processing path, this needs to be set to the name of the element. If
  840. * the name doesn't identify the element uniquely, then this should
  841. * instead be an array with a single key/value pair, corresponding to the
  842. * element name and value. The \Drupal\Core\Form\FormAjaxResponseBuilder
  843. * uses this to find the #ajax information for the element, including
  844. * which specific callback to use for processing the request.
  845. *
  846. * This can also be set to NULL in order to emulate an Internet Explorer
  847. * submission of a form with a single text field, and pressing ENTER in that
  848. * textfield: under these conditions, no button information is added to the
  849. * POST data.
  850. * @param $options
  851. * Options to be forwarded to the url generator.
  852. * @param $headers
  853. * An array containing additional HTTP request headers, each formatted as
  854. * "name: value".
  855. * @param $form_html_id
  856. * (optional) HTML ID of the form to be submitted. On some pages
  857. * there are many identical forms, so just using the value of the submit
  858. * button is not enough. For example: 'trigger-node-presave-assign-form'.
  859. * Note that this is not the Drupal $form_id, but rather the HTML ID of the
  860. * form, which is typically the same thing but with hyphens replacing the
  861. * underscores.
  862. * @param $extra_post
  863. * (optional) A string of additional data to append to the POST submission.
  864. * This can be used to add POST data for which there are no HTML fields, as
  865. * is done by drupalPostAjaxForm(). This string is literally appended to the
  866. * POST data, so it must already be urlencoded and contain a leading "&"
  867. * (e.g., "&extra_var1=hello+world&extra_var2=you%26me").
  868. */
  869. protected function drupalPostForm($path, $edit, $submit, array $options = [], array $headers = [], $form_html_id = NULL, $extra_post = NULL) {
  870. if (is_object($submit)) {
  871. // Cast MarkupInterface objects to string.
  872. $submit = (string) $submit;
  873. }
  874. if (is_array($edit)) {
  875. $edit = $this->castSafeStrings($edit);
  876. }
  877. $submit_matches = FALSE;
  878. $ajax = is_array($submit);
  879. if (isset($path)) {
  880. $this->drupalGet($path, $options);
  881. }
  882. if ($this->parse()) {
  883. $edit_save = $edit;
  884. // Let's iterate over all the forms.
  885. $xpath = "//form";
  886. if (!empty($form_html_id)) {
  887. $xpath .= "[@id='" . $form_html_id . "']";
  888. }
  889. $forms = $this->xpath($xpath);
  890. foreach ($forms as $form) {
  891. // We try to set the fields of this form as specified in $edit.
  892. $edit = $edit_save;
  893. $post = [];
  894. $upload = [];
  895. $submit_matches = $this->handleForm($post, $edit, $upload, $ajax ? NULL : $submit, $form);
  896. $action = isset($form['action']) ? $this->getAbsoluteUrl((string) $form['action']) : $this->getUrl();
  897. if ($ajax) {
  898. if (empty($submit['path'])) {
  899. throw new \Exception('No #ajax path specified.');
  900. }
  901. $action = $this->getAbsoluteUrl($submit['path']);
  902. // Ajax callbacks verify the triggering element if necessary, so while
  903. // we may eventually want extra code that verifies it in the
  904. // handleForm() function, it's not currently a requirement.
  905. $submit_matches = TRUE;
  906. }
  907. // We post only if we managed to handle every field in edit and the
  908. // submit button matches.
  909. if (!$edit && ($submit_matches || !isset($submit))) {
  910. $post_array = $post;
  911. if ($upload) {
  912. foreach ($upload as $key => $file) {
  913. if (is_array($file) && count($file)) {
  914. // There seems to be no way via php's API to cURL to upload
  915. // several files with the same post field name. However, Drupal
  916. // still sees array-index syntax in a similar way.
  917. for ($i = 0; $i < count($file); $i++) {
  918. $postfield = str_replace('[]', '', $key) . '[' . $i . ']';
  919. $file_path = $this->container->get('file_system')->realpath($file[$i]);
  920. $post[$postfield] = curl_file_create($file_path);
  921. }
  922. }
  923. else {
  924. $file = $this->container->get('file_system')->realpath($file);
  925. if ($file && is_file($file)) {
  926. $post[$key] = curl_file_create($file);
  927. }
  928. }
  929. }
  930. }
  931. else {
  932. $post = $this->serializePostValues($post) . $extra_post;
  933. }
  934. $out = $this->curlExec([CURLOPT_URL => $action, CURLOPT_POST => TRUE, CURLOPT_POSTFIELDS => $post, CURLOPT_HTTPHEADER => $headers]);
  935. // Ensure that any changes to variables in the other thread are picked
  936. // up.
  937. $this->refreshVariables();
  938. // Replace original page output with new output from redirected
  939. // page(s).
  940. if ($new = $this->checkForMetaRefresh()) {
  941. $out = $new;
  942. }
  943. if ($path instanceof Url) {
  944. $path = $path->toString();
  945. }
  946. $verbose = 'POST request to: ' . $path;
  947. $verbose .= '<hr />Ending URL: ' . $this->getUrl();
  948. if ($this->dumpHeaders) {
  949. $verbose .= '<hr />Headers: <pre>' . Html::escape(var_export(array_map('trim', $this->headers), TRUE)) . '</pre>';
  950. }
  951. $verbose .= '<hr />Fields: ' . highlight_string('<?php ' . var_export($post_array, TRUE), TRUE);
  952. $verbose .= '<hr />' . $out;
  953. $this->verbose($verbose);
  954. return $out;
  955. }
  956. }
  957. // We have not found a form which contained all fields of $edit.
  958. foreach ($edit as $name => $value) {
  959. $this->fail(new FormattableMarkup('Failed to set field @name to @value', ['@name' => $name, '@value' => $value]));
  960. }
  961. if (!$ajax && isset($submit)) {
  962. $this->assertTrue($submit_matches, format_string('Found the @submit button', ['@submit' => $submit]));
  963. }
  964. $this->fail(format_string('Found the requested form fields at @path', ['@path' => ($path instanceof Url) ? $path->toString() : $path]));
  965. }
  966. }
  967. /**
  968. * Executes an Ajax form submission.
  969. *
  970. * This executes a POST as ajax.js does. The returned JSON data is used to
  971. * update $this->content via drupalProcessAjaxResponse(). It also returns
  972. * the array of AJAX commands received.
  973. *
  974. * @param \Drupal\Core\Url|string $path
  975. * Location of the form containing the Ajax enabled element to test. Can be
  976. * either a Drupal path or an absolute path or NULL to use the current page.
  977. * @param $edit
  978. * Field data in an associative array. Changes the current input fields
  979. * (where possible) to the values indicated.
  980. * @param $triggering_element
  981. * The name of the form element that is responsible for triggering the Ajax
  982. * functionality to test. May be a string or, if the triggering element is
  983. * a button, an associative array where the key is the name of the button
  984. * and the value is the button label. i.e.) array('op' => t('Refresh')).
  985. * @param $ajax_path
  986. * (optional) Override the path set by the Ajax settings of the triggering
  987. * element.
  988. * @param $options
  989. * (optional) Options to be forwarded to the url generator.
  990. * @param $headers
  991. * (optional) An array containing additional HTTP request headers, each
  992. * formatted as "name: value". Forwarded to drupalPostForm().
  993. * @param $form_html_id
  994. * (optional) HTML ID of the form to be submitted, use when there is more
  995. * than one identical form on the same page and the value of the triggering
  996. * element is not enough to identify the form. Note this is not the Drupal
  997. * ID of the form but rather the HTML ID of the form.
  998. * @param $ajax_settings
  999. * (optional) An array of Ajax settings which if specified will be used in
  1000. * place of the Ajax settings of the triggering element.
  1001. *
  1002. * @return
  1003. * An array of Ajax commands.
  1004. *
  1005. * @see drupalPostForm()
  1006. * @see drupalProcessAjaxResponse()
  1007. * @see ajax.js
  1008. */
  1009. protected function drupalPostAjaxForm($path, $edit, $triggering_element, $ajax_path = NULL, array $options = [], array $headers = [], $form_html_id = NULL, $ajax_settings = NULL) {
  1010. // Get the content of the initial page prior to calling drupalPostForm(),
  1011. // since drupalPostForm() replaces $this->content.
  1012. if (isset($path)) {
  1013. // Avoid sending the wrapper query argument to drupalGet so we can fetch
  1014. // the form and populate the internal WebTest values.
  1015. $get_options = $options;
  1016. unset($get_options['query'][MainContentViewSubscriber::WRAPPER_FORMAT]);
  1017. $this->drupalGet($path, $get_options);
  1018. }
  1019. $content = $this->content;
  1020. $drupal_settings = $this->drupalSettings;
  1021. // Provide a default value for the wrapper envelope.
  1022. $options['query'][MainContentViewSubscriber::WRAPPER_FORMAT] =
  1023. isset($options['query'][MainContentViewSubscriber::WRAPPER_FORMAT]) ?
  1024. $options['query'][MainContentViewSubscriber::WRAPPER_FORMAT] :
  1025. 'drupal_ajax';
  1026. // Get the Ajax settings bound to the triggering element.
  1027. if (!isset($ajax_settings)) {
  1028. if (is_array($triggering_element)) {
  1029. $xpath = '//*[@name="' . key($triggering_element) . '" and @value="' . current($triggering_element) . '"]';
  1030. }
  1031. else {
  1032. $xpath = '//*[@name="' . $triggering_element . '"]';
  1033. }
  1034. if (isset($form_html_id)) {
  1035. $xpath = '//form[@id="' . $form_html_id . '"]' . $xpath;
  1036. }
  1037. $element = $this->xpath($xpath);
  1038. $element_id = (string) $element[0]['id'];
  1039. $ajax_settings = $drupal_settings['ajax'][$element_id];
  1040. }
  1041. // Add extra information to the POST data as ajax.js does.
  1042. $extra_post = [];
  1043. if (isset($ajax_settings['submit'])) {
  1044. foreach ($ajax_settings['submit'] as $key => $value) {
  1045. $extra_post[$key] = $value;
  1046. }
  1047. }
  1048. $extra_post[AjaxResponseSubscriber::AJAX_REQUEST_PARAMETER] = 1;
  1049. $extra_post += $this->getAjaxPageStatePostData();
  1050. // Now serialize all the $extra_post values, and prepend it with an '&'.
  1051. $extra_post = '&' . $this->serializePostValues($extra_post);
  1052. // Unless a particular path is specified, use the one specified by the
  1053. // Ajax settings.
  1054. if (!isset($ajax_path)) {
  1055. if (isset($ajax_settings['url'])) {
  1056. // In order to allow to set for example the wrapper envelope query
  1057. // parameter we need to get the system path again.
  1058. $parsed_url = UrlHelper::parse($ajax_settings['url']);
  1059. $options['query'] = $parsed_url['query'] + $options['query'];
  1060. $options += ['fragment' => $parsed_url['fragment']];
  1061. // We know that $parsed_url['path'] is already with the base path
  1062. // attached.
  1063. $ajax_path = preg_replace(
  1064. '/^' . preg_quote(base_path(), '/') . '/',
  1065. '',
  1066. $parsed_url['path']
  1067. );
  1068. }
  1069. }
  1070. if (empty($ajax_path)) {
  1071. throw new \Exception('No #ajax path specified.');
  1072. }
  1073. $ajax_path = $this->container->get('unrouted_url_assembler')->assemble('base://' . $ajax_path, $options);
  1074. // Submit the POST request.
  1075. $return = Json::decode($this->drupalPostForm(NULL, $edit, ['path' => $ajax_path, 'triggering_element' => $triggering_element], $options, $headers, $form_html_id, $extra_post));
  1076. if ($this->assertAjaxHeader) {
  1077. $this->assertIdentical($this->drupalGetHeader('X-Drupal-Ajax-Token'), '1', 'Ajax response header found.');
  1078. }
  1079. // Change the page content by applying the returned commands.
  1080. if (!empty($ajax_settings) && !empty($return)) {
  1081. $this->drupalProcessAjaxResponse($content, $return, $ajax_settings, $drupal_settings);
  1082. }
  1083. $verbose = 'AJAX POST request to: ' . $path;
  1084. $verbose .= '<br />AJAX controller path: ' . $ajax_path;
  1085. $verbose .= '<hr />Ending URL: ' . $this->getUrl();
  1086. $verbose .= '<hr />' . $this->content;
  1087. $this->verbose($verbose);
  1088. return $return;
  1089. }
  1090. /**
  1091. * Processes an AJAX response into current content.
  1092. *
  1093. * This processes the AJAX response as ajax.js does. It uses the response's
  1094. * JSON data, an array of commands, to update $this->content using equivalent
  1095. * DOM manipulation as is used by ajax.js.
  1096. * It does not apply custom AJAX commands though, because emulation is only
  1097. * implemented for the AJAX commands that ship with Drupal core.
  1098. *
  1099. * @param string $content
  1100. * The current HTML content.
  1101. * @param array $ajax_response
  1102. * An array of AJAX commands.
  1103. * @param array $ajax_settings
  1104. * An array of AJAX settings which will be used to process the response.
  1105. * @param array $drupal_settings
  1106. * An array of settings to update the value of drupalSettings for the
  1107. * currently-loaded page.
  1108. *
  1109. * @see drupalPostAjaxForm()
  1110. * @see ajax.js
  1111. */
  1112. protected function drupalProcessAjaxResponse($content, array $ajax_response, array $ajax_settings, array $drupal_settings) {
  1113. // ajax.js applies some defaults to the settings object, so do the same
  1114. // for what's used by this function.
  1115. $ajax_settings += [
  1116. 'method' => 'replaceWith',
  1117. ];
  1118. // DOM can load HTML soup. But, HTML soup can throw warnings, suppress
  1119. // them.
  1120. $dom = new \DOMDocument();
  1121. @$dom->loadHTML($content);
  1122. // XPath allows for finding wrapper nodes better than DOM does.
  1123. $xpath = new \DOMXPath($dom);
  1124. foreach ($ajax_response as $command) {
  1125. // Error messages might be not commands.
  1126. if (!is_array($command)) {
  1127. continue;
  1128. }
  1129. switch ($command['command']) {
  1130. case 'settings':
  1131. $drupal_settings = NestedArray::mergeDeepArray([$drupal_settings, $command['settings']], TRUE);
  1132. break;
  1133. case 'insert':
  1134. $wrapperNode = NULL;
  1135. // When a command doesn't specify a selector, use the
  1136. // #ajax['wrapper'] which is always an HTML ID.
  1137. if (!isset($command['selector'])) {
  1138. $wrapperNode = $xpath->query('//*[@id="' . $ajax_settings['wrapper'] . '"]')->item(0);
  1139. }
  1140. // @todo Ajax commands can target any jQuery selector, but these are
  1141. // hard to fully emulate with XPath. For now, just handle 'head'
  1142. // and 'body', since these are used by the Ajax renderer.
  1143. elseif (in_array($command['selector'], ['head', 'body'])) {
  1144. $wrapperNode = $xpath->query('//' . $command['selector'])->item(0);
  1145. }
  1146. if ($wrapperNode) {
  1147. // ajax.js adds an enclosing DIV to work around a Safari bug.
  1148. $newDom = new \DOMDocument();
  1149. // DOM can load HTML soup. But, HTML soup can throw warnings,
  1150. // suppress them.
  1151. @$newDom->loadHTML('<div>' . $command['data'] . '</div>');
  1152. // Suppress warnings thrown when duplicate HTML IDs are encountered.
  1153. // This probably means we are replacing an element with the same ID.
  1154. $newNode = @$dom->importNode($newDom->documentElement->firstChild->firstChild, TRUE);
  1155. $method = isset($command['method']) ? $command['method'] : $ajax_settings['method'];
  1156. // The "method" is a jQuery DOM manipulation function. Emulate
  1157. // each one using PHP's DOMNode API.
  1158. switch ($method) {
  1159. case 'replaceWith':
  1160. $wrapperNode->parentNode->replaceChild($newNode, $wrapperNode);
  1161. break;
  1162. case 'append':
  1163. $wrapperNode->appendChild($newNode);
  1164. break;
  1165. case 'prepend':
  1166. // If no firstChild, insertBefore() falls back to
  1167. // appendChild().
  1168. $wrapperNode->insertBefore($newNode, $wrapperNode->firstChild);
  1169. break;
  1170. case 'before':
  1171. $wrapperNode->parentNode->insertBefore($newNode, $wrapperNode);
  1172. break;
  1173. case 'after':
  1174. // If no nextSibling, insertBefore() falls back to
  1175. // appendChild().
  1176. $wrapperNode->parentNode->insertBefore($newNode, $wrapperNode->nextSibling);
  1177. break;
  1178. case 'html':
  1179. foreach ($wrapperNode->childNodes as $childNode) {
  1180. $wrapperNode->removeChild($childNode);
  1181. }
  1182. $wrapperNode->appendChild($newNode);
  1183. break;
  1184. }
  1185. }
  1186. break;
  1187. // @todo Add suitable implementations for these commands in order to
  1188. // have full test coverage of what ajax.js can do.
  1189. case 'remove':
  1190. break;
  1191. case 'changed':
  1192. break;
  1193. case 'css':
  1194. break;
  1195. case 'data':
  1196. break;
  1197. case 'restripe':
  1198. break;
  1199. case 'add_css':
  1200. break;
  1201. case 'update_build_id':
  1202. $buildId = $xpath->query('//input[@name="form_build_id" and @value="' . $command['old'] . '"]')->item(0);
  1203. if ($buildId) {
  1204. $buildId->setAttribute('value', $command['new']);
  1205. }
  1206. break;
  1207. }
  1208. }
  1209. $content = $dom->saveHTML();
  1210. $this->setRawContent($content);
  1211. $this->setDrupalSettings($drupal_settings);
  1212. }
  1213. /**
  1214. * Perform a POST HTTP request.
  1215. *
  1216. * @param string|\Drupal\Core\Url $path
  1217. * Drupal path or absolute path where the request should be POSTed.
  1218. * @param string $accept
  1219. * The value for the "Accept" header. Usually either 'application/json' or
  1220. * 'application/vnd.drupal-ajax'.
  1221. * @param array $post
  1222. * The POST data. When making a 'application/vnd.drupal-ajax' request, the
  1223. * Ajax page state data should be included. Use getAjaxPageStatePostData()
  1224. * for that.
  1225. * @param array $options
  1226. * (optional) Options to be forwarded to the url generator. The 'absolute'
  1227. * option will automatically be enabled.
  1228. *
  1229. * @return
  1230. * The content returned from the call to curl_exec().
  1231. *
  1232. * @see WebTestBase::getAjaxPageStatePostData()
  1233. * @see WebTestBase::curlExec()
  1234. */
  1235. protected function drupalPost($path, $accept, array $post, $options = []) {
  1236. return $this->curlExec([
  1237. CURLOPT_URL => $this->buildUrl($path, $options),
  1238. CURLOPT_POST => TRUE,
  1239. CURLOPT_POSTFIELDS => $this->serializePostValues($post),
  1240. CURLOPT_HTTPHEADER => [
  1241. 'Accept: ' . $accept,
  1242. 'Content-Type: application/x-www-form-urlencoded',
  1243. ],
  1244. ]);
  1245. }
  1246. /**
  1247. * Performs a POST HTTP request with a specific format.
  1248. *
  1249. * @param string|\Drupal\Core\Url $path
  1250. * Drupal path or absolute path where the request should be POSTed.
  1251. * @param string $format
  1252. * The request format.
  1253. * @param array $post
  1254. * The POST data. When making a 'application/vnd.drupal-ajax' request, the
  1255. * Ajax page state data should be included. Use getAjaxPageStatePostData()
  1256. * for that.
  1257. * @param array $options
  1258. * (optional) Options to be forwarded to the url generator. The 'absolute'
  1259. * option will automatically be enabled.
  1260. *
  1261. * @return string
  1262. * The content returned from the call to curl_exec().
  1263. *
  1264. * @see WebTestBase::drupalPost
  1265. * @see WebTestBase::getAjaxPageStatePostData()
  1266. * @see WebTestBase::curlExec()
  1267. */
  1268. protected function drupalPostWithFormat($path, $format, array $post, $options = []) {
  1269. $options['query']['_format'] = $format;
  1270. return $this->drupalPost($path, '', $post, $options);
  1271. }
  1272. /**
  1273. * Get the Ajax page state from drupalSettings and prepare it for POSTing.
  1274. *
  1275. * @return array
  1276. * The Ajax page state POST data.
  1277. */
  1278. protected function getAjaxPageStatePostData() {
  1279. $post = [];
  1280. $drupal_settings = $this->drupalSettings;
  1281. if (isset($drupal_settings['ajaxPageState']['theme'])) {
  1282. $post['ajax_page_state[theme]'] = $drupal_settings['ajaxPageState']['theme'];
  1283. }
  1284. if (isset($drupal_settings['ajaxPageState']['theme_token'])) {
  1285. $post['ajax_page_state[theme_token]'] = $drupal_settings['ajaxPageState']['theme_token'];
  1286. }
  1287. if (isset($drupal_settings['ajaxPageState']['libraries'])) {
  1288. $post['ajax_page_state[libraries]'] = $drupal_settings['ajaxPageState']['libraries'];
  1289. }
  1290. return $post;
  1291. }
  1292. /**
  1293. * Serialize POST HTTP request values.
  1294. *
  1295. * Encode according to application/x-www-form-urlencoded. Both names and
  1296. * values needs to be urlencoded, according to
  1297. * http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.1
  1298. *
  1299. * @param array $post
  1300. * The array of values to be POSTed.
  1301. *
  1302. * @return string
  1303. * The serialized result.
  1304. */
  1305. protected function serializePostValues($post = []) {
  1306. foreach ($post as $key => $value) {
  1307. $post[$key] = urlencode($key) . '=' . urlencode($value);
  1308. }
  1309. return implode('&', $post);
  1310. }
  1311. /**
  1312. * Transforms a nested array into a flat array suitable for WebTestBase::drupalPostForm().
  1313. *
  1314. * @param array $values
  1315. * A multi-dimensional form values array to convert.
  1316. *
  1317. * @return array
  1318. * The flattened $edit array suitable for WebTestBase::drupalPostForm().
  1319. */
  1320. protected function translatePostValues(array $values) {
  1321. $edit = [];
  1322. // The easiest and most straightforward way to translate values suitable for
  1323. // WebTestBase::drupalPostForm() is to actually build the POST data string
  1324. // and convert the resulting key/value pairs back into a flat array.
  1325. $query = http_build_query($values);
  1326. foreach (explode('&', $query) as $item) {
  1327. list($key, $value) = explode('=', $item);
  1328. $edit[urldecode($key)] = urldecode($value);
  1329. }
  1330. return $edit;
  1331. }
  1332. /**
  1333. * Checks for meta refresh tag and if found call drupalGet() recursively.
  1334. *
  1335. * This function looks for the http-equiv attribute to be set to "Refresh" and
  1336. * is case-sensitive.
  1337. *
  1338. * @return
  1339. * Either the new page content or FALSE.
  1340. */
  1341. protected function checkForMetaRefresh() {
  1342. if (strpos($this->getRawContent(), '<meta ') && $this->parse() && (!isset($this->maximumMetaRefreshCount) || $this->metaRefreshCount < $this->maximumMetaRefreshCount)) {
  1343. $refresh = $this->xpath('//meta[@http-equiv="Refresh"]');
  1344. if (!empty($refresh)) {
  1345. // Parse the content attribute of the meta tag for the format:
  1346. // "[delay]: URL=[page_to_redirect_to]".
  1347. if (preg_match('/\d+;\s*URL=(?<url>.*)/i', $refresh[0]['content'], $match)) {
  1348. $this->metaRefreshCount++;
  1349. return $this->drupalGet($this->getAbsoluteUrl(Html::decodeEntities($match['url'])));
  1350. }
  1351. }
  1352. }
  1353. return FALSE;
  1354. }
  1355. /**
  1356. * Retrieves only the headers for a Drupal path or an absolute path.
  1357. *
  1358. * @param $path
  1359. * Drupal path or URL to load into internal browser
  1360. * @param $options
  1361. * Options to be forwarded to the url generator.
  1362. * @param $headers
  1363. * An array containing additional HTTP request headers, each formatted as
  1364. * "name: value".
  1365. *
  1366. * @return
  1367. * The retrieved headers, also available as $this->getRawContent()
  1368. */
  1369. protected function drupalHead($path, array $options = [], array $headers = []) {
  1370. $options['absolute'] = TRUE;
  1371. $url = $this->buildUrl($path, $options);
  1372. $out = $this->curlExec([CURLOPT_NOBODY => TRUE, CURLOPT_URL => $url, CURLOPT_HTTPHEADER => $headers]);
  1373. // Ensure that any changes to variables in the other thread are picked up.
  1374. $this->refreshVariables();
  1375. if ($this->dumpHeaders) {
  1376. $this->verbose('GET request to: ' . $path .
  1377. '<hr />Ending URL: ' . $this->getUrl() .
  1378. '<hr />Headers: <pre>' . Html::escape(var_export(array_map('trim', $this->headers), TRUE)) . '</pre>');
  1379. }
  1380. return $out;
  1381. }
  1382. /**
  1383. * Handles form input related to drupalPostForm().
  1384. *
  1385. * Ensure that the specified fields exist and attempt to create POST data in
  1386. * the correct manner for the particular field type.
  1387. *
  1388. * @param $post
  1389. * Reference to array of post values.
  1390. * @param $edit
  1391. * Reference to array of edit values to be checked against the form.
  1392. * @param $submit
  1393. * Form submit button value.
  1394. * @param $form
  1395. * Array of form elements.
  1396. *
  1397. * @return
  1398. * Submit value matches a valid submit input in the form.
  1399. */
  1400. protected function handleForm(&$post, &$edit, &$upload, $submit, $form) {
  1401. // Retrieve the form elements.
  1402. $elements = $form->xpath('.//input[not(@disabled)]|.//textarea[not(@disabled)]|.//select[not(@disabled)]');
  1403. $submit_matches = FALSE;
  1404. foreach ($elements as $element) {
  1405. // SimpleXML objects need string casting all the time.
  1406. $name = (string) $element['name'];
  1407. // This can either be the type of <input> or the name of the tag itself
  1408. // for <select> or <textarea>.
  1409. $type = isset($element['type']) ? (string) $element['type'] : $element->getName();
  1410. $value = isset($element['value']) ? (string) $element['value'] : '';
  1411. $done = FALSE;
  1412. if (isset($edit[$name])) {
  1413. switch ($type) {
  1414. case 'text':
  1415. case 'tel':
  1416. case 'textarea':
  1417. case 'url':
  1418. case 'number':
  1419. case 'range':
  1420. case 'color':
  1421. case 'hidden':
  1422. case 'password':
  1423. case 'email':
  1424. case 'search':
  1425. case 'date':
  1426. case 'time':
  1427. case 'datetime':
  1428. case 'datetime-local';
  1429. $post[$name] = $edit[$name];
  1430. unset($edit[$name]);
  1431. break;
  1432. case 'radio':
  1433. if ($edit[$name] == $value) {
  1434. $post[$name] = $edit[$name];
  1435. unset($edit[$name]);
  1436. }
  1437. break;
  1438. case 'checkbox':
  1439. // To prevent checkbox from being checked.pass in a FALSE,
  1440. // otherwise the checkbox will be set to its value regardless
  1441. // of $edit.
  1442. if ($edit[$name] === FALSE) {
  1443. unset($edit[$name]);
  1444. continue 2;
  1445. }
  1446. else {
  1447. unset($edit[$name]);
  1448. $post[$name] = $value;
  1449. }
  1450. break;
  1451. case 'select':
  1452. $new_value = $edit[$name];
  1453. $options = $this->getAllOptions($element);
  1454. if (is_array($new_value)) {
  1455. // Multiple select box.
  1456. if (!empty($new_value)) {
  1457. $index = 0;
  1458. $key = preg_replace('/\[\]$/', '', $name);
  1459. foreach ($options as $option) {
  1460. $option_value = (string) $option['value'];
  1461. if (in_array($option_value, $new_value)) {
  1462. $post[$key . '[' . $index++ . ']'] = $option_value;
  1463. $done = TRUE;
  1464. unset($edit[$name]);
  1465. }
  1466. }
  1467. }
  1468. else {
  1469. // No options selected: do not include any POST data for the
  1470. // element.
  1471. $done = TRUE;
  1472. unset($edit[$name]);
  1473. }
  1474. }
  1475. else {
  1476. // Single select box.
  1477. foreach ($options as $option) {
  1478. if ($new_value == $option['value']) {
  1479. $post[$name] = $new_value;
  1480. unset($edit[$name]);
  1481. $done = TRUE;
  1482. break;
  1483. }
  1484. }
  1485. }
  1486. break;
  1487. case 'file':
  1488. $upload[$name] = $edit[$name];
  1489. unset($edit[$name]);
  1490. break;
  1491. }
  1492. }
  1493. if (!isset($post[$name]) && !$done) {
  1494. switch ($type) {
  1495. case 'textarea':
  1496. $post[$name] = (string) $element;
  1497. break;
  1498. case 'select':
  1499. $single = empty($element['multiple']);
  1500. $first = TRUE;
  1501. $index = 0;
  1502. $key = preg_replace('/\[\]$/', '', $name);
  1503. $options = $this->getAllOptions($element);
  1504. foreach ($options as $option) {
  1505. // For single select, we load the first option, if there is a
  1506. // selected option that will overwrite it later.
  1507. if ($option['selected'] || ($first && $single)) {
  1508. $first = FALSE;
  1509. if ($single) {
  1510. $post[$name] = (string) $option['value'];
  1511. }
  1512. else {
  1513. $post[$key . '[' . $index++ . ']'] = (string) $option['value'];
  1514. }
  1515. }
  1516. }
  1517. break;
  1518. case 'file':
  1519. break;
  1520. case 'submit':
  1521. case 'image':
  1522. if (isset($submit) && $submit == $value) {
  1523. $post[$name] = $value;
  1524. $submit_matches = TRUE;
  1525. }
  1526. break;
  1527. case 'radio':
  1528. case 'checkbox':
  1529. if (!isset($element['checked'])) {
  1530. break;
  1531. }
  1532. // Deliberate no break.
  1533. default:
  1534. $post[$name] = $value;
  1535. }
  1536. }
  1537. }
  1538. // An empty name means the value is not sent.
  1539. unset($post['']);
  1540. return $submit_matches;
  1541. }
  1542. /**
  1543. * Follows a link by complete name.
  1544. *
  1545. * Will click the first link found with this link text by default, or a later
  1546. * one if an index is given. Match is case sensitive with normalized space.
  1547. * The label is translated label.
  1548. *
  1549. * If the link is discovered and clicked, the test passes. Fail otherwise.
  1550. *
  1551. * @param string|\Drupal\Component\Render\MarkupInterface $label
  1552. * Text between the anchor tags.
  1553. * @param int $index
  1554. * Link position counting from zero.
  1555. *
  1556. * @return string|bool
  1557. * Page contents on success, or FALSE on failure.
  1558. */
  1559. protected function clickLink($label, $index = 0) {
  1560. return $this->clickLinkHelper($label, $index, '//a[normalize-space()=:label]');
  1561. }
  1562. /**
  1563. * Follows a link by partial name.
  1564. *
  1565. * If the link is discovered and clicked, the test passes. Fail otherwise.
  1566. *
  1567. * @param string|\Drupal\Component\Render\MarkupInterface $label
  1568. * Text between the anchor tags, uses starts-with().
  1569. * @param int $index
  1570. * Link position counting from zero.
  1571. *
  1572. * @return string|bool
  1573. * Page contents on success, or FALSE on failure.
  1574. *
  1575. * @see ::clickLink()
  1576. */
  1577. protected function clickLinkPartialName($label, $index = 0) {
  1578. return $this->clickLinkHelper($label, $index, '//a[starts-with(normalize-space(), :label)]');
  1579. }
  1580. /**
  1581. * Provides a helper for ::clickLink() and ::clickLinkPartialName().
  1582. *
  1583. * @param string|\Drupal\Component\Render\MarkupInterface $label
  1584. * Text between the anchor tags, uses starts-with().
  1585. * @param int $index
  1586. * Link position counting from zero.
  1587. * @param string $pattern
  1588. * A pattern to use for the XPath.
  1589. *
  1590. * @return bool|string
  1591. * Page contents on success, or FALSE on failure.
  1592. */
  1593. protected function clickLinkHelper($label, $index, $pattern) {
  1594. // Cast MarkupInterface objects to string.
  1595. $label = (string) $label;
  1596. $url_before = $this->getUrl();
  1597. $urls = $this->xpath($pattern, [':label' => $label]);
  1598. if (isset($urls[$index])) {
  1599. $url_target = $this->getAbsoluteUrl($urls[$index]['href']);
  1600. $this->pass(new FormattableMarkup('Clicked link %label (@url_target) from @url_before', ['%label' => $label, '@url_target' => $url_target, '@url_before' => $url_before]), 'Browser');
  1601. return $this->drupalGet($url_target);
  1602. }
  1603. $this->fail(new FormattableMarkup('Link %label does not exist on @url_before', ['%label' => $label, '@url_before' => $url_before]), 'Browser');
  1604. return FALSE;
  1605. }
  1606. /**
  1607. * Takes a path and returns an absolute path.
  1608. *
  1609. * This method is implemented in the way that browsers work, see
  1610. * https://url.spec.whatwg.org/#relative-state for more information about the
  1611. * possible cases.
  1612. *
  1613. * @param string $path
  1614. * A path from the internal browser content.
  1615. *
  1616. * @return string
  1617. * The $path with $base_url prepended, if necessary.
  1618. */
  1619. protected function getAbsoluteUrl($path) {
  1620. global $base_url, $base_path;
  1621. $parts = parse_url($path);
  1622. // In case the $path has a host, it is already an absolute URL and we are
  1623. // done.
  1624. if (!empty($parts['host'])) {
  1625. return $path;
  1626. }
  1627. // In case the $path contains just a query, we turn it into an absolute URL
  1628. // with the same scheme, host and path, see
  1629. // https://url.spec.whatwg.org/#relative-state.
  1630. if (array_keys($parts) === ['query']) {
  1631. $current_uri = new Uri($this->getUrl());
  1632. return (string) $current_uri->withQuery($parts['query']);
  1633. }
  1634. if (empty($parts['host'])) {
  1635. // Ensure that we have a string (and no xpath object).
  1636. $path = (string) $path;
  1637. // Strip $base_path, if existent.
  1638. $length = strlen($base_path);
  1639. if (substr($path, 0, $length) === $base_path) {
  1640. $path = substr($path, $length);
  1641. }
  1642. // Ensure that we have an absolute path.
  1643. if (empty($path) || $path[0] !== '/') {
  1644. $path = '/' . $path;
  1645. }
  1646. // Finally, prepend the $base_url.
  1647. $path = $base_url . $path;
  1648. }
  1649. return $path;
  1650. }
  1651. /**
  1652. * Gets the HTTP response headers of the requested page.
  1653. *
  1654. * Normally we are only interested in the headers returned by the last
  1655. * request. However, if a page is redirected or HTTP authentication is in use,
  1656. * multiple requests will be required to retrieve the page. Headers from all
  1657. * requests may be requested by passing TRUE to this function.
  1658. *
  1659. * @param $all_requests
  1660. * Boolean value specifying whether to return headers from all requests
  1661. * instead of just the last request. Defaults to FALSE.
  1662. *
  1663. * @return
  1664. * A name/value array if headers from only the last request are requested.
  1665. * If headers from all requests are requested, an array of name/value
  1666. * arrays, one for each request.
  1667. *
  1668. * The pseudonym ":status" is used for the HTTP status line.
  1669. *
  1670. * Values for duplicate headers are stored as a single comma-separated list.
  1671. */
  1672. protected function drupalGetHeaders($all_requests = FALSE) {
  1673. $request = 0;
  1674. $headers = [$request => []];
  1675. foreach ($this->headers as $header) {
  1676. $header = trim($header);
  1677. if ($header === '') {
  1678. $request++;
  1679. }
  1680. else {
  1681. if (strpos($header, 'HTTP/') === 0) {
  1682. $name = ':status';
  1683. $value = $header;
  1684. }
  1685. else {
  1686. list($name, $value) = explode(':', $header, 2);
  1687. $name = strtolower($name);
  1688. }
  1689. if (isset($headers[$request][$name])) {
  1690. $headers[$request][$name] .= ',' . trim($value);
  1691. }
  1692. else {
  1693. $headers[$request][$name] = trim($value);
  1694. }
  1695. }
  1696. }
  1697. if (!$all_requests) {
  1698. $headers = array_pop($headers);
  1699. }
  1700. return $headers;
  1701. }
  1702. /**
  1703. * Gets the value of an HTTP response header.
  1704. *
  1705. * If multiple requests were required to retrieve the page, only the headers
  1706. * from the last request will be checked by default. However, if TRUE is
  1707. * passed as the second argument, all requests will be processed from last to
  1708. * first until the header is found.
  1709. *
  1710. * @param $name
  1711. * The name of the header to retrieve. Names are case-insensitive (see RFC
  1712. * 2616 section 4.2).
  1713. * @param $all_requests
  1714. * Boolean value specifying whether to check all requests if the header is
  1715. * not found in the last request. Defaults to FALSE.
  1716. *
  1717. * @return
  1718. * The HTTP header value or FALSE if not found.
  1719. */
  1720. protected function drupalGetHeader($name, $all_requests = FALSE) {
  1721. $name = strtolower($name);
  1722. $header = FALSE;
  1723. if ($all_requests) {
  1724. foreach (array_reverse($this->drupalGetHeaders(TRUE)) as $headers) {
  1725. if (isset($headers[$name])) {
  1726. $header = $headers[$name];
  1727. break;
  1728. }
  1729. }
  1730. }
  1731. else {
  1732. $headers = $this->drupalGetHeaders();
  1733. if (isset($headers[$name])) {
  1734. $header = $headers[$name];
  1735. }
  1736. }
  1737. return $header;
  1738. }
  1739. /**
  1740. * Check if a HTTP response header exists and has the expected value.
  1741. *
  1742. * @param string $header
  1743. * The header key, example: Content-Type
  1744. * @param string $value
  1745. * The header value.
  1746. * @param string $message
  1747. * (optional) A message to display with the assertion.
  1748. * @param string $group
  1749. * (optional) The group this message is in, which is displayed in a column
  1750. * in test output. Use 'Debug' to indicate this is debugging output. Do not
  1751. * translate this string. Defaults to 'Other'; most tests do not override
  1752. * this default.
  1753. *
  1754. * @return bool
  1755. * TRUE if the assertion succeeded, FALSE otherwise.
  1756. */
  1757. protected function assertHeader($header, $value, $message = '', $group = 'Browser') {
  1758. $header_value = $this->drupalGetHeader($header);
  1759. return $this->assertTrue($header_value == $value, $message ? $message : 'HTTP response header ' . $header . ' with value ' . $value . ' found, actual value: ' . $header_value, $group);
  1760. }
  1761. /**
  1762. * Passes if the internal browser's URL matches the given path.
  1763. *
  1764. * @param \Drupal\Core\Url|string $path
  1765. * The expected system path or URL.
  1766. * @param $options
  1767. * (optional) Any additional options to pass for $path to the url generator.
  1768. * @param $message
  1769. * (optional) A message to display with the assertion. Do not translate
  1770. * messages: use \Drupal\Component\Render\FormattableMarkup to embed
  1771. * variables in the message text, not t(). If left blank, a default message
  1772. * will be displayed.
  1773. * @param $group
  1774. * (optional) The group this message is in, which is displayed in a column
  1775. * in test output. Use 'Debug' to indicate this is debugging output. Do not
  1776. * translate this string. Defaults to 'Other'; most tests do not override
  1777. * this default.
  1778. *
  1779. * @return
  1780. * TRUE on pass, FALSE on fail.
  1781. */
  1782. protected function assertUrl($path, array $options = [], $message = '', $group = 'Other') {
  1783. if ($path instanceof Url) {
  1784. $url_obj = $path;
  1785. }
  1786. elseif (UrlHelper::isExternal($path)) {
  1787. $url_obj = Url::fromUri($path, $options);
  1788. }
  1789. else {
  1790. $uri = $path === '<front>' ? 'base:/' : 'base:/' . $path;
  1791. // This is needed for language prefixing.
  1792. $options['path_processing'] = TRUE;
  1793. $url_obj = Url::fromUri($uri, $options);
  1794. }
  1795. $url = $url_obj->setAbsolute()->toString();
  1796. if (!$message) {
  1797. $message = new FormattableMarkup('Expected @url matches current URL (@current_url).', [
  1798. '@url' => var_export($url, TRUE),
  1799. '@current_url' => $this->getUrl(),
  1800. ]);
  1801. }
  1802. // Paths in query strings can be encoded or decoded with no functional
  1803. // difference, decode them for comparison purposes.
  1804. $actual_url = urldecode($this->getUrl());
  1805. $expected_url = urldecode($url);
  1806. return $this->assertEqual($actual_url, $expected_url, $message, $group);
  1807. }
  1808. /**
  1809. * Asserts the page responds with the specified response code.
  1810. *
  1811. * @param $code
  1812. * Response code. For example 200 is a successful page request. For a list
  1813. * of all codes see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html.
  1814. * @param $message
  1815. * (optional) A message to display with the assertion. Do not translate
  1816. * messages: use \Drupal\Component\Render\FormattableMarkup to embed
  1817. * variables in the message text, not t(). If left blank, a default message
  1818. * will be displayed.
  1819. * @param $group
  1820. * (optional) The group this message is in, which is displayed in a column
  1821. * in test output. Use 'Debug' to indicate this is debugging output. Do not
  1822. * translate this string. Defaults to 'Browser'; most tests do not override
  1823. * this default.
  1824. *
  1825. * @return
  1826. * Assertion result.
  1827. */
  1828. protected function assertResponse($code, $message = '', $group = 'Browser') {
  1829. $curl_code = curl_getinfo($this->curlHandle, CURLINFO_HTTP_CODE);
  1830. $match = is_array($code) ? in_array($curl_code, $code) : $curl_code == $code;
  1831. return $this->assertTrue($match, $message ? $message : new FormattableMarkup('HTTP response expected @code, actual @curl_code', ['@code' => $code, '@curl_code' => $curl_code]), $group);
  1832. }
  1833. /**
  1834. * Asserts the page did not return the specified response code.
  1835. *
  1836. * @param $code
  1837. * Response code. For example 200 is a successful page request. For a list
  1838. * of all codes see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html.
  1839. * @param $message
  1840. * (optional) A message to display with the assertion. Do not translate
  1841. * messages: use \Drupal\Component\Render\FormattableMarkup to embed
  1842. * variables in the message text, not t(). If left blank, a default message
  1843. * will be displayed.
  1844. * @param $group
  1845. * (optional) The group this message is in, which is displayed in a column
  1846. * in test output. Use 'Debug' to indicate this is debugging output. Do not
  1847. * translate this string. Defaults to 'Browser'; most tests do not override
  1848. * this default.
  1849. *
  1850. * @return
  1851. * Assertion result.
  1852. */
  1853. protected function assertNoResponse($code, $message = '', $group = 'Browser') {
  1854. $curl_code = curl_getinfo($this->curlHandle, CURLINFO_HTTP_CODE);
  1855. $match = is_array($code) ? in_array($curl_code, $code) : $curl_code == $code;
  1856. return $this->assertFalse($match, $message ? $message : new FormattableMarkup('HTTP response not expected @code, actual @curl_code', ['@code' => $code, '@curl_code' => $curl_code]), $group);
  1857. }
  1858. /**
  1859. * Builds an a absolute URL from a system path or a URL object.
  1860. *
  1861. * @param string|\Drupal\Core\Url $path
  1862. * A system path or a URL.
  1863. * @param array $options
  1864. * Options to be passed to Url::fromUri().
  1865. *
  1866. * @return string
  1867. * An absolute URL string.
  1868. */
  1869. protected function buildUrl($path, array $options = []) {
  1870. if ($path instanceof Url) {
  1871. $url_options = $path->getOptions();
  1872. $options = $url_options + $options;
  1873. $path->setOptions($options);
  1874. return $path->setAbsolute()->toString(TRUE)->getGeneratedUrl();
  1875. }
  1876. // The URL generator service is not necessarily available yet; e.g., in
  1877. // interactive installer tests.
  1878. elseif ($this->container->has('url_generator')) {
  1879. $force_internal = isset($options['external']) && $options['external'] == FALSE;
  1880. if (!$force_internal && UrlHelper::isExternal($path)) {
  1881. return Url::fromUri($path, $options)->toString();
  1882. }
  1883. else {
  1884. $uri = $path === '<front>' ? 'base:/' : 'base:/' . $path;
  1885. // Path processing is needed for language prefixing. Skip it when a
  1886. // path that may look like an external URL is being used as internal.
  1887. $options['path_processing'] = !$force_internal;
  1888. return Url::fromUri($uri, $options)
  1889. ->setAbsolute()
  1890. ->toString();
  1891. }
  1892. }
  1893. else {
  1894. return $this->getAbsoluteUrl($path);
  1895. }
  1896. }
  1897. /**
  1898. * Asserts whether an expected cache tag was present in the last response.
  1899. *
  1900. * @param string $expected_cache_tag
  1901. * The expected cache tag.
  1902. */
  1903. protected function assertCacheTag($expected_cache_tag) {
  1904. $cache_tags = explode(' ', $this->drupalGetHeader('X-Drupal-Cache-Tags'));
  1905. $this->assertTrue(in_array($expected_cache_tag, $cache_tags), "'" . $expected_cache_tag . "' is present in the X-Drupal-Cache-Tags header.");
  1906. }
  1907. /**
  1908. * Asserts whether an expected cache tag was absent in the last response.
  1909. *
  1910. * @param string $cache_tag
  1911. * The cache tag to check.
  1912. */
  1913. protected function assertNoCacheTag($cache_tag) {
  1914. $cache_tags = explode(' ', $this->drupalGetHeader('X-Drupal-Cache-Tags'));
  1915. $this->assertFalse(in_array($cache_tag, $cache_tags), "'" . $cache_tag . "' is absent in the X-Drupal-Cache-Tags header.");
  1916. }
  1917. /**
  1918. * Enables/disables the cacheability headers.
  1919. *
  1920. * Sets the http.response.debug_cacheability_headers container parameter.
  1921. *
  1922. * @param bool $value
  1923. * (optional) Whether the debugging cacheability headers should be sent.
  1924. */
  1925. protected function setHttpResponseDebugCacheabilityHeaders($value = TRUE) {
  1926. $this->setContainerParameter('http.response.debug_cacheability_headers', $value);
  1927. $this->rebuildContainer();
  1928. $this->resetAll();
  1929. }
  1930. }