Projet

Général

Profil

Paste
Télécharger (22,5 ko) Statistiques
| Branche: | Révision:

root / htmltest / modules / simpletest / tests / ajax.test @ 85ad3d82

1
<?php
2

    
3
class AJAXTestCase extends DrupalWebTestCase {
4
  function setUp() {
5
    $modules = func_get_args();
6
    if (isset($modules[0]) && is_array($modules[0])) {
7
      $modules = $modules[0];
8
    }
9
    parent::setUp(array_unique(array_merge(array('ajax_test', 'ajax_forms_test'), $modules)));
10
  }
11

    
12
  /**
13
   * Assert that a command with the required properties exists within the array of Ajax commands returned by the server.
14
   *
15
   * The Ajax framework, via the ajax_deliver() and ajax_render() functions,
16
   * returns an array of commands. This array sometimes includes commands
17
   * automatically provided by the framework in addition to commands returned by
18
   * a particular page callback. During testing, we're usually interested that a
19
   * particular command is present, and don't care whether other commands
20
   * precede or follow the one we're interested in. Additionally, the command
21
   * we're interested in may include additional data that we're not interested
22
   * in. Therefore, this function simply asserts that one of the commands in
23
   * $haystack contains all of the keys and values in $needle. Furthermore, if
24
   * $needle contains a 'settings' key with an array value, we simply assert
25
   * that all keys and values within that array are present in the command we're
26
   * checking, and do not consider it a failure if the actual command contains
27
   * additional settings that aren't part of $needle.
28
   *
29
   * @param $haystack
30
   *   An array of Ajax commands returned by the server.
31
   * @param $needle
32
   *   Array of info we're expecting in one of those commands.
33
   * @param $message
34
   *   An assertion message.
35
   */
36
  protected function assertCommand($haystack, $needle, $message) {
37
    $found = FALSE;
38
    foreach ($haystack as $command) {
39
      // If the command has additional settings that we're not testing for, do
40
      // not consider that a failure.
41
      if (isset($command['settings']) && is_array($command['settings']) && isset($needle['settings']) && is_array($needle['settings'])) {
42
        $command['settings'] = array_intersect_key($command['settings'], $needle['settings']);
43
      }
44
      // If the command has additional data that we're not testing for, do not
45
      // consider that a failure. Also, == instead of ===, because we don't
46
      // require the key/value pairs to be in any particular order
47
      // (http://www.php.net/manual/en/language.operators.array.php).
48
      if (array_intersect_key($command, $needle) == $needle) {
49
        $found = TRUE;
50
        break;
51
      }
52
    }
53
    $this->assertTrue($found, $message);
54
  }
55
}
56

    
57
/**
58
 * Tests primary Ajax framework functions.
59
 */
