ajax.test

File

drupal-7.x/modules/simpletest/tests/ajax.test
View source
  1. <?php
  2. class AJAXTestCase extends DrupalWebTestCase {
  3. function setUp() {
  4. $modules = func_get_args();
  5. if (isset($modules[0]) && is_array($modules[0])) {
  6. $modules = $modules[0];
  7. }
  8. parent::setUp(array_unique(array_merge(array('ajax_test', 'ajax_forms_test'), $modules)));
  9. }
  10. /**
  11. * Assert that a command with the required properties exists within the array of Ajax commands returned by the server.
  12. *
  13. * The Ajax framework, via the ajax_deliver() and ajax_render() functions,
  14. * returns an array of commands. This array sometimes includes commands
  15. * automatically provided by the framework in addition to commands returned by
  16. * a particular page callback. During testing, we're usually interested that a
  17. * particular command is present, and don't care whether other commands
  18. * precede or follow the one we're interested in. Additionally, the command
  19. * we're interested in may include additional data that we're not interested
  20. * in. Therefore, this function simply asserts that one of the commands in
  21. * $haystack contains all of the keys and values in $needle. Furthermore, if
  22. * $needle contains a 'settings' key with an array value, we simply assert
  23. * that all keys and values within that array are present in the command we're
  24. * checking, and do not consider it a failure if the actual command contains
  25. * additional settings that aren't part of $needle.
  26. *
  27. * @param $haystack
  28. * An array of Ajax commands returned by the server.
  29. * @param $needle
  30. * Array of info we're expecting in one of those commands.
  31. * @param $message
  32. * An assertion message.
  33. */
  34. protected function assertCommand($haystack, $needle, $message) {
  35. $found = FALSE;
  36. foreach ($haystack as $command) {
  37. // If the command has additional settings that we're not testing for, do
  38. // not consider that a failure.
  39. if (isset($command['settings']) && is_array($command['settings']) && isset($needle['settings']) && is_array($needle['settings'])) {
  40. $command['settings'] = array_intersect_key($command['settings'], $needle['settings']);
  41. }
  42. // If the command has additional data that we're not testing for, do not
  43. // consider that a failure. Also, == instead of ===, because we don't
  44. // require the key/value pairs to be in any particular order
  45. // (http://www.php.net/manual/en/language.operators.array.php).
  46. if (array_intersect_key($command, $needle) == $needle) {
  47. $found = TRUE;
  48. break;
  49. }
  50. }
  51. $this->assertTrue($found, $message);
  52. }
  53. }
  54. /**
  55. * Tests primary Ajax framework functions.
  56. */
  57. class AJAXFrameworkTestCase extends AJAXTestCase {
  58. protected $profile = 'testing';
  59. public static function getInfo() {
  60. return array(
  61. 'name' => 'AJAX framework',
  62. 'description' => 'Performs tests on AJAX framework functions.',
  63. 'group' => 'AJAX',
  64. );
  65. }
  66. /**
  67. * Test that ajax_render() returns JavaScript settings generated during the page request.
  68. *
  69. * @todo Add tests to ensure that ajax_render() returns commands for new CSS
  70. * and JavaScript files to be loaded by the page. See
  71. * http://drupal.org/node/561858.
  72. */
  73. function testAJAXRender() {
  74. $commands = $this->drupalGetAJAX('ajax-test/render');
  75. // Verify that there is a command to load settings added with
  76. // drupal_add_js().
  77. $expected = array(
  78. 'command' => 'settings',
  79. 'settings' => array('basePath' => base_path(), 'ajax' => 'test'),
  80. );
  81. $this->assertCommand($commands, $expected, t('ajax_render() loads settings added with drupal_add_js().'));
  82. // Verify that Ajax settings are loaded for #type 'link'.
  83. $this->drupalGet('ajax-test/link');
  84. $settings = $this->drupalGetSettings();
  85. $this->assertEqual($settings['ajax']['ajax-link']['url'], url('filter/tips'));
  86. $this->assertEqual($settings['ajax']['ajax-link']['wrapper'], 'block-system-main');
  87. }
  88. /**
  89. * Test behavior of ajax_render_error().
  90. */
  91. function testAJAXRenderError() {
  92. // Verify default error message.
  93. $commands = $this->drupalGetAJAX('ajax-test/render-error');
  94. $expected = array(
  95. 'command' => 'alert',
  96. 'text' => t('An error occurred while handling the request: The server received invalid input.'),
  97. );
  98. $this->assertCommand($commands, $expected, t('ajax_render_error() invokes alert command.'));
  99. // Verify custom error message.
  100. $edit = array(
  101. 'message' => 'Custom error message.',
  102. );
  103. $commands = $this->drupalGetAJAX('ajax-test/render-error', array('query' => $edit));
  104. $expected = array(
  105. 'command' => 'alert',
  106. 'text' => $edit['message'],
  107. );
  108. $this->assertCommand($commands, $expected, t('Custom error message is output.'));
  109. }
  110. /**
  111. * Test that new JavaScript and CSS files added during an AJAX request are returned.
  112. */
  113. function testLazyLoad() {
  114. $expected = array(
  115. 'setting_name' => 'ajax_forms_test_lazy_load_form_submit',
  116. 'setting_value' => 'executed',
  117. 'css' => drupal_get_path('module', 'system') . '/system.admin.css',
  118. 'js' => drupal_get_path('module', 'system') . '/system.js',
  119. );
  120. // @todo D8: Add a drupal_css_defaults() helper function.
  121. $expected_css_html = drupal_get_css(array($expected['css'] => array(
  122. 'type' => 'file',
  123. 'group' => CSS_DEFAULT,
  124. 'weight' => 0,
  125. 'every_page' => FALSE,
  126. 'media' => 'all',
  127. 'preprocess' => TRUE,
  128. 'data' => $expected['css'],
  129. 'browsers' => array('IE' => TRUE, '!IE' => TRUE),
  130. )), TRUE);
  131. $expected_js_html = drupal_get_js('header', array($expected['js'] => drupal_js_defaults($expected['js'])), TRUE);
  132. // Get the base page.
  133. $this->drupalGet('ajax_forms_test_lazy_load_form');
  134. $original_settings = $this->drupalGetSettings();
  135. $original_css = $original_settings['ajaxPageState']['css'];
  136. $original_js = $original_settings['ajaxPageState']['js'];
  137. // Verify that the base page doesn't have the settings and files that are to
  138. // be lazy loaded as part of the next requests.
  139. $this->assertTrue(!isset($original_settings[$expected['setting_name']]), t('Page originally lacks the %setting, as expected.', array('%setting' => $expected['setting_name'])));
  140. $this->assertTrue(!isset($original_settings[$expected['css']]), t('Page originally lacks the %css file, as expected.', array('%css' => $expected['css'])));
  141. $this->assertTrue(!isset($original_settings[$expected['js']]), t('Page originally lacks the %js file, as expected.', array('%js' => $expected['js'])));
  142. // Submit the AJAX request without triggering files getting added.
  143. $commands = $this->drupalPostAJAX(NULL, array('add_files' => FALSE), array('op' => t('Submit')));
  144. $new_settings = $this->drupalGetSettings();
  145. // Verify the setting was not added when not expected.
  146. $this->assertTrue(!isset($new_settings['setting_name']), t('Page still lacks the %setting, as expected.', array('%setting' => $expected['setting_name'])));
  147. // Verify a settings command does not add CSS or scripts to Drupal.settings
  148. // and no command inserts the corresponding tags on the page.
  149. $found_settings_command = FALSE;
  150. $found_markup_command = FALSE;
  151. foreach ($commands as $command) {
  152. if ($command['command'] == 'settings' && (array_key_exists('css', $command['settings']['ajaxPageState']) || array_key_exists('js', $command['settings']['ajaxPageState']))) {
  153. $found_settings_command = TRUE;
  154. }
  155. if (isset($command['data']) && ($command['data'] == $expected_js_html || $command['data'] == $expected_css_html)) {
  156. $found_markup_command = TRUE;
  157. }
  158. }
  159. $this->assertFalse($found_settings_command, t('Page state still lacks the %css and %js files, as expected.', array('%css' => $expected['css'], '%js' => $expected['js'])));
  160. $this->assertFalse($found_markup_command, t('Page still lacks the %css and %js files, as expected.', array('%css' => $expected['css'], '%js' => $expected['js'])));
  161. // Submit the AJAX request and trigger adding files.
  162. $commands = $this->drupalPostAJAX(NULL, array('add_files' => TRUE), array('op' => t('Submit')));
  163. $new_settings = $this->drupalGetSettings();
  164. $new_css = $new_settings['ajaxPageState']['css'];
  165. $new_js = $new_settings['ajaxPageState']['js'];
  166. // Verify the expected setting was added.
  167. $this->assertIdentical($new_settings[$expected['setting_name']], $expected['setting_value'], t('Page now has the %setting.', array('%setting' => $expected['setting_name'])));
  168. // Verify the expected CSS file was added, both to Drupal.settings, and as
  169. // an AJAX command for inclusion into the HTML.
  170. $this->assertEqual($new_css, $original_css + array($expected['css'] => 1), t('Page state now has the %css file.', array('%css' => $expected['css'])));
  171. $this->assertCommand($commands, array('data' => $expected_css_html), t('Page now has the %css file.', array('%css' => $expected['css'])));
  172. // Verify the expected JS file was added, both to Drupal.settings, and as
  173. // an AJAX command for inclusion into the HTML. By testing for an exact HTML
  174. // string containing the SCRIPT tag, we also ensure that unexpected
  175. // JavaScript code, such as a jQuery.extend() that would potentially clobber
  176. // rather than properly merge settings, didn't accidentally get added.
  177. $this->assertEqual($new_js, $original_js + array($expected['js'] => 1), t('Page state now has the %js file.', array('%js' => $expected['js'])));
  178. $this->assertCommand($commands, array('data' => $expected_js_html), t('Page now has the %js file.', array('%js' => $expected['js'])));
  179. }
  180. /**
  181. * Tests that overridden CSS files are not added during lazy load.
  182. */
  183. function testLazyLoadOverriddenCSS() {
  184. // The test theme overrides system.base.css without an implementation,
  185. // thereby removing it.
  186. theme_enable(array('test_theme'));
  187. variable_set('theme_default', 'test_theme');
  188. // This gets the form, and emulates an Ajax submission on it, including
  189. // adding markup to the HEAD and BODY for any lazy loaded JS/CSS files.
  190. $this->drupalPostAJAX('ajax_forms_test_lazy_load_form', array('add_files' => TRUE), array('op' => t('Submit')));
  191. // Verify that the resulting HTML does not load the overridden CSS file.
  192. // We add a "?" to the assertion, because Drupal.settings may include
  193. // information about the file; we only really care about whether it appears
  194. // in a LINK or STYLE tag, for which Drupal always adds a query string for
  195. // cache control.
  196. $this->assertNoText('system.base.css?', 'Ajax lazy loading does not add overridden CSS files.');
  197. }
  198. }
  199. /**
  200. * Tests Ajax framework commands.
  201. */
  202. class AJAXCommandsTestCase extends AJAXTestCase {
  203. public static function getInfo() {
  204. return array(
  205. 'name' => 'AJAX commands',
  206. 'description' => 'Performs tests on AJAX framework commands.',
  207. 'group' => 'AJAX',
  208. );
  209. }
  210. /**
  211. * Test the various Ajax Commands.
  212. */
  213. function testAJAXCommands() {
  214. $form_path = 'ajax_forms_test_ajax_commands_form';
  215. $web_user = $this->drupalCreateUser(array('access content'));
  216. $this->drupalLogin($web_user);
  217. $edit = array();
  218. // Tests the 'after' command.
  219. $commands = $this->drupalPostAJAX($form_path, $edit, array('op' => t("AJAX 'After': Click to put something after the div")));
  220. $expected = array(
  221. 'command' => 'insert',
  222. 'method' => 'after',
  223. 'data' => 'This will be placed after',
  224. );
  225. $this->assertCommand($commands, $expected, "'after' AJAX command issued with correct data");
  226. // Tests the 'alert' command.
  227. $commands = $this->drupalPostAJAX($form_path, $edit, array('op' => t("AJAX 'Alert': Click to alert")));
  228. $expected = array(
  229. 'command' => 'alert',
  230. 'text' => 'Alert',
  231. );
  232. $this->assertCommand($commands, $expected, "'alert' AJAX Command issued with correct text");
  233. // Tests the 'append' command.
  234. $commands = $this->drupalPostAJAX($form_path, $edit, array('op' => t("AJAX 'Append': Click to append something")));
  235. $expected = array(
  236. 'command' => 'insert',
  237. 'method' => 'append',
  238. 'data' => 'Appended text',
  239. );
  240. $this->assertCommand($commands, $expected, "'append' AJAX command issued with correct data");
  241. // Tests the 'before' command.
  242. $commands = $this->drupalPostAJAX($form_path, $edit, array('op' => t("AJAX 'before': Click to put something before the div")));
  243. $expected = array(
  244. 'command' => 'insert',
  245. 'method' => 'before',
  246. 'data' => 'Before text',
  247. );
  248. $this->assertCommand($commands, $expected, "'before' AJAX command issued with correct data");
  249. // Tests the 'changed' command.
  250. $commands = $this->drupalPostAJAX($form_path, $edit, array('op' => t("AJAX changed: Click to mark div changed.")));
  251. $expected = array(
  252. 'command' => 'changed',
  253. 'selector' => '#changed_div',
  254. );
  255. $this->assertCommand($commands, $expected, "'changed' AJAX command issued with correct selector");
  256. // Tests the 'changed' command using the second argument.
  257. $commands = $this->drupalPostAJAX($form_path, $edit, array('op' => t("AJAX changed: Click to mark div changed with asterisk.")));
  258. $expected = array(
  259. 'command' => 'changed',
  260. 'selector' => '#changed_div',
  261. 'asterisk' => '#changed_div_mark_this',
  262. );
  263. $this->assertCommand($commands, $expected, "'changed' AJAX command (with asterisk) issued with correct selector");
  264. // Tests the 'css' command.
  265. $commands = $this->drupalPostAJAX($form_path, $edit, array('op' => t("Set the the '#box' div to be blue.")));
  266. $expected = array(
  267. 'command' => 'css',
  268. 'selector' => '#css_div',
  269. 'argument' => array('background-color' => 'blue'),
  270. );
  271. $this->assertCommand($commands, $expected, "'css' AJAX command issued with correct selector");
  272. // Tests the 'data' command.
  273. $commands = $this->drupalPostAJAX($form_path, $edit, array('op' => t("AJAX data command: Issue command.")));
  274. $expected = array(
  275. 'command' => 'data',
  276. 'name' => 'testkey',
  277. 'value' => 'testvalue',
  278. );
  279. $this->assertCommand($commands, $expected, "'data' AJAX command issued with correct key and value");
  280. // Tests the 'invoke' command.
  281. $commands = $this->drupalPostAJAX($form_path, $edit, array('op' => t("AJAX invoke command: Invoke addClass() method.")));
  282. $expected = array(
  283. 'command' => 'invoke',
  284. 'method' => 'addClass',
  285. 'arguments' => array('error'),
  286. );
  287. $this->assertCommand($commands, $expected, "'invoke' AJAX command issued with correct method and argument");
  288. // Tests the 'html' command.
  289. $commands = $this->drupalPostAJAX($form_path, $edit, array('op' => t("AJAX html: Replace the HTML in a selector.")));
  290. $expected = array(
  291. 'command' => 'insert',
  292. 'method' => 'html',
  293. 'data' => 'replacement text',
  294. );
  295. $this->assertCommand($commands, $expected, "'html' AJAX command issued with correct data");
  296. // Tests the 'insert' command.
  297. $commands = $this->drupalPostAJAX($form_path, $edit, array('op' => t("AJAX insert: Let client insert based on #ajax['method'].")));
  298. $expected = array(
  299. 'command' => 'insert',
  300. 'data' => 'insert replacement text',
  301. );
  302. $this->assertCommand($commands, $expected, "'insert' AJAX command issued with correct data");
  303. // Tests the 'prepend' command.
  304. $commands = $this->drupalPostAJAX($form_path, $edit, array('op' => t("AJAX 'prepend': Click to prepend something")));
  305. $expected = array(
  306. 'command' => 'insert',
  307. 'method' => 'prepend',
  308. 'data' => 'prepended text',
  309. );
  310. $this->assertCommand($commands, $expected, "'prepend' AJAX command issued with correct data");
  311. // Tests the 'remove' command.
  312. $commands = $this->drupalPostAJAX($form_path, $edit, array('op' => t("AJAX 'remove': Click to remove text")));
  313. $expected = array(
  314. 'command' => 'remove',
  315. 'selector' => '#remove_text',
  316. );
  317. $this->assertCommand($commands, $expected, "'remove' AJAX command issued with correct command and selector");
  318. // Tests the 'restripe' command.
  319. $commands = $this->drupalPostAJAX($form_path, $edit, array('op' => t("AJAX 'restripe' command")));
  320. $expected = array(
  321. 'command' => 'restripe',
  322. 'selector' => '#restripe_table',
  323. );
  324. $this->assertCommand($commands, $expected, "'restripe' AJAX command issued with correct selector");
  325. // Tests the 'settings' command.
  326. $commands = $this->drupalPostAJAX($form_path, $edit, array('op' => t("AJAX 'settings' command")));
  327. $expected = array(
  328. 'command' => 'settings',
  329. 'settings' => array('ajax_forms_test' => array('foo' => 42)),
  330. );
  331. $this->assertCommand($commands, $expected, "'settings' AJAX command issued with correct data");
  332. }
  333. }
  334. /**
  335. * Test that $form_state['values'] is properly delivered to $ajax['callback'].
  336. */
  337. class AJAXFormValuesTestCase extends AJAXTestCase {
  338. public static function getInfo() {
  339. return array(
  340. 'name' => 'AJAX command form values',
  341. 'description' => 'Tests that form values are properly delivered to AJAX callbacks.',
  342. 'group' => 'AJAX',
  343. );
  344. }
  345. function setUp() {
  346. parent::setUp();
  347. $this->web_user = $this->drupalCreateUser(array('access content'));
  348. $this->drupalLogin($this->web_user);
  349. }
  350. /**
  351. * Create a simple form, then POST to system/ajax to change to it.
  352. */
  353. function testSimpleAJAXFormValue() {
  354. // Verify form values of a select element.
  355. foreach (array('red', 'green', 'blue') as $item) {
  356. $edit = array(
  357. 'select' => $item,
  358. );
  359. $commands = $this->drupalPostAJAX('ajax_forms_test_get_form', $edit, 'select');
  360. $expected = array(
  361. 'command' => 'data',
  362. 'value' => $item,
  363. );
  364. $this->assertCommand($commands, $expected, "verification of AJAX form values from a selectbox issued with a correct value");
  365. }
  366. // Verify form values of a checkbox element.
  367. foreach (array(FALSE, TRUE) as $item) {
  368. $edit = array(
  369. 'checkbox' => $item,
  370. );
  371. $commands = $this->drupalPostAJAX('ajax_forms_test_get_form', $edit, 'checkbox');
  372. $expected = array(
  373. 'command' => 'data',
  374. 'value' => (int) $item,
  375. );
  376. $this->assertCommand($commands, $expected, "verification of AJAX form values from a checkbox issued with a correct value");
  377. }
  378. }
  379. }
  380. /**
  381. * Tests that Ajax-enabled forms work when multiple instances of the same form are on a page.
  382. */
  383. class AJAXMultiFormTestCase extends AJAXTestCase {
  384. public static function getInfo() {
  385. return array(
  386. 'name' => 'AJAX multi form',
  387. 'description' => 'Tests that AJAX-enabled forms work when multiple instances of the same form are on a page.',
  388. 'group' => 'AJAX',
  389. );
  390. }
  391. function setUp() {
  392. parent::setUp(array('form_test'));
  393. // Create a multi-valued field for 'page' nodes to use for Ajax testing.
  394. $field_name = 'field_ajax_test';
  395. $field = array(
  396. 'field_name' => $field_name,
  397. 'type' => 'text',
  398. 'cardinality' => FIELD_CARDINALITY_UNLIMITED,
  399. );
  400. field_create_field($field);
  401. $instance = array(
  402. 'field_name' => $field_name,
  403. 'entity_type' => 'node',
  404. 'bundle' => 'page',
  405. );
  406. field_create_instance($instance);
  407. // Login a user who can create 'page' nodes.
  408. $this->web_user = $this->drupalCreateUser(array('create page content'));
  409. $this->drupalLogin($this->web_user);
  410. }
  411. /**
  412. * Test that a page with the 'page_node_form' included twice works correctly.
  413. */
  414. function testMultiForm() {
  415. // HTML IDs for elements within the field are potentially modified with
  416. // each Ajax submission, but these variables are stable and help target the
  417. // desired elements.
  418. $field_name = 'field_ajax_test';
  419. $field_xpaths = array(
  420. 'page-node-form' => '//form[@id="page-node-form"]//div[contains(@class, "field-name-field-ajax-test")]',
  421. 'page-node-form--2' => '//form[@id="page-node-form--2"]//div[contains(@class, "field-name-field-ajax-test")]',
  422. );
  423. $button_name = $field_name . '_add_more';
  424. $button_value = t('Add another item');
  425. $button_xpath_suffix = '//input[@name="' . $button_name . '"]';
  426. $field_items_xpath_suffix = '//input[@type="text"]';
  427. // Ensure the initial page contains both node forms and the correct number
  428. // of field items and "add more" button for the multi-valued field within
  429. // each form.
  430. $this->drupalGet('form-test/two-instances-of-same-form');
  431. foreach ($field_xpaths as $form_html_id => $field_xpath) {
  432. $this->assert(count($this->xpath($field_xpath . $field_items_xpath_suffix)) == 1, t('Found the correct number of field items on the initial page.'));
  433. $this->assertFieldByXPath($field_xpath . $button_xpath_suffix, NULL, t('Found the "add more" button on the initial page.'));
  434. }
  435. $this->assertNoDuplicateIds(t('Initial page contains unique IDs'), 'Other');
  436. // Submit the "add more" button of each form twice. After each corresponding
  437. // page update, ensure the same as above.
  438. foreach ($field_xpaths as $form_html_id => $field_xpath) {
  439. for ($i = 0; $i < 2; $i++) {
  440. $this->drupalPostAJAX(NULL, array(), array($button_name => $button_value), 'system/ajax', array(), array(), $form_html_id);
  441. $this->assert(count($this->xpath($field_xpath . $field_items_xpath_suffix)) == $i+2, t('Found the correct number of field items after an AJAX submission.'));
  442. $this->assertFieldByXPath($field_xpath . $button_xpath_suffix, NULL, t('Found the "add more" button after an AJAX submission.'));
  443. $this->assertNoDuplicateIds(t('Updated page contains unique IDs'), 'Other');
  444. }
  445. }
  446. }
  447. }
  448. /**
  449. * Miscellaneous Ajax tests using ajax_test module.
  450. */
  451. class AJAXElementValidation extends AJAXTestCase {
  452. public static function getInfo() {
  453. return array(
  454. 'name' => 'Miscellaneous AJAX tests',
  455. 'description' => 'Various tests of AJAX behavior',
  456. 'group' => 'AJAX',
  457. );
  458. }
  459. /**
  460. * Try to post an Ajax change to a form that has a validated element.
  461. *
  462. * The drivertext field is Ajax-enabled. An additional field is not, but
  463. * is set to be a required field. In this test the required field is not
  464. * filled in, and we want to see if the activation of the "drivertext"
  465. * Ajax-enabled field fails due to the required field being empty.
  466. */
  467. function testAJAXElementValidation() {
  468. $web_user = $this->drupalCreateUser();
  469. $edit = array('drivertext' => t('some dumb text'));
  470. // Post with 'drivertext' as the triggering element.
  471. $post_result = $this->drupalPostAJAX('ajax_validation_test', $edit, 'drivertext');
  472. // Look for a validation failure in the resultant JSON.
  473. $this->assertNoText(t('Error message'), "No error message in resultant JSON");
  474. $this->assertText('ajax_forms_test_validation_form_callback invoked', 'The correct callback was invoked');
  475. }
  476. }