Download & Extend

Add an assertArrayEqual method to compare two arrays

Project:Drupal core
Version:8.x-dev
Component:simpletest.module
Category:feature request
Priority:normal
Assigned:Unassigned
Status:needs review
Issue tags:Needs tests

Issue Summary

Problem/Motivation

You still deal with a lot of arrays in drupal, thought it's not totally trivial to compare two arrays (as the order of the keys depense on the insertion).

#1810480: Provide the plugin_id to support views metadata integration for example is one of these issues which adds such a helper method.

Proposed resolution

Add one method to the TestBase.

Comments

#1

Status:active» needs review

There seems to be no specific tests for the assertions, or they are hard to find :)

AttachmentSizeStatusTest resultOperations
drupal-1870786-1.patch1.89 KBIdlePASSED: [[SimpleTest]]: [MySQL] 50,460 pass(es).View details | Re-test

#2

#1: drupal-1870786-1.patch queued for re-testing.

#3

I created such a method for my test suite (in D7). It deepen compares the arrays and provides the trace to the differing elements in the error message:
I've seen this when using PHPunit in another project end wanted this fine granuar approach in Drupal and simpletest.

class Wake2eBaseUnitTestCase extends DrupalUnitTestCase {

  public function assertArrayEqual(array $first, array $second, $message = '', $group = 'Other') {
      $results = $this->_check_test_results($first, $second);
      if (count($results)) {
        $this->assert(false, implode("\n", $results));
      }
  }

  protected function _check_test_results($first = NULL, $second = NULL, $path = '') {
    $results = array();
    if (is_array($first)) {
      if (! is_array($second)) {
        $results[] = "ERROR: \$second is not an array - at $path";
        return $results;
      }

      // Don't run assertEqual() directly, because we need to aggregate
      // teste results
      if (count($first) != count($second)) {
        $results[] = t('Length of array differ (@first != @second) at @path.',
          array('@first' => count($first), '@second' => count($second), '@path' => $path));
        return $results;
      }

      foreach(array_keys($first) as $key) {
        $results += $this->_check_test_results($first[$key], $second[$key], $path."[$key]");
      }
    }
    else {
      // Don't run assertEqual() directly, because we need to aggregate
      // teste results
      if($first != $second) {
        $results[] = t('Value @first is equal to value @second at @path.',
          array('@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE), '@path' => $path));
      }
    }
    return $results;
  }
}

It's not feature complete (but works for me). It needs support for Objects and some other general features...

nobody click here