MongoCursorTest.php 12 KB

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