60
class AJAXFrameworkTestCase extends AJAXTestCase {
61
  protected $profile = 'testing';
62

    
63
  public static function getInfo() {
64
    return array(
65
      'name' => 'AJAX framework',
66
      'description' => 'Performs tests on AJAX framework functions.',
67
      'group' => 'AJAX',
68
    );
69
  }
70

    
71
  /**
72
   * Test that ajax_render() returns JavaScript settings generated during the page request.
73
   *
74
   * @todo Add tests to ensure that ajax_render() returns commands for new CSS
75
   *   and JavaScript files to be loaded by the page. See
76
   *   http://drupal.org/node/561858.
77
   */
78
  function testAJAXRender() {
79
    $commands = $this->drupalGetAJAX('ajax-test/render');
80

    
81
    // Verify that there is a command to load settings added with
82
    // drupal_add_js().
83
    $expected = array(
84
      'command' => 'settings',
85
      'settings' => array('basePath' => base_path(), 'ajax' => 'test'),
86
    );
87
    $this->assertCommand($commands, $expected, t('ajax_render() loads settings added with drupal_add_js().'));
88

    
89
    // Verify that Ajax settings are loaded for #type 'link'.
90
    $this->drupalGet('ajax-test/link');
91
    $settings = $this->drupalGetSettings();
92
    $this->assertEqual($settings['ajax']['ajax-link']['url'], url('filter/tips'));
93
    $this->assertEqual($settings['ajax']['ajax-link']['wrapper'], 'block-system-main');
94
  }
95

    
96
  /**
97
   * Test behavior of ajax_render_error().
98
   */
99
  function testAJAXRenderError() {
100
    // Verify default error message.
101
    $commands = $this->drupalGetAJAX('ajax-test/render-error');
102
    $expected = array(
103
      'command' => 'alert',
104
      'text' => t('An error occurred while handling the request: The server received invalid input.'),
105
    );
106
    $this->assertCommand($commands, $expected, t('ajax_render_error() invokes alert command.'));
107

    
108
    // Verify custom error message.
109
    $edit = array(
110
      'message' => 'Custom error message.',
111
    );
112
    $commands = $this->drupalGetAJAX('ajax-test/render-error', array('query' => $edit));
113
    $expected = array(
114
      'command' => 'alert',
115
      'text' => $edit['message'],
116
    );
117
     $this->assertCommand($commands, $expected, t('Custom error message is output.'));
118
  }
119

    
120
  /**
121
   * Test that new JavaScript and CSS files added during an AJAX request are returned.
122
   */
123
  function testLazyLoad() {
124
    $expected = array(
125
      'setting_name' => 'ajax_forms_test_lazy_load_form_submit',
126
      'setting_value' => 'executed',
127
      'css' => drupal_get_path('module', 'system') . '/system.admin.css',
128
      'js' => drupal_get_path('module', 'system') . '/system.js',
129
    );
130
    // @todo D8: Add a drupal_css_defaults() helper function.
131
    $expected_css_html = drupal_get_css(array($expected['css'] => array(
132
      'type' => 'file',
133
      'group' => CSS_DEFAULT,
134
      'weight' => 0,
135
      'every_page' => FALSE,
136
      'media' => 'all',
137
      'preprocess' => TRUE,
138
      'data' => $expected['css'],
139
      'browsers' => array('IE' => TRUE, '!IE' => TRUE),
140
    )), TRUE);
141
    $expected_js_html = drupal_get_js('header', array($expected['js'] => drupal_js_defaults($expected['js'])), TRUE);
142

    
143
    // Get the base page.
144
    $this->drupalGet('ajax_forms_test_lazy_load_form');
145
    $original_settings = $this->drupalGetSettings();
146
    $original_css = $original_settings['ajaxPageState']['css'];
147
    $original_js = $original_settings['ajaxPageState']['js'];
148

    
149
    // Verify that the base page doesn't have the settings and files that are to
150
    // be lazy loaded as part of the next requests.
151
    $this->assertTrue(!isset($original_settings[$expected['setting_name']]), t('Page originally lacks the %setting, as expected.', array('%setting' => $expected['setting_name'])));
152
    $this->assertTrue(!isset($original_settings[$expected['css']]), t('Page originally lacks the %css file, as expected.', array('%css' => $expected['css'])));
153
    $this->assertTrue(!isset($original_settings[$expected['js']]), t('Page originally lacks the %js file, as expected.', array('%js' => $expected['js'])));
154

    
155
    // Submit the AJAX request without triggering files getting added.
156
    $commands = $this->drupalPostAJAX(NULL, array('add_files' => FALSE), array('op' => t('Submit')));
157
    $new_settings = $this->drupalGetSettings();
158

    
159
    // Verify the setting was not added when not expected.
160
    $this->assertTrue(!isset($new_settings['setting_name']), t('Page still lacks the %setting, as expected.', array('%setting' => $expected['setting_name'])));
161
    // Verify a settings command does not add CSS or scripts to Drupal.settings
162
    // and no command inserts the corresponding tags on the page.
163
    $found_settings_command = FALSE;
164
    $found_markup_command = FALSE;
165
    foreach ($commands as $command) {
166
      if ($command['command'] == 'settings' && (array_key_exists('css', $command['settings']['ajaxPageState']) || array_key_exists('js', $command['settings']['ajaxPageState']))) {
167
        $found_settings_command = TRUE;
168
      }
169
      if (isset($command['data']) && ($command['data'] == $expected_js_html || $command['data'] == $expected_css_html)) {
170
        $found_markup_command = TRUE;
171
      }
172
    }
173
    $this->assertFalse($found_settings_command, t('Page state still lacks the %css and %js files, as expected.', array('%css' => $expected['css'], '%js' => $expected['js'])));
174
    $this->assertFalse($found_markup_command, t('Page still lacks the %css and %js files, as expected.', array('%css' => $expected['css'], '%js' => $expected['js'])));
175

    
176
    // Submit the AJAX request and trigger adding files.
177
    $commands = $this->drupalPostAJAX(NULL, array('add_files' => TRUE), array('op' => t('Submit')));
178
    $new_settings = $this->drupalGetSettings();
179
    $new_css = $new_settings['ajaxPageState']['css'];
180
    $new_js = $new_settings['ajaxPageState']['js'];
181

    
182
    // Verify the expected setting was added.
183
    $this->assertIdentical($new_settings[$expected['setting_name']], $expected['setting_value'], t('Page now has the %setting.', array('%setting' => $expected['setting_name'])));
184

    
185
    // Verify the expected CSS file was added, both to Drupal.settings, and as
186
    // an AJAX command for inclusion into the HTML.
187
    $this->assertEqual($new_css, $original_css + array($expected['css'] => 1), t('Page state now has the %css file.', array('%css' => $expected['css'])));
188
    $this->assertCommand($commands, array('data' => $expected_css_html), t('Page now has the %css file.', array('%css' => $expected['css'])));
189

    
190
    // Verify the expected JS file was added, both to Drupal.settings, and as
191
    // an AJAX command for inclusion into the HTML. By testing for an exact HTML
192
    // string containing the SCRIPT tag, we also ensure that unexpected
193
    // JavaScript code, such as a jQuery.extend() that would potentially clobber
194
    // rather than properly merge settings, didn't accidentally get added.
195
    $this->assertEqual($new_js, $original_js + array($expected['js'] => 1), t('Page state now has the %js file.', array('%js' => $expected['js'])));
196
    $this->assertCommand($commands, array('data' => $expected_js_html), t('Page now has the %js file.', array('%js' => $expected['js'])));
197
  }
198

    
199
  /**
200
   * Tests that overridden CSS files are not added during lazy load.
201
   */
202
  function testLazyLoadOverriddenCSS() {
203
    // The test theme overrides system.base.css without an implementation,
204
    // thereby removing it.
205
    theme_enable(array('test_theme'));
206
    variable_set('theme_default', 'test_theme');
207

    
208
    // This gets the form, and emulates an Ajax submission on it, including
209
    // adding markup to the HEAD and BODY for any lazy loaded JS/CSS files.
210
    $this->drupalPostAJAX('ajax_forms_test_lazy_load_form', array('add_files' => TRUE), array('op' => t('Submit')));
211

    
212
    // Verify that the resulting HTML does not load the overridden CSS file.
213
    // We add a "?" to the assertion, because Drupal.settings may include
214
    // information about the file; we only really care about whether it appears
215
    // in a LINK or STYLE tag, for which Drupal always adds a query string for
216
    // cache control.
217
    $this->assertNoText('system.base.css?', 'Ajax lazy loading does not add overridden CSS files.');
218
  }
219
}
220

    
221
/**
222
 * Tests Ajax framework commands.
223
 */
