BrowserTestBaseTest.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792
  1. <?php
  2. namespace Drupal\FunctionalTests;
  3. use Behat\Mink\Exception\ExpectationException;
  4. use Drupal\Component\Serialization\Json;
  5. use Drupal\Component\Utility\Html;
  6. use Drupal\Core\Url;
  7. use Drupal\Tests\BrowserTestBase;
  8. use Drupal\Tests\Traits\Core\CronRunTrait;
  9. use PHPUnit\Framework\ExpectationFailedException;
  10. /**
  11. * Tests BrowserTestBase functionality.
  12. *
  13. * @group browsertestbase
  14. */
  15. class BrowserTestBaseTest extends BrowserTestBase {
  16. use CronRunTrait;
  17. /**
  18. * Modules to enable.
  19. *
  20. * @var array
  21. */
  22. public static $modules = [
  23. 'test_page_test',
  24. 'form_test',
  25. 'system_test',
  26. 'node',
  27. ];
  28. /**
  29. * {@inheritdoc}
  30. */
  31. protected $defaultTheme = 'classy';
  32. /**
  33. * Tests basic page test.
  34. */
  35. public function testGoTo() {
  36. $account = $this->drupalCreateUser();
  37. $this->drupalLogin($account);
  38. // Visit a Drupal page that requires login.
  39. $this->drupalGet('test-page');
  40. $this->assertSession()->statusCodeEquals(200);
  41. // Test page contains some text.
  42. $this->assertSession()->pageTextContains('Test page text.');
  43. // Check that returned plain text is correct.
  44. $text = $this->getTextContent();
  45. $this->assertStringContainsString('Test page text.', $text);
  46. $this->assertStringNotContainsString('</html>', $text);
  47. // Response includes cache tags that we can assert.
  48. $this->assertSession()->responseHeaderEquals('X-Drupal-Cache-Tags', 'http_response rendered');
  49. // Test that we can read the JS settings.
  50. $js_settings = $this->getDrupalSettings();
  51. $this->assertSame('azAZ09();.,\\\/-_{}', $js_settings['test-setting']);
  52. // Test drupalGet with a url object.
  53. $url = Url::fromRoute('test_page_test.render_title');
  54. $this->drupalGet($url);
  55. $this->assertSession()->statusCodeEquals(200);
  56. // Test page contains some text.
  57. $this->assertSession()->pageTextContains('Hello Drupal');
  58. // Test that setting headers with drupalGet() works.
  59. $this->drupalGet('system-test/header', [], [
  60. 'Test-Header' => 'header value',
  61. ]);
  62. $returned_header = $this->getSession()->getResponseHeader('Test-Header');
  63. $this->assertSame('header value', $returned_header);
  64. }
  65. /**
  66. * Tests drupalGet().
  67. */
  68. public function testDrupalGet() {
  69. $this->drupalGet('test-page');
  70. $this->assertSession()->statusCodeEquals(200);
  71. $this->assertSession()->addressEquals('test-page');
  72. $this->drupalGet('/test-page');
  73. $this->assertSession()->statusCodeEquals(200);
  74. $this->assertSession()->addressEquals('test-page');
  75. $this->drupalGet('/test-page/');
  76. $this->assertSession()->statusCodeEquals(200);
  77. $this->assertSession()->addressEquals('/test-page/');
  78. }
  79. /**
  80. * Tests basic form functionality.
  81. */
  82. public function testForm() {
  83. // Ensure the proper response code for a _form route.
  84. $this->drupalGet('form-test/object-builder');
  85. $this->assertSession()->statusCodeEquals(200);
  86. // Ensure the form and text field exist.
  87. $this->assertSession()->elementExists('css', 'form#form-test-form-test-object');
  88. $this->assertSession()->fieldExists('bananas');
  89. // Check that the hidden field exists and has a specific value.
  90. $this->assertSession()->hiddenFieldExists('strawberry');
  91. $this->assertSession()->hiddenFieldExists('red');
  92. $this->assertSession()->hiddenFieldExists('redstrawberryhiddenfield');
  93. $this->assertSession()->hiddenFieldValueNotEquals('strawberry', 'brown');
  94. $this->assertSession()->hiddenFieldValueEquals('strawberry', 'red');
  95. // Check that a hidden field does not exist.
  96. $this->assertSession()->hiddenFieldNotExists('bananas');
  97. $this->assertSession()->hiddenFieldNotExists('pineapple');
  98. $edit = ['bananas' => 'green'];
  99. $this->submitForm($edit, 'Save', 'form-test-form-test-object');
  100. $config_factory = $this->container->get('config.factory');
  101. $value = $config_factory->get('form_test.object')->get('bananas');
  102. $this->assertSame('green', $value);
  103. // Test drupalPostForm().
  104. $edit = ['bananas' => 'red'];
  105. // Submit the form using the button label.
  106. $result = $this->drupalPostForm('form-test/object-builder', $edit, 'Save');
  107. $this->assertSame($this->getSession()->getPage()->getContent(), $result);
  108. $value = $config_factory->get('form_test.object')->get('bananas');
  109. $this->assertSame('red', $value);
  110. $this->drupalPostForm('form-test/object-builder', NULL, 'Save');
  111. $value = $config_factory->get('form_test.object')->get('bananas');
  112. $this->assertSame('', $value);
  113. // Submit the form using the button id.
  114. $edit = ['bananas' => 'blue'];
  115. $result = $this->drupalPostForm('form-test/object-builder', $edit, 'edit-submit');
  116. $this->assertSame($this->getSession()->getPage()->getContent(), $result);
  117. $value = $config_factory->get('form_test.object')->get('bananas');
  118. $this->assertSame('blue', $value);
  119. // Submit the form using the button name.
  120. $edit = ['bananas' => 'purple'];
  121. $result = $this->drupalPostForm('form-test/object-builder', $edit, 'op');
  122. $this->assertSame($this->getSession()->getPage()->getContent(), $result);
  123. $value = $config_factory->get('form_test.object')->get('bananas');
  124. $this->assertSame('purple', $value);
  125. // Test drupalPostForm() with no-html response.
  126. $values = Json::decode($this->drupalPostForm('form_test/form-state-values-clean', [], t('Submit')));
  127. $this->assertSame(1000, $values['beer']);
  128. // Test drupalPostForm() with form by HTML id.
  129. $this->drupalCreateContentType(['type' => 'page']);
  130. $this->drupalLogin($this->drupalCreateUser(['create page content']));
  131. $this->drupalGet('form-test/two-instances-of-same-form');
  132. $this->getSession()->getPage()->fillField('edit-title-0-value', 'form1');
  133. $this->getSession()->getPage()->fillField('edit-title-0-value--2', 'form2');
  134. $this->drupalPostForm(NULL, [], 'Save', [], 'node-page-form--2');
  135. $this->assertSession()->pageTextContains('Page form2 has been created.');
  136. }
  137. /**
  138. * Tests clickLink() functionality.
  139. */
  140. public function testClickLink() {
  141. $this->drupalGet('test-page');
  142. $this->clickLink('Visually identical test links');
  143. $this->assertStringContainsString('user/login', $this->getSession()->getCurrentUrl());
  144. $this->drupalGet('test-page');
  145. $this->clickLink('Visually identical test links', 0);
  146. $this->assertStringContainsString('user/login', $this->getSession()->getCurrentUrl());
  147. $this->drupalGet('test-page');
  148. $this->clickLink('Visually identical test links', 1);
  149. $this->assertStringContainsString('user/register', $this->getSession()->getCurrentUrl());
  150. }
  151. public function testError() {
  152. $this->expectException('\Exception');
  153. $this->expectExceptionMessage('User notice: foo');
  154. $this->drupalGet('test-error');
  155. }
  156. /**
  157. * Tests linkExists() with pipe character (|) in locator.
  158. *
  159. * @see \Drupal\Tests\WebAssert::linkExists()
  160. */
  161. public function testPipeCharInLocator() {
  162. $this->drupalGet('test-pipe-char');
  163. $this->assertSession()->linkExists('foo|bar|baz');
  164. }
  165. /**
  166. * Tests linkExistsExact() functionality.
  167. *
  168. * @see \Drupal\Tests\WebAssert::linkExistsExact()
  169. */
  170. public function testLinkExistsExact() {
  171. $this->drupalGet('test-pipe-char');
  172. $this->assertSession()->linkExistsExact('foo|bar|baz');
  173. }
  174. /**
  175. * Tests linkExistsExact() functionality fail.
  176. *
  177. * @see \Drupal\Tests\WebAssert::linkExistsExact()
  178. */
  179. public function testInvalidLinkExistsExact() {
  180. $this->drupalGet('test-pipe-char');
  181. $this->expectException(ExpectationException::class);
  182. $this->expectExceptionMessage('Link with label foo|bar found');
  183. $this->assertSession()->linkExistsExact('foo|bar');
  184. }
  185. /**
  186. * Tests linkNotExistsExact() functionality.
  187. *
  188. * @see \Drupal\Tests\WebAssert::linkNotExistsExact()
  189. */
  190. public function testLinkNotExistsExact() {
  191. $this->drupalGet('test-pipe-char');
  192. $this->assertSession()->linkNotExistsExact('foo|bar');
  193. }
  194. /**
  195. * Tests linkNotExistsExact() functionality fail.
  196. *
  197. * @see \Drupal\Tests\WebAssert::linkNotExistsExact()
  198. */
  199. public function testInvalidLinkNotExistsExact() {
  200. $this->drupalGet('test-pipe-char');
  201. $this->expectException(ExpectationException::class);
  202. $this->expectExceptionMessage('Link with label foo|bar|baz not found');
  203. $this->assertSession()->linkNotExistsExact('foo|bar|baz');
  204. }
  205. /**
  206. * Tests legacy text asserts.
  207. */
  208. public function testTextAsserts() {
  209. $this->drupalGet('test-encoded');
  210. $dangerous = 'Bad html <script>alert(123);</script>';
  211. $sanitized = Html::escape($dangerous);
  212. $this->assertNoText($dangerous);
  213. $this->assertText($sanitized);
  214. }
  215. /**
  216. * Tests legacy getRawContent().
  217. *
  218. * @group legacy
  219. * @expectedDeprecation AssertLegacyTrait::getRawContent() is deprecated in drupal:8.2.0 and is removed from drupal:10.0.0. Use $this->getSession()->getPage()->getContent() instead. See https://www.drupal.org/node/3129738
  220. */
  221. public function testGetRawContent() {
  222. $this->drupalGet('test-encoded');
  223. $this->assertSame($this->getSession()->getPage()->getContent(), $this->getRawContent());
  224. }
  225. /**
  226. * Tests legacy field asserts which use xpath directly.
  227. */
  228. public function testXpathAsserts() {
  229. $this->drupalGet('test-field-xpath');
  230. $this->assertFieldsByValue($this->xpath("//h1[@class = 'page-title']"), NULL);
  231. $this->assertFieldsByValue($this->xpath('//table/tbody/tr[2]/td[1]'), 'one');
  232. $this->assertFieldByXPath('//table/tbody/tr[2]/td[1]', 'one');
  233. $this->assertFieldsByValue($this->xpath("//input[@id = 'edit-name']"), 'Test name');
  234. $this->assertFieldByXPath("//input[@id = 'edit-name']", 'Test name');
  235. $this->assertFieldsByValue($this->xpath("//select[@id = 'edit-options']"), '2');
  236. $this->assertFieldByXPath("//select[@id = 'edit-options']", '2');
  237. $this->assertNoFieldByXPath('//notexisting');
  238. $this->assertNoFieldByXPath("//input[@id = 'edit-name']", 'wrong value');
  239. // Test that the assertion fails correctly.
  240. try {
  241. $this->assertFieldByXPath("//input[@id = 'notexisting']");
  242. $this->fail('The "notexisting" field was found.');
  243. }
  244. catch (ExpectationFailedException $e) {
  245. $this->pass('assertFieldByXPath correctly failed. The "notexisting" field was not found.');
  246. }
  247. try {
  248. $this->assertNoFieldByXPath("//input[@id = 'edit-name']");
  249. $this->fail('The "edit-name" field was not found.');
  250. }
  251. catch (ExpectationException $e) {
  252. $this->pass('assertNoFieldByXPath correctly failed. The "edit-name" field was found.');
  253. }
  254. try {
  255. $this->assertFieldsByValue($this->xpath("//input[@id = 'edit-name']"), 'not the value');
  256. $this->fail('The "edit-name" field is found with the value "not the value".');
  257. }
  258. catch (ExpectationFailedException $e) {
  259. $this->pass('The "edit-name" field is not found with the value "not the value".');
  260. }
  261. }
  262. /**
  263. * Tests legacy field asserts using textfields.
  264. */
  265. public function testFieldAssertsForTextfields() {
  266. $this->drupalGet('test-field-xpath');
  267. // *** 1. assertNoField().
  268. $this->assertNoField('invalid_name_and_id');
  269. // Test that the assertion fails correctly when searching by name.
  270. try {
  271. $this->assertNoField('name');
  272. $this->fail('The "name" field was not found based on name.');
  273. }
  274. catch (ExpectationException $e) {
  275. $this->pass('assertNoField correctly failed. The "name" field was found by name.');
  276. }
  277. // Test that the assertion fails correctly when searching by id.
  278. try {
  279. $this->assertNoField('edit-name');
  280. $this->fail('The "name" field was not found based on id.');
  281. }
  282. catch (ExpectationException $e) {
  283. $this->pass('assertNoField correctly failed. The "name" field was found by id.');
  284. }
  285. // *** 2. assertField().
  286. $this->assertField('name');
  287. $this->assertField('edit-name');
  288. // Test that the assertion fails correctly if the field does not exist.
  289. try {
  290. $this->assertField('invalid_name_and_id');
  291. $this->fail('The "invalid_name_and_id" field was found.');
  292. }
  293. catch (ExpectationFailedException $e) {
  294. $this->pass('assertField correctly failed. The "invalid_name_and_id" field was not found.');
  295. }
  296. // *** 3. assertNoFieldById().
  297. $this->assertNoFieldById('name');
  298. $this->assertNoFieldById('name', 'not the value');
  299. $this->assertNoFieldById('notexisting');
  300. $this->assertNoFieldById('notexisting', NULL);
  301. // Test that the assertion fails correctly if no value is passed in.
  302. try {
  303. $this->assertNoFieldById('edit-description');
  304. $this->fail('The "description" field, with no value was not found.');
  305. }
  306. catch (ExpectationException $e) {
  307. $this->pass('The "description" field, with no value was found.');
  308. }
  309. // Test that the assertion fails correctly if a NULL value is passed in.
  310. try {
  311. $this->assertNoFieldById('edit-name', NULL);
  312. $this->fail('The "name" field was not found.');
  313. }
  314. catch (ExpectationException $e) {
  315. $this->pass('The "name" field was found.');
  316. }
  317. // *** 4. assertFieldById().
  318. $this->assertFieldById('edit-name', NULL);
  319. $this->assertFieldById('edit-name', 'Test name');
  320. $this->assertFieldById('edit-description', NULL);
  321. $this->assertFieldById('edit-description');
  322. // Test that the assertion fails correctly if no value is passed in.
  323. try {
  324. $this->assertFieldById('edit-name');
  325. $this->fail('The "edit-name" field with no value was found.');
  326. }
  327. catch (ExpectationFailedException $e) {
  328. $this->pass('The "edit-name" field with no value was not found.');
  329. }
  330. // Test that the assertion fails correctly if the wrong value is passed in.
  331. try {
  332. $this->assertFieldById('edit-name', 'not the value');
  333. $this->fail('The "name" field was found, using the wrong value.');
  334. }
  335. catch (ExpectationFailedException $e) {
  336. $this->pass('The "name" field was not found, using the wrong value.');
  337. }
  338. // *** 5. assertNoFieldByName().
  339. $this->assertNoFieldByName('name');
  340. $this->assertNoFieldByName('name', 'not the value');
  341. $this->assertNoFieldByName('notexisting');
  342. $this->assertNoFieldByName('notexisting', NULL);
  343. // Test that the assertion fails correctly if no value is passed in.
  344. try {
  345. $this->assertNoFieldByName('description');
  346. $this->fail('The "description" field, with no value was not found.');
  347. }
  348. catch (ExpectationException $e) {
  349. $this->pass('The "description" field, with no value was found.');
  350. }
  351. // Test that the assertion fails correctly if a NULL value is passed in.
  352. try {
  353. $this->assertNoFieldByName('name', NULL);
  354. $this->fail('The "name" field was not found.');
  355. }
  356. catch (ExpectationException $e) {
  357. $this->pass('The "name" field was found.');
  358. }
  359. // *** 6. assertFieldByName().
  360. $this->assertFieldByName('name');
  361. $this->assertFieldByName('name', NULL);
  362. $this->assertFieldByName('name', 'Test name');
  363. $this->assertFieldByName('description');
  364. $this->assertFieldByName('description', '');
  365. $this->assertFieldByName('description', NULL);
  366. // Test that the assertion fails correctly if given the wrong name.
  367. try {
  368. $this->assertFieldByName('non-existing-name');
  369. $this->fail('The "non-existing-name" field was found.');
  370. }
  371. catch (ExpectationFailedException $e) {
  372. $this->pass('The "non-existing-name" field was not found');
  373. }
  374. // Test that the assertion fails correctly if given the wrong value.
  375. try {
  376. $this->assertFieldByName('name', 'not the value');
  377. $this->fail('The "name" field with incorrect value was found.');
  378. }
  379. catch (ExpectationFailedException $e) {
  380. $this->pass('assertFieldByName correctly failed. The "name" field with incorrect value was not found.');
  381. }
  382. // Test that text areas can contain new lines.
  383. $this->assertFieldsByValue($this->xpath("//textarea[@id = 'edit-test-textarea-with-newline']"), "Test text with\nnewline");
  384. }
  385. /**
  386. * Tests legacy field asserts for options field type.
  387. */
  388. public function testFieldAssertsForOptions() {
  389. $this->drupalGet('test-field-xpath');
  390. // Option field type.
  391. $this->assertOptionByText('options', 'one');
  392. try {
  393. $this->assertOptionByText('options', 'four');
  394. $this->fail('The select option "four" was found.');
  395. }
  396. catch (ExpectationException $e) {
  397. $this->pass($e->getMessage());
  398. }
  399. $this->assertOption('options', 1);
  400. try {
  401. $this->assertOption('options', 4);
  402. $this->fail('The select option "4" was found.');
  403. }
  404. catch (ExpectationException $e) {
  405. $this->pass($e->getMessage());
  406. }
  407. $this->assertNoOption('options', 'non-existing');
  408. try {
  409. $this->assertNoOption('options', 'one');
  410. $this->fail('The select option "one" was not found.');
  411. }
  412. catch (ExpectationException $e) {
  413. $this->pass($e->getMessage());
  414. }
  415. $this->assertOptionSelected('options', 2);
  416. try {
  417. $this->assertOptionSelected('options', 4);
  418. $this->fail('The select option "4" was selected.');
  419. }
  420. catch (ExpectationException $e) {
  421. $this->pass($e->getMessage());
  422. }
  423. try {
  424. $this->assertOptionSelected('options', 1);
  425. $this->fail('The select option "1" was selected.');
  426. }
  427. catch (ExpectationFailedException $e) {
  428. $this->pass($e->getMessage());
  429. }
  430. }
  431. /**
  432. * Tests legacy field asserts for button field type.
  433. */
  434. public function testFieldAssertsForButton() {
  435. $this->drupalGet('test-field-xpath');
  436. $this->assertFieldById('edit-save', NULL);
  437. // Test that the assertion fails correctly if the field value is passed in
  438. // rather than the id.
  439. try {
  440. $this->assertFieldById('Save', NULL);
  441. $this->fail('The field with id of "Save" was found.');
  442. }
  443. catch (ExpectationFailedException $e) {
  444. $this->pass($e->getMessage());
  445. }
  446. $this->assertNoFieldById('Save', NULL);
  447. // Test that the assertion fails correctly if the id of an actual field is
  448. // passed in.
  449. try {
  450. $this->assertNoFieldById('edit-save', NULL);
  451. $this->fail('The field with id of "edit-save" was not found.');
  452. }
  453. catch (ExpectationException $e) {
  454. $this->pass($e->getMessage());
  455. }
  456. // Test that multiple fields with the same name are validated correctly.
  457. $this->assertFieldByName('duplicate_button', 'Duplicate button 1');
  458. $this->assertFieldByName('duplicate_button', 'Duplicate button 2');
  459. $this->assertNoFieldByName('duplicate_button', 'Rabbit');
  460. try {
  461. $this->assertNoFieldByName('duplicate_button', 'Duplicate button 2');
  462. $this->fail('The "duplicate_button" field with the value Duplicate button 2 was not found.');
  463. }
  464. catch (ExpectationException $e) {
  465. $this->pass('assertNoFieldByName correctly failed. The "duplicate_button" field with the value Duplicate button 2 was found.');
  466. }
  467. }
  468. /**
  469. * Tests legacy field asserts for checkbox field type.
  470. */
  471. public function testFieldAssertsForCheckbox() {
  472. $this->drupalGet('test-field-xpath');
  473. // Part 1 - Test by name.
  474. // Test that checkboxes are found/not found correctly by name, when using
  475. // TRUE or FALSE to match their 'checked' state.
  476. $this->assertFieldByName('checkbox_enabled', TRUE);
  477. $this->assertFieldByName('checkbox_disabled', FALSE);
  478. $this->assertNoFieldByName('checkbox_enabled', FALSE);
  479. $this->assertNoFieldByName('checkbox_disabled', TRUE);
  480. // Test that checkboxes are found by name when using NULL to ignore the
  481. // 'checked' state.
  482. $this->assertFieldByName('checkbox_enabled', NULL);
  483. $this->assertFieldByName('checkbox_disabled', NULL);
  484. // Test that checkboxes are found by name when passing no second parameter.
  485. $this->assertFieldByName('checkbox_enabled');
  486. $this->assertFieldByName('checkbox_disabled');
  487. // Test that we have legacy support.
  488. $this->assertFieldByName('checkbox_enabled', '1');
  489. $this->assertFieldByName('checkbox_disabled', '');
  490. // Test that the assertion fails correctly when using NULL to ignore state.
  491. try {
  492. $this->assertNoFieldByName('checkbox_enabled', NULL);
  493. $this->fail('The "checkbox_enabled" field was not found by name, using NULL value.');
  494. }
  495. catch (ExpectationException $e) {
  496. $this->pass('assertNoFieldByName failed correctly. The "checkbox_enabled" field was found using NULL value.');
  497. }
  498. // Part 2 - Test by ID.
  499. // Test that checkboxes are found/not found correctly by ID, when using
  500. // TRUE or FALSE to match their 'checked' state.
  501. $this->assertFieldById('edit-checkbox-enabled', TRUE);
  502. $this->assertFieldById('edit-checkbox-disabled', FALSE);
  503. $this->assertNoFieldById('edit-checkbox-enabled', FALSE);
  504. $this->assertNoFieldById('edit-checkbox-disabled', TRUE);
  505. // Test that checkboxes are found by ID, when using NULL to ignore the
  506. // 'checked' state.
  507. $this->assertFieldById('edit-checkbox-enabled', NULL);
  508. $this->assertFieldById('edit-checkbox-disabled', NULL);
  509. // Test that checkboxes are found by ID when passing no second parameter.
  510. $this->assertFieldById('edit-checkbox-enabled');
  511. $this->assertFieldById('edit-checkbox-disabled');
  512. // Test that we have legacy support.
  513. $this->assertFieldById('edit-checkbox-enabled', '1');
  514. $this->assertFieldById('edit-checkbox-disabled', '');
  515. // Test that the assertion fails correctly when using NULL to ignore state.
  516. try {
  517. $this->assertNoFieldById('edit-checkbox-disabled', NULL);
  518. $this->fail('The "edit-checkbox-disabled" field was not found by ID, using NULL value.');
  519. }
  520. catch (ExpectationException $e) {
  521. $this->pass('assertNoFieldById failed correctly. The "edit-checkbox-disabled" field was found by ID using NULL value.');
  522. }
  523. // Part 3 - Test the specific 'checked' assertions.
  524. $this->assertFieldChecked('edit-checkbox-enabled');
  525. $this->assertNoFieldChecked('edit-checkbox-disabled');
  526. // Test that the assertion fails correctly with non-existent field id.
  527. try {
  528. $this->assertNoFieldChecked('incorrect_checkbox_id');
  529. $this->fail('The "incorrect_checkbox_id" field was found');
  530. }
  531. catch (ExpectationException $e) {
  532. $this->pass('assertNoFieldChecked correctly failed. The "incorrect_checkbox_id" field was not found.');
  533. }
  534. // Test that the assertion fails correctly for a checkbox that is checked.
  535. try {
  536. $this->assertNoFieldChecked('edit-checkbox-enabled');
  537. $this->fail('The "edit-checkbox-enabled" field was not found in a checked state.');
  538. }
  539. catch (ExpectationException $e) {
  540. $this->pass('assertNoFieldChecked correctly failed. The "edit-checkbox-enabled" field was found in a checked state.');
  541. }
  542. // Test that the assertion fails correctly for a checkbox that is not
  543. // checked.
  544. try {
  545. $this->assertFieldChecked('edit-checkbox-disabled');
  546. $this->fail('The "edit-checkbox-disabled" field was found and checked.');
  547. }
  548. catch (ExpectationException $e) {
  549. $this->pass('assertFieldChecked correctly failed. The "edit-checkbox-disabled" field was not found in a checked state.');
  550. }
  551. }
  552. /**
  553. * Tests the ::cronRun() method.
  554. */
  555. public function testCronRun() {
  556. $last_cron_time = \Drupal::state()->get('system.cron_last');
  557. $this->cronRun();
  558. $this->assertSession()->statusCodeEquals(204);
  559. $next_cron_time = \Drupal::state()->get('system.cron_last');
  560. $this->assertGreaterThan($last_cron_time, $next_cron_time);
  561. }
  562. /**
  563. * Tests the Drupal install done in \Drupal\Tests\BrowserTestBase::setUp().
  564. */
  565. public function testInstall() {
  566. $htaccess_filename = $this->tempFilesDirectory . '/.htaccess';
  567. $this->assertFileExists($htaccess_filename);
  568. }
  569. /**
  570. * Tests the assumption that local time is in 'Australia/Sydney'.
  571. */
  572. public function testLocalTimeZone() {
  573. $expected = 'Australia/Sydney';
  574. // The 'Australia/Sydney' time zone is set in core/tests/bootstrap.php
  575. $this->assertEquals($expected, date_default_timezone_get());
  576. // The 'Australia/Sydney' time zone is also set in
  577. // FunctionalTestSetupTrait::initConfig().
  578. $config_factory = $this->container->get('config.factory');
  579. $value = $config_factory->get('system.date')->get('timezone.default');
  580. $this->assertEquals($expected, $value);
  581. // Test that users have the correct time zone set.
  582. $this->assertEquals($expected, $this->rootUser->getTimeZone());
  583. $admin_user = $this->drupalCreateUser(['administer site configuration']);
  584. $this->assertEquals($expected, $admin_user->getTimeZone());
  585. }
  586. /**
  587. * Tests the ::checkForMetaRefresh() method.
  588. */
  589. public function testCheckForMetaRefresh() {
  590. // Disable following redirects in the client.
  591. $this->getSession()->getDriver()->getClient()->followRedirects(FALSE);
  592. // Set the maximumMetaRefreshCount to zero to make sure the redirect doesn't
  593. // happen when doing a drupalGet.
  594. $this->maximumMetaRefreshCount = 0;
  595. $this->drupalGet('test-meta-refresh');
  596. $this->assertNotEmpty($this->cssSelect('meta[http-equiv="refresh"]'));
  597. // Allow one redirect to happen.
  598. $this->maximumMetaRefreshCount = 1;
  599. $this->checkForMetaRefresh();
  600. // Check that we are now on the test page.
  601. $this->assertSession()->pageTextContains('Test page text.');
  602. }
  603. public function testGetDefaultDriveInstance() {
  604. putenv('MINK_DRIVER_ARGS=' . json_encode([NULL, ['key1' => ['key2' => ['key3' => 3, 'key3.1' => 3.1]]]]));
  605. $this->getDefaultDriverInstance();
  606. $this->assertEquals([NULL, ['key1' => ['key2' => ['key3' => 3, 'key3.1' => 3.1]]]], $this->minkDefaultDriverArgs);
  607. }
  608. /**
  609. * Ensures we can't access modules we shouldn't be able to after install.
  610. */
  611. public function testProfileModules() {
  612. $this->expectException(\InvalidArgumentException::class);
  613. $this->expectExceptionMessage('The module demo_umami_content does not exist.');
  614. $this->assertFileExists('core/profiles/demo_umami/modules/demo_umami_content/demo_umami_content.info.yml');
  615. \Drupal::service('extension.list.module')->getPathname('demo_umami_content');
  616. }
  617. /**
  618. * Test the protections provided by .htkey.
  619. */
  620. public function testHtkey() {
  621. // Remove the Simpletest private key file so we can test the protection
  622. // against requests that forge a valid testing user agent to gain access
  623. // to the installer.
  624. // @see drupal_valid_test_ua()
  625. // Not using File API; a potential error must trigger a PHP warning.
  626. $install_url = Url::fromUri('base:core/install.php', ['external' => TRUE, 'absolute' => TRUE])->toString();
  627. $this->drupalGet($install_url);
  628. $this->assertSession()->statusCodeEquals(200);
  629. unlink($this->siteDirectory . '/.htkey');
  630. $this->drupalGet($install_url);
  631. $this->assertSession()->statusCodeEquals(403);
  632. }
  633. /**
  634. * Tests assertEscaped() and assertUnescaped().
  635. *
  636. * @see \Drupal\Tests\WebAssert::assertNoEscaped()
  637. * @see \Drupal\Tests\WebAssert::assertEscaped()
  638. */
  639. public function testEscapingAssertions() {
  640. $assert = $this->assertSession();
  641. $this->drupalGet('test-escaped-characters');
  642. $assert->assertNoEscaped('<div class="escaped">');
  643. $assert->responseContains('<div class="escaped">');
  644. $assert->assertEscaped('Escaped: <"\'&>');
  645. $this->drupalGet('test-escaped-script');
  646. $assert->assertNoEscaped('<div class="escaped">');
  647. $assert->responseContains('<div class="escaped">');
  648. $assert->assertEscaped("<script>alert('XSS');alert(\"XSS\");</script>");
  649. $this->drupalGet('test-unescaped-script');
  650. $assert->assertNoEscaped('<div class="unescaped">');
  651. $assert->responseContains('<div class="unescaped">');
  652. $assert->responseContains("<script>alert('Marked safe');alert(\"Marked safe\");</script>");
  653. $assert->assertNoEscaped("<script>alert('Marked safe');alert(\"Marked safe\");</script>");
  654. }
  655. /**
  656. * Tests that deprecation headers do not get duplicated.
  657. *
  658. * @group legacy
  659. *
  660. * @see \Drupal\Core\Test\HttpClientMiddleware\TestHttpClientMiddleware::__invoke()
  661. */
  662. public function testDeprecationHeaders() {
  663. $this->drupalGet('/test-deprecations');
  664. $deprecation_messages = [];
  665. foreach ($this->getSession()->getResponseHeaders() as $name => $values) {
  666. if (preg_match('/^X-Drupal-Assertion-[0-9]+$/', $name, $matches)) {
  667. foreach ($values as $value) {
  668. // Call \Drupal\simpletest\WebTestBase::error() with the parameters from
  669. // the header.
  670. $parameters = unserialize(urldecode($value));
  671. if (count($parameters) === 3) {
  672. if ($parameters[1] === 'User deprecated function') {
  673. $deprecation_messages[] = (string) $parameters[0];
  674. }
  675. }
  676. }
  677. }
  678. }
  679. $this->assertContains('Test deprecation message', $deprecation_messages);
  680. $test_deprecation_messages = array_filter($deprecation_messages, function ($message) {
  681. return $message === 'Test deprecation message';
  682. });
  683. $this->assertCount(1, $test_deprecation_messages);
  684. }
  685. }