MongoCursorTest.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  1. <?php
  2. namespace Alcaeus\MongoDbAdapter\Tests\Mongo;
  3. use Alcaeus\MongoDbAdapter\Tests\TestCase;
  4. use Alcaeus\MongoDbAdapter\TypeConverter;
  5. use Countable;
  6. use MongoCursorInterface;
  7. use MongoDB\Driver\ReadPreference;
  8. use MongoDB\Model\BSONDocument;
  9. use MongoDB\Operation\Find;
  10. /**
  11. * @author alcaeus <alcaeus@alcaeus.org>
  12. */
  13. class MongoCursorTest extends TestCase
  14. {
  15. public function testSerialize()
  16. {
  17. $this->prepareData();
  18. $cursor = $this->getCollection()->find(['foo' => 'bar']);
  19. $this->assertIsString(serialize($cursor));
  20. }
  21. public function testCursorConvertsTypes()
  22. {
  23. $this->prepareData();
  24. $collection = $this->getCollection();
  25. $cursor = $collection->find(['foo' => 'bar']);
  26. $this->assertCount(2, $cursor);
  27. $this->assertCursorIteration($cursor);
  28. }
  29. public function testCursorHandlesHasNextBeforeIteration()
  30. {
  31. $this->prepareData();
  32. $collection = $this->getCollection();
  33. $cursor = $collection->find(['foo' => 'bar']);
  34. $this->assertTrue($cursor->hasNext());
  35. $this->assertCursorIteration($cursor);
  36. }
  37. private function assertCursorIteration($cursor)
  38. {
  39. $iterated = 0;
  40. foreach ($cursor as $key => $item) {
  41. $this->assertSame($iterated, $cursor->info()['at']);
  42. $this->assertInstanceOf('MongoId', $item['_id']);
  43. $this->assertEquals($key, (string) $item['_id']);
  44. $this->assertSame('bar', $item['foo']);
  45. $iterated++;
  46. }
  47. $this->assertSame(2, $iterated);
  48. }
  49. public function testCount()
  50. {
  51. $this->prepareData();
  52. $collection = $this->getCollection();
  53. $cursor = $collection->find(['foo' => 'bar'])->limit(1);
  54. $this->assertSame(2, $cursor->count());
  55. $this->assertSame(1, $cursor->count(true));
  56. }
  57. public function testCountCannotConnect()
  58. {
  59. $client = $this->getClient(['connect' => false], 'mongodb://localhost:28888');
  60. $cursor = $client->selectCollection('mongo-php-adapter', 'test')->find();
  61. $this->expectException(\MongoConnectionException::class);
  62. $cursor->count();
  63. }
  64. public function testCountAfterIteration()
  65. {
  66. $this->prepareData();
  67. $collection = $this->getCollection();
  68. $cursor = $collection->find(['foo' => 'bar']);
  69. // Ensure the generator is consumed and thus closed
  70. iterator_to_array($cursor);
  71. $this->assertSame(2, $cursor->count(true));
  72. }
  73. public function testNextStartsWithFirstItem()
  74. {
  75. $this->prepareData();
  76. $collection = $this->getCollection();
  77. $cursor = $collection->find(['foo' => 'bar']);
  78. $this->assertTrue($cursor->hasNext());
  79. $item = $cursor->getNext();
  80. $this->assertNotNull($item);
  81. $this->assertInstanceOf('MongoId', $item['_id']);
  82. $this->assertSame('bar', $item['foo']);
  83. $this->assertTrue($cursor->hasNext());
  84. $item = $cursor->getNext();
  85. $this->assertNotNull($item);
  86. $this->assertInstanceOf('MongoId', $item['_id']);
  87. $this->assertSame('bar', $item['foo']);
  88. $this->assertFalse($cursor->hasNext());
  89. $item = $cursor->getNext();
  90. $this->assertNull($item);
  91. $cursor->reset();
  92. $this->assertTrue($cursor->hasNext());
  93. $item = $cursor->getNext();
  94. $this->assertNotNull($item);
  95. $this->assertInstanceOf('MongoId', $item['_id']);
  96. $this->assertSame('bar', $item['foo']);
  97. $item = $cursor->getNext();
  98. $this->assertNotNull($item);
  99. $this->assertInstanceOf('MongoId', $item['_id']);
  100. $this->assertSame('bar', $item['foo']);
  101. }
  102. public function testIteratorInterface()
  103. {
  104. $this->prepareData();
  105. $collection = $this->getCollection();
  106. $cursor = $collection->find(['foo' => 'bar']);
  107. $this->assertFalse($cursor->valid(), 'Cursor should be invalid to start with');
  108. $this->assertNull($cursor->current(), 'Cursor should be invalid to start with');
  109. $this->assertNull($cursor->key(), 'Cursor should be invalid to start with');
  110. $cursor->next();
  111. $this->assertTrue($cursor->valid(), 'Cursor should be valid');
  112. $item = $cursor->current();
  113. $this->assertNotNull($item);
  114. $this->assertInstanceOf('MongoId', $item['_id']);
  115. $this->assertSame('bar', $item['foo']);
  116. $cursor->next();
  117. $item = $cursor->current();
  118. $this->assertNotNull($item);
  119. $this->assertInstanceOf('MongoId', $item['_id']);
  120. $this->assertSame('bar', $item['foo']);
  121. $cursor->next();
  122. $this->assertNull($cursor->current(), 'Cursor should return null at the end');
  123. $this->assertFalse($cursor->valid(), 'Cursor should be invalid');
  124. $cursor->rewind();
  125. $item = $cursor->current();
  126. $this->assertNotNull($item);
  127. $this->assertInstanceOf('MongoId', $item['_id']);
  128. $this->assertSame('bar', $item['foo']);
  129. }
  130. /**
  131. * @dataProvider getCursorOptions
  132. */
  133. public function testCursorAppliesOptions($checkOptionCallback, \Closure $applyOptionCallback = null)
  134. {
  135. $this->skipTestIf(extension_loaded('mongo'));
  136. $query = ['foo' => 'bar'];
  137. $projection = ['_id' => false, 'foo' => true];
  138. $collectionMock = $this->getCollectionMock();
  139. $collectionMock
  140. ->expects($this->once())
  141. ->method('find')
  142. ->with($this->equalTo(TypeConverter::fromLegacy($query)), $this->callback($checkOptionCallback))
  143. ->will($this->returnValue(new \ArrayIterator([])));
  144. $collection = $this->getCollection('test');
  145. $cursor = $collection->find($query, $projection);
  146. // Replace the original MongoDB collection with our mock
  147. $reflectionProperty = new \ReflectionProperty($cursor, 'collection');
  148. $reflectionProperty->setAccessible(true);
  149. $reflectionProperty->setValue($cursor, $collectionMock);
  150. if ($applyOptionCallback !== null) {
  151. $applyOptionCallback($cursor);
  152. }
  153. // Force query by converting to array
  154. iterator_to_array($cursor);
  155. }
  156. public static function getCursorOptions()
  157. {
  158. function getMissingOptionCallback($optionName)
  159. {
  160. return function ($value) use ($optionName) {
  161. return
  162. is_array($value) &&
  163. ! array_key_exists($optionName, $value);
  164. };
  165. }
  166. function getBasicCheckCallback($expected, $optionName)
  167. {
  168. return function ($value) use ($expected, $optionName) {
  169. return
  170. is_array($value) &&
  171. array_key_exists($optionName, $value) &&
  172. $value[$optionName] == $expected;
  173. };
  174. }
  175. function getModifierCheckCallback($expected, $modifierName)
  176. {
  177. return function ($value) use ($expected, $modifierName) {
  178. return
  179. is_array($value) &&
  180. is_array($value['modifiers']) &&
  181. array_key_exists($modifierName, $value['modifiers']) &&
  182. $value['modifiers'][$modifierName] == $expected;
  183. };
  184. }
  185. $tests = [
  186. 'allowPartialResults' => [
  187. getBasicCheckCallback(true, 'allowPartialResults'),
  188. function (\MongoCursor $cursor) {
  189. $cursor->partial(true);
  190. },
  191. ],
  192. 'batchSize' => [
  193. getBasicCheckCallback(10, 'batchSize'),
  194. function (\MongoCursor $cursor) {
  195. $cursor->batchSize(10);
  196. },
  197. ],
  198. 'cursorTypeNonTailable' => [
  199. getMissingOptionCallback('cursorType'),
  200. function (\MongoCursor $cursor) {
  201. $cursor
  202. ->tailable(false)
  203. ->awaitData(true);
  204. },
  205. ],
  206. 'cursorTypeTailable' => [
  207. getBasicCheckCallback(Find::TAILABLE, 'cursorType'),
  208. function (\MongoCursor $cursor) {
  209. $cursor->tailable(true);
  210. },
  211. ],
  212. 'cursorTypeTailableAwait' => [
  213. getBasicCheckCallback(Find::TAILABLE_AWAIT, 'cursorType'),
  214. function (\MongoCursor $cursor) {
  215. $cursor->tailable(true)->awaitData(true);
  216. },
  217. ],
  218. 'hint' => [
  219. getModifierCheckCallback('index_name', '$hint'),
  220. function (\MongoCursor $cursor) {
  221. $cursor->hint('index_name');
  222. },
  223. ],
  224. 'limit' => [
  225. getBasicCheckCallback(5, 'limit'),
  226. function (\MongoCursor $cursor) {
  227. $cursor->limit(5);
  228. }
  229. ],
  230. 'maxTimeMS' => [
  231. getBasicCheckCallback(100, 'maxTimeMS'),
  232. function (\MongoCursor $cursor) {
  233. $cursor->maxTimeMS(100);
  234. },
  235. ],
  236. 'noCursorTimeout' => [
  237. getBasicCheckCallback(true, 'noCursorTimeout'),
  238. function (\MongoCursor $cursor) {
  239. $cursor->immortal(true);
  240. },
  241. ],
  242. 'slaveOkay' => [
  243. getBasicCheckCallback(new ReadPreference(ReadPreference::RP_SECONDARY_PREFERRED), 'readPreference'),
  244. function (\MongoCursor $cursor) {
  245. $cursor->slaveOkay(true);
  246. },
  247. ],
  248. 'slaveOkayWithReadPreferenceSet' => [
  249. getBasicCheckCallback(new ReadPreference(ReadPreference::RP_SECONDARY), 'readPreference'),
  250. function (\MongoCursor $cursor) {
  251. $cursor
  252. ->setReadPreference(\MongoClient::RP_SECONDARY)
  253. ->slaveOkay(true);
  254. },
  255. ],
  256. 'projectionDefaultFields' => [
  257. getBasicCheckCallback(new BSONDocument(['_id' => false, 'foo' => true]), 'projection'),
  258. ],
  259. 'projectionDifferentFields' => [
  260. getBasicCheckCallback(new BSONDocument(['_id' => false, 'foo' => true, 'bar' => true]), 'projection'),
  261. function (\MongoCursor $cursor) {
  262. $cursor->fields(['_id' => false, 'foo' => true, 'bar' => true]);
  263. },
  264. ],
  265. 'readPreferencePrimary' => [
  266. getBasicCheckCallback(new ReadPreference(ReadPreference::RP_PRIMARY), 'readPreference'),
  267. function (\MongoCursor $cursor) {
  268. $cursor->setReadPreference(\MongoClient::RP_PRIMARY);
  269. },
  270. ],
  271. 'skip' => [
  272. getBasicCheckCallback(5, 'skip'),
  273. function (\MongoCursor $cursor) {
  274. $cursor->skip(5);
  275. },
  276. ],
  277. 'sort' => [
  278. getBasicCheckCallback(['foo' => -1], 'sort'),
  279. function (\MongoCursor $cursor) {
  280. $cursor->sort(['foo' => -1]);
  281. },
  282. ],
  283. ];
  284. return $tests;
  285. }
  286. public function testCursorInfo()
  287. {
  288. $this->prepareData();
  289. $collection = $this->getCollection();
  290. $cursor = $collection->find(['foo' => 'bar'], ['_id' => false])->skip(1)->limit(3);
  291. $expected = [
  292. 'ns' => 'mongo-php-adapter.test',
  293. 'limit' => 3,
  294. 'batchSize' => 0,
  295. 'skip' => 1,
  296. 'flags' => 0,
  297. 'query' => ['foo' => 'bar'],
  298. 'fields' => ['_id' => false],
  299. 'started_iterating' => false,
  300. ];
  301. $this->assertSame($expected, $cursor->info());
  302. // Ensure cursor started iterating
  303. iterator_to_array($cursor);
  304. $expected['started_iterating'] = true;
  305. $expected += [
  306. 'id' => 0,
  307. 'at' => 1,
  308. 'numReturned' => 1,
  309. 'server' => 'localhost:27017;-;.;' . getmypid(),
  310. 'host' => 'localhost',
  311. 'port' => 27017,
  312. 'connection_type_desc' => 'STANDALONE'
  313. ];
  314. $this->assertSame($expected, $cursor->info());
  315. }
  316. public function testCursorInfoWithBatchSize()
  317. {
  318. $this->prepareData();
  319. $collection = $this->getCollection();
  320. $cursor = $collection->find(['foo' => 'bar'], ['_id' => false])->skip(1)->limit(3);
  321. $cursor->batchSize(1);
  322. $expected = [
  323. 'ns' => 'mongo-php-adapter.test',
  324. 'limit' => 3,
  325. 'batchSize' => 1,
  326. 'skip' => 1,
  327. 'flags' => 0,
  328. 'query' => ['foo' => 'bar'],
  329. 'fields' => ['_id' => false],
  330. 'started_iterating' => false,
  331. ];
  332. $this->assertSame($expected, $cursor->info());
  333. // Ensure cursor started iterating
  334. iterator_to_array($cursor);
  335. $expected['started_iterating'] = true;
  336. $expected += [
  337. 'id' => 0,
  338. 'at' => 1,
  339. 'numReturned' => 1,
  340. 'server' => 'localhost:27017;-;.;' . getmypid(),
  341. 'host' => 'localhost',
  342. 'port' => 27017,
  343. 'connection_type_desc' => 'STANDALONE'
  344. ];
  345. $this->assertSame($expected, $cursor->info());
  346. }
  347. public function testReadPreferenceIsInherited()
  348. {
  349. $collection = $this->getCollection();
  350. $collection->setReadPreference(\MongoClient::RP_SECONDARY, [['a' => 'b']]);
  351. $cursor = $collection->find(['foo' => 'bar']);
  352. $this->assertSame(['type' => \MongoClient::RP_SECONDARY, 'tagsets' => [['a' => 'b']]], $cursor->getReadPreference());
  353. }
  354. public function testExplain()
  355. {
  356. $this->prepareData();
  357. $collection = $this->getCollection();
  358. $cursor = $collection->find(['foo' => 'bar'], ['_id' => false])->skip(1)->limit(3);
  359. $expected = [
  360. 'queryPlanner' => [
  361. 'plannerVersion' => 1,
  362. 'namespace' => 'mongo-php-adapter.test',
  363. 'indexFilterSet' => false,
  364. 'parsedQuery' => [
  365. 'foo' => ['$eq' => 'bar']
  366. ],
  367. 'winningPlan' => ['$$exists' => true],
  368. 'rejectedPlans' => ['$$exists' => true],
  369. ],
  370. 'executionStats' => [
  371. 'executionSuccess' => true,
  372. 'nReturned' => 1,
  373. 'totalKeysExamined' => 0,
  374. 'totalDocsExamined' => 3,
  375. 'executionStages' => ['$$exists' => true],
  376. 'allPlansExecution' => ['$$exists' => true],
  377. ],
  378. 'serverInfo' => [
  379. 'port' => 27017,
  380. ],
  381. ];
  382. $this->assertMatches($expected, $cursor->explain());
  383. }
  384. public function testExplainWithEmptyProjection()
  385. {
  386. $this->prepareData();
  387. $collection = $this->getCollection();
  388. $cursor = $collection->find(['foo' => 'bar']);
  389. $expected = [
  390. 'queryPlanner' => [
  391. 'plannerVersion' => 1,
  392. 'namespace' => 'mongo-php-adapter.test',
  393. 'indexFilterSet' => false,
  394. 'parsedQuery' => [
  395. 'foo' => ['$eq' => 'bar']
  396. ],
  397. 'winningPlan' => ['$$exists' => true],
  398. 'rejectedPlans' => ['$$exists' => true],
  399. ],
  400. 'executionStats' => [
  401. 'executionSuccess' => true,
  402. 'nReturned' => 2,
  403. 'totalKeysExamined' => 0,
  404. 'totalDocsExamined' => 3,
  405. 'executionStages' => ['$$exists' => true],
  406. 'allPlansExecution' => ['$$exists' => true],
  407. ],
  408. 'serverInfo' => [
  409. 'port' => 27017,
  410. ],
  411. ];
  412. $this->assertMatches($expected, $cursor->explain());
  413. }
  414. public function testExplainConvertsQuery()
  415. {
  416. $this->prepareData();
  417. $collection = $this->getCollection();
  418. $cursor = $collection->find(['foo' => new \MongoRegex('/^b/')]);
  419. $expected = [
  420. 'queryPlanner' => [
  421. 'plannerVersion' => 1,
  422. 'namespace' => 'mongo-php-adapter.test',
  423. 'indexFilterSet' => false,
  424. 'winningPlan' => ['$$exists' => true],
  425. 'rejectedPlans' => ['$$exists' => true],
  426. ],
  427. 'executionStats' => [
  428. 'executionSuccess' => true,
  429. 'nReturned' => 2,
  430. 'totalKeysExamined' => 0,
  431. 'totalDocsExamined' => 3,
  432. 'executionStages' => ['$$exists' => true],
  433. 'allPlansExecution' => ['$$exists' => true],
  434. ],
  435. 'serverInfo' => [
  436. 'port' => 27017,
  437. ],
  438. ];
  439. $this->assertMatches($expected, $cursor->explain());
  440. }
  441. public function testInterfaces()
  442. {
  443. $collection = $this->getCollection();
  444. $cursor = $collection->find();
  445. $this->assertInstanceOf(MongoCursorInterface::class, $cursor);
  446. // The countable interface is necessary for compatibility with PHP 7.3+, but not implemented by MongoCursor
  447. if (! extension_loaded('mongo')) {
  448. $this->assertInstanceOf(Countable::class, $cursor);
  449. }
  450. }
  451. /**
  452. * @return \PHPUnit_Framework_MockObject_MockObject
  453. */
  454. protected function getCollectionMock()
  455. {
  456. return $this->createMock('MongoDB\Collection', [], [], '', false);
  457. }
  458. }