224
class AJAXCommandsTestCase extends AJAXTestCase {
225
  public static function getInfo() {
226
    return array(
227
      'name' => 'AJAX commands',
228
      'description' => 'Performs tests on AJAX framework commands.',
229
      'group' => 'AJAX',
230
    );
231
  }
232

    
233
  /**
234
   * Test the various Ajax Commands.
235
   */
236
  function testAJAXCommands() {
237
    $form_path = 'ajax_forms_test_ajax_commands_form';
238
    $web_user = $this->drupalCreateUser(array('access content'));
239
    $this->drupalLogin($web_user);
240

    
241
    $edit = array();
242

    
243
    // Tests the 'after' command.
244
    $commands = $this->drupalPostAJAX($form_path, $edit, array('op' => t("AJAX 'After': Click to put something after the div")));
245
    $expected = array(
246
      'command' => 'insert',
247
      'method' => 'after',
248
      'data' => 'This will be placed after',
249
    );
250
    $this->assertCommand($commands, $expected, "'after' AJAX command issued with correct data");
251

    
252
    // Tests the 'alert' command.
253
    $commands = $this->drupalPostAJAX($form_path, $edit, array('op' => t("AJAX 'Alert': Click to alert")));
254
    $expected = array(
255
      'command' => 'alert',
256
      'text' => 'Alert',
257
    );
258
    $this->assertCommand($commands, $expected, "'alert' AJAX Command issued with correct text");
259

    
260
    // Tests the 'append' command.
261
    $commands = $this->drupalPostAJAX($form_path, $edit, array('op' => t("AJAX 'Append': Click to append something")));
262
    $expected = array(
263
      'command' => 'insert',
264
      'method' => 'append',
265
      'data' => 'Appended text',
266
    );
267
    $this->assertCommand($commands, $expected, "'append' AJAX command issued with correct data");
268

    
269
    // Tests the 'before' command.
270
    $commands = $this->drupalPostAJAX($form_path, $edit, array('op' => t("AJAX 'before': Click to put something before the div")));
271
    $expected = array(
272
      'command' => 'insert',
273
      'method' => 'before',
274
      'data' => 'Before text',
275
    );
276
    $this->assertCommand($commands, $expected, "'before' AJAX command issued with correct data");
277

    
278
    // Tests the 'changed' command.
279
    $commands = $this->drupalPostAJAX($form_path, $edit, array('op' => t("AJAX changed: Click to mark div changed.")));
280
    $expected = array(
281
      'command' => 'changed',
282
      'selector' => '#changed_div',
283
    );
284
    $this->assertCommand($commands, $expected, "'changed' AJAX command issued with correct selector");
285

    
286
    // Tests the 'changed' command using the second argument.
287
    $commands = $this->drupalPostAJAX($form_path, $edit, array('op' => t("AJAX changed: Click to mark div changed with asterisk.")));
288
    $expected = array(
289
      'command' => 'changed',
290
      'selector' => '#changed_div',
291
      'asterisk' => '#changed_div_mark_this',
292
    );
293
    $this->assertCommand($commands, $expected, "'changed' AJAX command (with asterisk) issued with correct selector");
294

    
295
    // Tests the 'css' command.
296
    $commands = $this->drupalPostAJAX($form_path, $edit, array('op' => t("Set the the '#box' div to be blue.")));
297
    $expected = array(
298
      'command' => 'css',
299
      'selector' => '#css_div',
300
      'argument' => array('background-color' => 'blue'),
301
    );
302
    $this->assertCommand($commands, $expected, "'css' AJAX command issued with correct selector");
303

    
304
    // Tests the 'data' command.
305
    $commands = $this->drupalPostAJAX($form_path, $edit, array('op' => t("AJAX data command: Issue command.")));
306
    $expected = array(
307
      'command' => 'data',
308
      'name' => 'testkey',
309
      'value' => 'testvalue',
310
    );
311
    $this->assertCommand($commands, $expected, "'data' AJAX command issued with correct key and value");
312

    
313
    // Tests the 'invoke' command.
314
    $commands = $this->drupalPostAJAX($form_path, $edit, array('op' => t("AJAX invoke command: Invoke addClass() method.")));
315
    $expected = array(
316
      'command' => 'invoke',
317
      'method' => 'addClass',
318
      'arguments' => array('error'),
319
    );
320
    $this->assertCommand($commands, $expected, "'invoke' AJAX command issued with correct method and argument");
321

    
322
    // Tests the 'html' command.
323
    $commands = $this->drupalPostAJAX($form_path, $edit, array('op' => t("AJAX html: Replace the HTML in a selector.")));
324
    $expected = array(
325
      'command' => 'insert',
326
      'method' => 'html',
327
      'data' => 'replacement text',
328
    );
329
    $this->assertCommand($commands, $expected, "'html' AJAX command issued with correct data");
330

    
331
    // Tests the 'insert' command.
332
    $commands = $this->drupalPostAJAX($form_path, $edit, array('op' => t("AJAX insert: Let client insert based on #ajax['method'].")));
333
    $expected = array(
334
      'command' => 'insert',
335
      'data' => 'insert replacement text',
336
    );
337
    $this->assertCommand($commands, $expected, "'insert' AJAX command issued with correct data");
338

    
339
    // Tests the 'prepend' command.
340
    $commands = $this->drupalPostAJAX($form_path, $edit, array('op' => t("AJAX 'prepend': Click to prepend something")));
341
    $expected = array(
342
      'command' => 'insert',
343
      'method' => 'prepend',
344
      'data' => 'prepended text',
345
    );
346
    $this->assertCommand($commands, $expected, "'prepend' AJAX command issued with correct data");
347

    
348
    // Tests the 'remove' command.
349
    $commands = $this->drupalPostAJAX($form_path, $edit, array('op' => t("AJAX 'remove': Click to remove text")));
350
    $expected = array(
351
      'command' => 'remove',
352
      'selector' => '#remove_text',
353
    );
354
    $this->assertCommand($commands, $expected, "'remove' AJAX command issued with correct command and selector");
355

    
356
    // Tests the 'restripe' command.
357
    $commands = $this->drupalPostAJAX($form_path, $edit, array('op' => t("AJAX 'restripe' command")));
358
    $expected = array(
359
      'command' => 'restripe',
360
      'selector' => '#restripe_table',
361
    );
362
    $this->assertCommand($commands, $expected, "'restripe' AJAX command issued with correct selector");
363

    
364
    // Tests the 'settings' command.
365
    $commands = $this->drupalPostAJAX($form_path, $edit, array('op' => t("AJAX 'settings' command")));
366
    $expected = array(
367
      'command' => 'settings',
368
      'settings' => array('ajax_forms_test' => array('foo' => 42)),
369
    );
370
    $this->assertCommand($commands, $expected, "'settings' AJAX command issued with correct data");
371
  }
372
}
373

    
374
/**
375
 * Test that $form_state['values'] is properly delivered to $ajax['callback'].
376
 */
