MongoCursorTest.php 12 KB

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