MongoCursorTest.php 12 KB

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