377
class AJAXFormValuesTestCase extends AJAXTestCase {
378
  public static function getInfo() {
379
    return array(
380
      'name' => 'AJAX command form values',
381
      'description' => 'Tests that form values are properly delivered to AJAX callbacks.',
382
      'group' => 'AJAX',
383
    );
384
  }
385

    
386
  function setUp() {
387
    parent::setUp();
388

    
389
    $this->web_user = $this->drupalCreateUser(array('access content'));
390
    $this->drupalLogin($this->web_user);
391
  }
392

    
393
  /**
394
   * Create a simple form, then POST to system/ajax to change to it.
395
   */
396
  function testSimpleAJAXFormValue() {
397
    // Verify form values of a select element.
398
    foreach (array('red', 'green', 'blue') as $item) {
399
      $edit = array(
400
        'select' => $item,
401
      );
402
      $commands = $this->drupalPostAJAX('ajax_forms_test_get_form', $edit, 'select');
403
      $expected = array(
404
        'command' => 'data',
405
        'value' => $item,
406
      );
407
      $this->assertCommand($commands, $expected, "verification of AJAX form values from a selectbox issued with a correct value");
408
    }
409

    
410
    // Verify form values of a checkbox element.
411
    foreach (array(FALSE, TRUE) as $item) {
412
      $edit = array(
413
        'checkbox' => $item,
414
      );
415
      $commands = $this->drupalPostAJAX('ajax_forms_test_get_form', $edit, 'checkbox');
416
      $expected = array(
417
        'command' => 'data',
418
        'value' => (int) $item,
419
      );
420
      $this->assertCommand($commands, $expected, "verification of AJAX form values from a checkbox issued with a correct value");
421
    }
422
  }
423
}
424

    
425
/**
426
 * Tests that Ajax-enabled forms work when multiple instances of the same form are on a page.
427
 */
