Skip to content

Commit dbc6883

Browse files
committed
Normalize BSON arrays and documents before assertEquals()
1 parent ad08e06 commit dbc6883

File tree

1 file changed

+48
-3
lines changed

1 file changed

+48
-3
lines changed

tests/FunctionalTestCase.php

Lines changed: 48 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
use MongoDB\Driver\Cursor;
77
use MongoDB\Driver\Manager;
88
use MongoDB\Driver\ReadPreference;
9+
use MongoDB\Model\BSONDocument;
910
use InvalidArgumentException;
1011
use stdClass;
1112
use Traversable;
@@ -42,8 +43,8 @@ protected function assertCommandSucceeded($document)
4243
protected function assertSameDocument($expectedDocument, $actualDocument)
4344
{
4445
$this->assertEquals(
45-
is_object($expectedDocument) ? (array) $expectedDocument : $expectedDocument,
46-
is_object($actualDocument) ? (array) $actualDocument : $actualDocument
46+
$this->normalizeBSON($expectedDocument),
47+
$this->normalizeBSON($actualDocument)
4748
);
4849
}
4950

@@ -58,7 +59,7 @@ protected function assertSameDocuments(array $expectedDocuments, $actualDocument
5859
}
5960

6061
$normalizeRootDocuments = function($document) {
61-
return is_object($document) ? (array) $document : $document;
62+
return $this->normalizeBSON($document);
6263
};
6364

6465
$this->assertEquals(
@@ -85,4 +86,48 @@ protected function getServerVersion(ReadPreference $readPreference = null)
8586

8687
return $document['version'];
8788
}
89+
90+
/**
91+
* Normalizes a BSON document or array for use with assertEquals().
92+
*
93+
* The argument will be converted to a BSONArray or BSONDocument based on
94+
* its type and keys. Document fields will be sorted alphabetically. Each
95+
* value within the array or document will then be normalized recursively.
96+
*
97+
* @param array|object $bson
98+
* @return BSONDocument|BSONArray
99+
* @throws InvalidArgumentException if $bson is not an array or object
100+
*/
101+
private function normalizeBSON($bson)
102+
{
103+
if ( ! is_array($bson) && ! is_object($bson)) {
104+
throw new InvalidArgumentException('$bson is not an array or object');
105+
}
106+
107+
if ($bson instanceof BSONArray || (is_array($bson) && $bson === array_values($bson))) {
108+
if ( ! $bson instanceof BSONArray) {
109+
$bson = new BSONArray($bson);
110+
}
111+
} else {
112+
if ( ! $bson instanceof BSONDocument) {
113+
$bson = new BSONDocument((array) $bson);
114+
}
115+
116+
$bson->ksort();
117+
}
118+
119+
foreach ($bson as $key => $value) {
120+
if ($value instanceof BSONArray || (is_array($value) && $value === array_values($value))) {
121+
$bson[$key] = $this->normalizeBSON($value);
122+
continue;
123+
}
124+
125+
if ($value instanceof stdClass || $value instanceof BSONDocument || is_array($value)) {
126+
$bson[$key] = $this->normalizeBSON($value);
127+
continue;
128+
}
129+
}
130+
131+
return $bson;
132+
}
88133
}

0 commit comments

Comments
 (0)