MongoCursorTest.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. <?php
  2. namespace Alcaeus\MongoDbAdapter\Tests\Mongo;
  3. use Alcaeus\MongoDbAdapter\Tests\TestCase;
  4. use Alcaeus\MongoDbAdapter\TypeConverter;
  5. use MongoDB\Driver\ReadPreference;
  6. use MongoDB\Model\BSONDocument;
  7. use MongoDB\Operation\Find;
  8. /**
  9. * @author alcaeus <alcaeus@alcaeus.org>
  10. */
  11. class MongoCursorTest extends TestCase
  12. {
  13. public function testSerialize()
  14. {
  15. $this->prepareData();
  16. $cursor = $this->getCollection()->find(['foo' => 'bar']);
  17. $this->assertInternalType('string', serialize($cursor));
  18. }
  19. public function testCursorConvertsTypes()
  20. {
  21. $this->prepareData();
  22. $collection = $this->getCollection();
  23. $cursor = $collection->find(['foo' => 'bar']);
  24. $this->assertCount(2, $cursor);
  25. $iterated = 0;
  26. foreach ($cursor as $key => $item) {
  27. $this->assertSame($iterated, $cursor->info()['at']);
  28. $this->assertInstanceOf('MongoId', $item['_id']);
  29. $this->assertEquals($key, (string) $item['_id']);
  30. $this->assertSame('bar', $item['foo']);
  31. $iterated++;
  32. }
  33. $this->assertSame(2, $iterated);
  34. }
  35. public function testCount()
  36. {
  37. $this->prepareData();
  38. $collection = $this->getCollection();
  39. $cursor = $collection->find(['foo' => 'bar'])->limit(1);
  40. $this->assertSame(2, $cursor->count());
  41. $this->assertSame(1, $cursor->count(true));
  42. }
  43. public function testCountCannotConnect()
  44. {
  45. $client = $this->getClient(['connect' => false], 'mongodb://localhost:28888');
  46. $cursor = $client->selectCollection('mongo-php-adapter', 'test')->find();
  47. $this->setExpectedException('MongoConnectionException');
  48. $cursor->count();
  49. }
  50. public function testCountAfterIteration()
  51. {
  52. $this->prepareData();
  53. $collection = $this->getCollection();
  54. $cursor = $collection->find(['foo' => 'bar']);
  55. // Ensure the generator is consumed and thus closed
  56. iterator_to_array($cursor);
  57. $this->assertSame(2, $cursor->count(true));
  58. }
  59. public function testNextStartsWithFirstItem()
  60. {
  61. $this->prepareData();
  62. $collection = $this->getCollection();
  63. $cursor = $collection->find(['foo' => 'bar']);
  64. $this->assertTrue($cursor->hasNext());
  65. $item = $cursor->getNext();
  66. $this->assertNotNull($item);
  67. $this->assertInstanceOf('MongoId', $item['_id']);
  68. $this->assertSame('bar', $item['foo']);
  69. $this->assertTrue($cursor->hasNext());
  70. $item = $cursor->getNext();
  71. $this->assertNotNull($item);
  72. $this->assertInstanceOf('MongoId', $item['_id']);
  73. $this->assertSame('bar', $item['foo']);
  74. $this->assertFalse($cursor->hasNext());
  75. $item = $cursor->getNext();
  76. $this->assertNull($item);
  77. $cursor->reset();
  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. $item = $cursor->getNext();
  84. $this->assertNotNull($item);
  85. $this->assertInstanceOf('MongoId', $item['_id']);
  86. $this->assertSame('bar', $item['foo']);
  87. }
  88. public function testIteratorInterface()
  89. {
  90. $this->prepareData();
  91. $collection = $this->getCollection();
  92. $cursor = $collection->find(['foo' => 'bar']);
  93. $this->assertFalse($cursor->valid(), 'Cursor should be invalid to start with');
  94. $this->assertNull($cursor->current(), 'Cursor should be invalid to start with');
  95. $this->assertNull($cursor->key(), 'Cursor should be invalid to start with');
  96. $cursor->next();
  97. $this->assertTrue($cursor->valid(), 'Cursor should be valid');
  98. $item = $cursor->current();
  99. $this->assertNotNull($item);
  100. $this->assertInstanceOf('MongoId', $item['_id']);
  101. $this->assertSame('bar', $item['foo']);
  102. $cursor->next();
  103. $item = $cursor->current();
  104. $this->assertNotNull($item);
  105. $this->assertInstanceOf('MongoId', $item['_id']);
  106. $this->assertSame('bar', $item['foo']);
  107. $cursor->next();
  108. $this->assertNull($cursor->current(), 'Cursor should return null at the end');
  109. $this->assertFalse($cursor->valid(), 'Cursor should be invalid');
  110. $cursor->rewind();
  111. $item = $cursor->current();
  112. $this->assertNotNull($item);
  113. $this->assertInstanceOf('MongoId', $item['_id']);
  114. $this->assertSame('bar', $item['foo']);
  115. }
  116. /**
  117. * @dataProvider getCursorOptions
  118. */
  119. public function testCursorAppliesOptions($checkOptionCallback, \Closure $applyOptionCallback = null)
  120. {
  121. $this->skipTestIf(extension_loaded('mongo'));
  122. $query = ['foo' => 'bar'];
  123. $projection = ['_id' => false, 'foo' => true];
  124. $collectionMock = $this->getCollectionMock();
  125. $collectionMock
  126. ->expects($this->once())
  127. ->method('find')
  128. ->with($this->equalTo(TypeConverter::fromLegacy($query)), $this->callback($checkOptionCallback))
  129. ->will($this->returnValue(new \ArrayIterator([])));
  130. $collection = $this->getCollection('test');
  131. $cursor = $collection->find($query, $projection);
  132. // Replace the original MongoDB collection with our mock
  133. $reflectionProperty = new \ReflectionProperty($cursor, 'collection');
  134. $reflectionProperty->setAccessible(true);
  135. $reflectionProperty->setValue($cursor, $collectionMock);
  136. if ($applyOptionCallback !== null) {
  137. $applyOptionCallback($cursor);
  138. }
  139. // Force query by converting to array
  140. iterator_to_array($cursor);
  141. }
  142. public static function getCursorOptions()
  143. {
  144. function getMissingOptionCallback($optionName) {
  145. return function ($value) use ($optionName) {
  146. return
  147. is_array($value) &&
  148. ! array_key_exists($optionName, $value);
  149. };
  150. }
  151. function getBasicCheckCallback($expected, $optionName) {
  152. return function ($value) use ($expected, $optionName) {
  153. return
  154. is_array($value) &&
  155. array_key_exists($optionName, $value) &&
  156. $value[$optionName] == $expected;
  157. };
  158. }
  159. function getModifierCheckCallback($expected, $modifierName) {
  160. return function ($value) use ($expected, $modifierName) {
  161. return
  162. is_array($value) &&
  163. is_array($value['modifiers']) &&
  164. array_key_exists($modifierName, $value['modifiers']) &&
  165. $value['modifiers'][$modifierName] == $expected;
  166. };
  167. }
  168. $tests = [
  169. 'allowPartialResults' => [
  170. getBasicCheckCallback(true, 'allowPartialResults'),
  171. function (\MongoCursor $cursor) {
  172. $cursor->partial(true);
  173. },
  174. ],
  175. 'batchSize' => [
  176. getBasicCheckCallback(10, 'batchSize'),
  177. function (\MongoCursor $cursor) {
  178. $cursor->batchSize(10);
  179. },
  180. ],
  181. 'cursorTypeNonTailable' => [
  182. getMissingOptionCallback('cursorType'),
  183. function (\MongoCursor $cursor) {
  184. $cursor
  185. ->tailable(false)
  186. ->awaitData(true);
  187. },
  188. ],
  189. 'cursorTypeTailable' => [
  190. getBasicCheckCallback(Find::TAILABLE, 'cursorType'),
  191. function (\MongoCursor $cursor) {
  192. $cursor->tailable(true);
  193. },
  194. ],
  195. 'cursorTypeTailableAwait' => [
  196. getBasicCheckCallback(Find::TAILABLE_AWAIT, 'cursorType'),
  197. function (\MongoCursor $cursor) {
  198. $cursor->tailable(true)->awaitData(true);
  199. },
  200. ],
  201. 'hint' => [
  202. getModifierCheckCallback('index_name', '$hint'),
  203. function (\MongoCursor $cursor) {
  204. $cursor->hint('index_name');
  205. },
  206. ],
  207. 'limit' => [
  208. getBasicCheckCallback(5, 'limit'),
  209. function (\MongoCursor $cursor) {
  210. $cursor->limit(5);
  211. }
  212. ],
  213. 'maxTimeMS' => [
  214. getBasicCheckCallback(100, 'maxTimeMS'),
  215. function (\MongoCursor $cursor) {
  216. $cursor->maxTimeMS(100);
  217. },
  218. ],
  219. 'noCursorTimeout' => [
  220. getBasicCheckCallback(true, 'noCursorTimeout'),
  221. function (\MongoCursor $cursor) {
  222. $cursor->immortal(true);
  223. },
  224. ],
  225. 'slaveOkay' => [
  226. getBasicCheckCallback(new ReadPreference(ReadPreference::RP_SECONDARY_PREFERRED), 'readPreference'),
  227. function (\MongoCursor $cursor) {
  228. $cursor->slaveOkay(true);
  229. },
  230. ],
  231. 'slaveOkayWithReadPreferenceSet' => [
  232. getBasicCheckCallback(new ReadPreference(ReadPreference::RP_SECONDARY), 'readPreference'),
  233. function (\MongoCursor $cursor) {
  234. $cursor
  235. ->setReadPreference(\MongoClient::RP_SECONDARY)
  236. ->slaveOkay(true);
  237. },
  238. ],
  239. 'projectionDefaultFields' => [
  240. getBasicCheckCallback(new BSONDocument(['_id' => false, 'foo' => true]), 'projection'),
  241. ],
  242. 'projectionDifferentFields' => [
  243. getBasicCheckCallback(new BSONDocument(['_id' => false, 'foo' => true, 'bar' => true]), 'projection'),
  244. function (\MongoCursor $cursor) {
  245. $cursor->fields(['_id' => false, 'foo' => true, 'bar' => true]);
  246. },
  247. ],
  248. 'readPreferencePrimary' => [
  249. getBasicCheckCallback(new ReadPreference(ReadPreference::RP_PRIMARY), 'readPreference'),
  250. function (\MongoCursor $cursor) {
  251. $cursor->setReadPreference(\MongoClient::RP_PRIMARY);
  252. },
  253. ],
  254. 'skip' => [
  255. getBasicCheckCallback(5, 'skip'),
  256. function (\MongoCursor $cursor) {
  257. $cursor->skip(5);
  258. },
  259. ],
  260. 'sort' => [
  261. getBasicCheckCallback(['foo' => -1], 'sort'),
  262. function (\MongoCursor $cursor) {
  263. $cursor->sort(['foo' => -1]);
  264. },
  265. ],
  266. ];
  267. return $tests;
  268. }
  269. public function testCursorInfo()
  270. {
  271. $this->prepareData();
  272. $collection = $this->getCollection();
  273. $cursor = $collection->find(['foo' => 'bar'], ['_id' => false])->skip(1)->limit(3);
  274. $expected = [
  275. 'ns' => 'mongo-php-adapter.test',
  276. 'limit' => 3,
  277. 'batchSize' => 0,
  278. 'skip' => 1,
  279. 'flags' => 0,
  280. 'query' => ['foo' => 'bar'],
  281. 'fields' => ['_id' => false],
  282. 'started_iterating' => false,
  283. ];
  284. $this->assertSame($expected, $cursor->info());
  285. // Ensure cursor started iterating
  286. iterator_to_array($cursor);
  287. $expected['started_iterating'] = true;
  288. $expected += [
  289. 'id' => 0,
  290. 'at' => 1,
  291. 'numReturned' => 1,
  292. 'server' => 'localhost:27017;-;.;' . getmypid(),
  293. 'host' => 'localhost',
  294. 'port' => 27017,
  295. 'connection_type_desc' => 'STANDALONE'
  296. ];
  297. $this->assertSame($expected, $cursor->info());
  298. }
  299. public function testCursorInfoWithBatchSize()
  300. {
  301. $this->prepareData();
  302. $collection = $this->getCollection();
  303. $cursor = $collection->find(['foo' => 'bar'], ['_id' => false])->skip(1)->limit(3);
  304. $cursor->batchSize(1);
  305. $expected = [
  306. 'ns' => 'mongo-php-adapter.test',
  307. 'limit' => 3,
  308. 'batchSize' => 1,
  309. 'skip' => 1,
  310. 'flags' => 0,
  311. 'query' => ['foo' => 'bar'],
  312. 'fields' => ['_id' => false],
  313. 'started_iterating' => false,
  314. ];
  315. $this->assertSame($expected, $cursor->info());
  316. // Ensure cursor started iterating
  317. iterator_to_array($cursor);
  318. $expected['started_iterating'] = true;
  319. $expected += [
  320. 'id' => 0,
  321. 'at' => 1,
  322. 'numReturned' => 1,
  323. 'server' => 'localhost:27017;-;.;' . getmypid(),
  324. 'host' => 'localhost',
  325. 'port' => 27017,
  326. 'connection_type_desc' => 'STANDALONE'
  327. ];
  328. $this->assertSame($expected, $cursor->info());
  329. }
  330. public function testReadPreferenceIsInherited()
  331. {
  332. $collection = $this->getCollection();
  333. $collection->setReadPreference(\MongoClient::RP_SECONDARY, [['a' => 'b']]);
  334. $cursor = $collection->find(['foo' => 'bar']);
  335. $this->assertSame(['type' => \MongoClient::RP_SECONDARY, 'tagsets' => [['a' => 'b']]], $cursor->getReadPreference());
  336. }
  337. /**
  338. * @return \PHPUnit_Framework_MockObject_MockObject
  339. */
  340. protected function getCollectionMock()
  341. {
  342. return $this->getMock('MongoDB\Collection', [], [], '', false);
  343. }
  344. }