Skip to content

Commit

Permalink
magento/web-api-test-recursive-array-comparison
Browse files Browse the repository at this point in the history
-Added a function to WebApi Test framework for recursively comparing two arrays
-Modified CategoryManagementTest to remove need for array_replace_recursive
  • Loading branch information
jekabs committed Aug 10, 2020
1 parent 4b6cdb7 commit 9cf55e5
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -766,4 +766,60 @@ protected function assertWebApiCallErrors(array $serviceInfo, array $data, array
}
}
}

/**
* Compare arrays recursively regardless of nesting.
* Can compare arrays that have both one level and n-level nesting.
* ```
* [
* 'products' => [
* 'items' => [
* [
* 'sku' => 'bundle-product',
* 'type_id' => 'bundle',
* 'items' => [
* [
* 'title' => 'Bundle Product Items',
* 'sku' => 'bundle-product',
* 'options' => [
* [
* 'price' => 2.75,
* 'label' => 'Simple Product',
* 'product' => [
* 'name' => 'Simple Product',
* 'sku' => 'simple',
* ]
* ]
* ]
* ]
* ];
* ```
*
* @param array $expected
* @param array $actual
* @return array
*/
public function compareArraysRecursively(array $expected, array $actual): array
{
$diffResult = [];

foreach ($expected as $key => $value) {
if (array_key_exists($key, $actual)) {
if (is_array($value)) {
$recursiveDiff = $this->compareArraysRecursively($value, $actual[$key]);
if (!empty($recursiveDiff)) {
$diffResult[$key] = $recursiveDiff;
}
} else {
if (!in_array($value, $actual, true)) {
$diffResult[$key] = $value;
}
}
} else {
$diffResult[$key] = $value;
}
}

return $diffResult;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,8 @@ public function testTree($rootCategoryId, $depth, $expected)
]
];
$result = $this->_webApiCall($serviceInfo, $requestData);
$expected = array_replace_recursive($result, $expected);
$this->assertEquals($expected, $result);
$diff = $this->compareArraysRecursively($expected, $result);
self::assertEquals([], $diff, "Actual categories response doesn't equal expected data");
}

/**
Expand Down

0 comments on commit 9cf55e5

Please sign in to comment.