summaryrefslogtreecommitdiffstats
path: root/core/modules/system/lib/Drupal/system/Tests/Ajax/AjaxTestBase.php
blob: a196f856053d6344b4cbe7ec87e8cd2100aa6292 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<?php

/**
 * @file
 * Definition of Drupal\system\Tests\Ajax\AjaxTestBase.
 */

namespace Drupal\system\Tests\Ajax;

use Drupal\simpletest\WebTestBase;

/**
 * Provides a base class for Ajax tests.
 */
abstract class AjaxTestBase extends WebTestBase {

  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = array('ajax_test', 'ajax_forms_test');

  /**
   * Asserts the array of Ajax commands contains the searched command.
   *
   * The Ajax framework, via the ajax_render() function, returns an array of
   * commands. This array sometimes includes commands automatically provided by
   * the framework in addition to commands returned by a particular page
   * callback. During testing, we're usually interested that a particular
   * command is present, and don't care whether other commands precede or
   * follow the one we're interested in. Additionally, the command we're
   * interested in may include additional data that we're not interested in.
   * Therefore, this function simply asserts that one of the commands in
   * $haystack contains all of the keys and values in $needle. Furthermore, if
   * $needle contains a 'settings' key with an array value, we simply assert
   * that all keys and values within that array are present in the command we're
   * checking, and do not consider it a failure if the actual command contains
   * additional settings that aren't part of $needle.
   *
   * @param $haystack
   *   An array of Ajax commands returned by the server.
   * @param $needle
   *   Array of info we're expecting in one of those commands.
   * @param $message
   *   An assertion message.
   */
  protected function assertCommand($haystack, $needle, $message) {
    $found = FALSE;
    foreach ($haystack as $command) {
      // If the command has additional settings that we're not testing for, do
      // not consider that a failure.
      if (isset($command['settings']) && is_array($command['settings']) && isset($needle['settings']) && is_array($needle['settings'])) {
        $command['settings'] = array_intersect_key($command['settings'], $needle['settings']);
      }
      // If the command has additional data that we're not testing for, do not
      // consider that a failure. Also, == instead of ===, because we don't
      // require the key/value pairs to be in any particular order
      // (http://www.php.net/manual/language.operators.array.php).
      if (array_intersect_key($command, $needle) == $needle) {
        $found = TRUE;
        break;
      }
    }
    $this->assertTrue($found, $message);
  }
}