428
class AJAXMultiFormTestCase extends AJAXTestCase {
429
  public static function getInfo() {
430
    return array(
431
      'name' => 'AJAX multi form',
432
      'description' => 'Tests that AJAX-enabled forms work when multiple instances of the same form are on a page.',
433
      'group' => 'AJAX',
434
    );
435
  }
436

    
437
  function setUp() {
438
    parent::setUp(array('form_test'));
439

    
440
    // Create a multi-valued field for 'page' nodes to use for Ajax testing.
441
    $field_name = 'field_ajax_test';
442
    $field = array(
443
      'field_name' => $field_name,
444
      'type' => 'text',
445
      'cardinality' => FIELD_CARDINALITY_UNLIMITED,
446
    );
447
    field_create_field($field);
448
    $instance = array(
449
      'field_name' => $field_name,
450
      'entity_type' => 'node',
451
      'bundle' => 'page',
452
    );
453
    field_create_instance($instance);
454

    
455
    // Login a user who can create 'page' nodes.
456
    $this->web_user = $this->drupalCreateUser(array('create page content'));
457
    $this->drupalLogin($this->web_user);
458
  }
459

    
460
  /**
461
   * Test that a page with the 'page_node_form' included twice works correctly.
462
   */
463
  function testMultiForm() {
464
    // HTML IDs for elements within the field are potentially modified with
465
    // each Ajax submission, but these variables are stable and help target the
466
    // desired elements.
467
    $field_name = 'field_ajax_test';
468
    $field_xpaths = array(
469
      'page-node-form' => '//form[@id="page-node-form"]//div[contains(@class, "field-name-field-ajax-test")]',
470
      'page-node-form--2' => '//form[@id="page-node-form--2"]//div[contains(@class, "field-name-field-ajax-test")]',
471
    );
472
    $button_name = $field_name . '_add_more';
473
    $button_value = t('Add another item');
474
    $button_xpath_suffix = '//input[@name="' . $button_name . '"]';
475
    $field_items_xpath_suffix = '//input[@type="text"]';
476

    
477
    // Ensure the initial page contains both node forms and the correct number
478
    // of field items and "add more" button for the multi-valued field within
479
    // each form.
480
    $this->drupalGet('form-test/two-instances-of-same-form');
481
    foreach ($field_xpaths as $form_html_id => $field_xpath) {
482
      $this->assert(count($this->xpath($field_xpath . $field_items_xpath_suffix)) == 1, t('Found the correct number of field items on the initial page.'));
483
      $this->assertFieldByXPath($field_xpath . $button_xpath_suffix, NULL, t('Found the "add more" button on the initial page.'));
484
    }
485
    $this->assertNoDuplicateIds(t('Initial page contains unique IDs'), 'Other');
486

    
487
    // Submit the "add more" button of each form twice. After each corresponding
488
    // page update, ensure the same as above.
489
    foreach ($field_xpaths as $form_html_id => $field_xpath) {
490
      for ($i = 0; $i < 2; $i++) {
491
        $this->drupalPostAJAX(NULL, array(), array($button_name => $button_value), 'system/ajax', array(), array(), $form_html_id);
492
        $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.'));
493
        $this->assertFieldByXPath($field_xpath . $button_xpath_suffix, NULL, t('Found the "add more" button after an AJAX submission.'));
494
        $this->assertNoDuplicateIds(t('Updated page contains unique IDs'), 'Other');
495
      }
496
    }
497
  }
498
}
499

    
500
/**
501
 * Miscellaneous Ajax tests using ajax_test module.
502
 */
503
class AJAXElementValidation extends AJAXTestCase {
504
  public static function getInfo() {
505
    return array(
506
      'name' => 'Miscellaneous AJAX tests',
507
      'description' => 'Various tests of AJAX behavior',
508
      'group' => 'AJAX',
509
    );
510
  }
511

    
512
  /**
513
   * Try to post an Ajax change to a form that has a validated element.
514
   *
515
   * The drivertext field is Ajax-enabled. An additional field is not, but
516
   * is set to be a required field. In this test the required field is not
517
   * filled in, and we want to see if the activation of the "drivertext"
518
   * Ajax-enabled field fails due to the required field being empty.
519
   */
520
  function testAJAXElementValidation() {
521
    $web_user = $this->drupalCreateUser();
522
    $edit = array('drivertext' => t('some dumb text'));
523

    
524
    // Post with 'drivertext' as the triggering element.
525
    $post_result = $this->drupalPostAJAX('ajax_validation_test', $edit, 'drivertext');
526
    // Look for a validation failure in the resultant JSON.
527
    $this->assertNoText(t('Error message'), "No error message in resultant JSON");
528
    $this->assertText('ajax_forms_test_validation_form_callback invoked', 'The correct callback was invoked');
529
  }
530
}