MongoCollectionTest.php 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355
  1. <?php
  2. namespace Alcaeus\MongoDbAdapter\Tests\Mongo;
  3. use MongoDB\Driver\ReadPreference;
  4. use Alcaeus\MongoDbAdapter\Tests\TestCase;
  5. /**
  6. * @author alcaeus <alcaeus@alcaeus.org>
  7. */
  8. class MongoCollectionTest extends TestCase
  9. {
  10. public function testSerialize()
  11. {
  12. $this->assertInternalType('string', serialize($this->getCollection()));
  13. }
  14. public function testGetNestedCollections()
  15. {
  16. $collection = $this->getCollection()->foo->bar;
  17. $this->assertSame('mongo-php-adapter.test.foo.bar', (string) $collection);
  18. }
  19. public function testCreateRecord()
  20. {
  21. $collection = $this->getCollection();
  22. $expected = [
  23. 'ok' => 1.0,
  24. 'n' => 0,
  25. 'err' => null,
  26. 'errmsg' => null,
  27. ];
  28. $document = ['foo' => 'bar'];
  29. $this->assertSame($expected, $collection->insert($document));
  30. $this->assertInstanceOf('MongoId', $document['_id']);
  31. $id = (string) $document['_id'];
  32. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  33. $this->assertSame(1, $newCollection->count());
  34. $object = $newCollection->findOne();
  35. $this->assertNotNull($object);
  36. $this->assertAttributeInstanceOf('MongoDB\BSON\ObjectID', '_id', $object);
  37. $this->assertSame($id, (string) $object->_id);
  38. $this->assertObjectHasAttribute('foo', $object);
  39. $this->assertAttributeSame('bar', 'foo', $object);
  40. }
  41. public function testInsertInvalidData()
  42. {
  43. $this->setExpectedException('PHPUnit_Framework_Error_Warning', 'MongoCollection::insert(): expects parameter 1 to be an array or object, integer given');
  44. $document = 8;
  45. $this->getCollection()->insert($document);
  46. }
  47. public function testInsertEmptyArray()
  48. {
  49. $document = [];
  50. $this->getCollection()->insert($document);
  51. $this->assertSame(1, $this->getCollection()->count());
  52. }
  53. public function testInsertArrayWithNumericKeys()
  54. {
  55. $document = [1 => 'foo'];
  56. $this->getCollection()->insert($document);
  57. $this->assertSame(1, $this->getCollection()->count(['_id' => $document['_id']]));
  58. }
  59. public function testInsertEmptyObject()
  60. {
  61. $document = (object) [];
  62. $this->getCollection()->insert($document);
  63. $this->assertSame(1, $this->getCollection()->count());
  64. }
  65. public function testInsertObjectWithPrivateProperties()
  66. {
  67. $this->setExpectedException('MongoException', 'zero-length keys are not allowed, did you use $ with double quotes?');
  68. $document = new PrivatePropertiesStub();
  69. $this->getCollection()->insert($document);
  70. }
  71. public function testInsertWithInvalidKey()
  72. {
  73. $document = ['*' => 'foo'];
  74. $this->getCollection()->insert($document);
  75. $this->assertSame(1, $this->getCollection()->count(['*' => 'foo']));
  76. }
  77. public function testInsertWithEmptyKey()
  78. {
  79. $this->setExpectedException('MongoException', 'zero-length keys are not allowed, did you use $ with double quotes?');
  80. $document = ['' => 'foo'];
  81. $this->getCollection()->insert($document);
  82. }
  83. public function testInsertWithNumericKey()
  84. {
  85. $document = ['foo'];
  86. $this->getCollection()->insert($document);
  87. $this->assertSame(1, $this->getCollection()->count(['foo']));
  88. }
  89. public function testInsertDuplicate()
  90. {
  91. $collection = $this->getCollection();
  92. $collection->createIndex(['foo' => 1], ['unique' => true]);
  93. $document = ['foo' => 'bar'];
  94. $collection->insert($document);
  95. unset($document['_id']);
  96. $this->setExpectedExceptionRegExp('MongoDuplicateKeyException', '/E11000 duplicate key error .* mongo-php-adapter\.test/');
  97. $collection->insert($document);
  98. }
  99. public function testUnacknowledgedWrite()
  100. {
  101. $document = ['foo' => 'bar'];
  102. $this->assertTrue($this->getCollection()->insert($document, ['w' => 0]));
  103. }
  104. public function testInsertWriteConcernException()
  105. {
  106. $this->setExpectedException(
  107. 'MongoWriteConcernException',
  108. "cannot use 'w' > 1 when a host is not replicated"
  109. );
  110. $document = ['foo' => 'bar'];
  111. $this->getCollection()->insert($document, ['w' => 2]);
  112. }
  113. public function testInsertMany()
  114. {
  115. $expected = [
  116. 'ok' => 1.0,
  117. 'n' => 0,
  118. 'syncMillis' => 0,
  119. 'writtenTo' => null,
  120. 'err' => null,
  121. ];
  122. $documents = [
  123. ['foo' => 'bar'],
  124. ['bar' => 'foo']
  125. ];
  126. $this->assertArraySubset($expected, $this->getCollection()->batchInsert($documents));
  127. foreach ($documents as $document) {
  128. $this->assertInstanceOf('MongoId', $document['_id']);
  129. }
  130. }
  131. public function testInsertManyWithNonNumericKeys()
  132. {
  133. $expected = [
  134. 'ok' => 1.0,
  135. 'n' => 0,
  136. 'syncMillis' => 0,
  137. 'writtenTo' => null,
  138. 'err' => null,
  139. ];
  140. $documents = [
  141. 'a' => ['foo' => 'bar'],
  142. 'b' => ['bar' => 'foo']
  143. ];
  144. $this->assertArraySubset($expected, $this->getCollection()->batchInsert($documents));
  145. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  146. $this->assertSame(2, $newCollection->count());
  147. }
  148. public function testBatchInsertContinuesOnError()
  149. {
  150. $expected = [
  151. 'ok' => 1.0,
  152. 'n' => 0,
  153. 'syncMillis' => 0,
  154. 'writtenTo' => null,
  155. 'err' => null,
  156. ];
  157. $documents = [
  158. 8,
  159. 'b' => ['bar' => 'foo']
  160. ];
  161. $this->assertArraySubset($expected, $this->getCollection()->batchInsert($documents, ['continueOnError' => true]));
  162. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  163. $this->assertSame(1, $newCollection->count());
  164. }
  165. public function testBatchInsertException()
  166. {
  167. $this->setExpectedExceptionRegExp('MongoDuplicateKeyException', '/E11000 duplicate key error .* mongo-php-adapter.test.*_id_/');
  168. $id = new \MongoId();
  169. $documents = [['_id' => $id, 'foo' => 'bar'], ['_id' => $id, 'foo' => 'bleh']];
  170. $this->getCollection()->batchInsert($documents);
  171. }
  172. public function testBatchInsertObjectWithPrivateProperties()
  173. {
  174. $this->setExpectedException('MongoException', 'zero-length keys are not allowed, did you use $ with double quotes?');
  175. $documents = [new PrivatePropertiesStub()];
  176. $this->getCollection()->batchInsert($documents);
  177. }
  178. public function testBatchInsertWithInvalidKey()
  179. {
  180. $documents = [['*' => 'foo']];
  181. $this->getCollection()->batchInsert($documents);
  182. $this->assertSame(1, $this->getCollection()->count(['*' => 'foo']));
  183. }
  184. public function testBatchInsertWithEmptyKey()
  185. {
  186. $this->setExpectedException('MongoException', 'zero-length keys are not allowed, did you use $ with double quotes?');
  187. $documents = [['' => 'foo']];
  188. $this->getCollection()->batchInsert($documents);
  189. }
  190. public function testBatchInsertWithNumericKey()
  191. {
  192. $documents = [['foo']];
  193. $this->getCollection()->batchInsert($documents);
  194. $this->assertSame(1, $this->getCollection()->count(['foo']));
  195. }
  196. public function testBatchInsertEmptyBatchException()
  197. {
  198. $this->setExpectedException('MongoException', 'No write ops were included in the batch');
  199. $documents = [];
  200. $this->getCollection()->batchInsert($documents, ['w' => 2]);
  201. }
  202. public function testUpdateWriteConcern()
  203. {
  204. $this->setExpectedException('MongoWriteConcernException', "cannot use 'w' > 1 when a host is not replicated");
  205. $this->getCollection()->update([], ['$set' => ['foo' => 'bar']], ['w' => 2]);
  206. }
  207. public function testUpdateOne()
  208. {
  209. $document = ['foo' => 'bar'];
  210. $this->getCollection()->insert($document);
  211. // Unset ID to re-insert
  212. unset($document['_id']);
  213. $this->getCollection()->insert($document);
  214. $expected = [
  215. 'ok' => 1.0,
  216. 'nModified' => 1,
  217. 'n' => 1,
  218. 'err' => null,
  219. 'errmsg' => null,
  220. 'updatedExisting' => true,
  221. ];
  222. $result = $this->getCollection()->update(['foo' => 'bar'], ['$set' => ['foo' => 'foo']]);
  223. $this->assertSame($expected, $result);
  224. $this->assertSame(1, $this->getCheckDatabase()->selectCollection('test')->count(['foo' => 'foo']));
  225. }
  226. public function testUpdateReplaceOne()
  227. {
  228. $document = ['foo' => 'bar', 'bar' => 'foo'];
  229. $this->getCollection()->insert($document);
  230. // Unset ID to re-insert
  231. unset($document['_id']);
  232. $this->getCollection()->insert($document);
  233. $expected = [
  234. 'ok' => 1.0,
  235. 'nModified' => 1,
  236. 'n' => 1,
  237. 'err' => null,
  238. 'errmsg' => null,
  239. 'updatedExisting' => true,
  240. ];
  241. $result = $this->getCollection()->update(['foo' => 'bar'], ['foo' => 'foo']);
  242. $this->assertSame($expected, $result);
  243. $this->assertSame(1, $this->getCheckDatabase()->selectCollection('test')->count(['foo' => 'foo']));
  244. $this->assertSame(1, $this->getCheckDatabase()->selectCollection('test')->count(['bar' => 'foo']));
  245. }
  246. public function testUpdateReplaceMultiple()
  247. {
  248. $this->setExpectedExceptionRegExp('MongoWriteConcernException', '/multi update only works with \$ operators/', 9);
  249. $this->getCollection()->update(['foo' => 'bar'], ['foo' => 'foo'], ['multiple' => true]);
  250. }
  251. public function testUpdateDuplicate()
  252. {
  253. $collection = $this->getCollection();
  254. $collection->createIndex(['foo' => 1], ['unique' => 1]);
  255. $document = ['foo' => 'bar'];
  256. $collection->insert($document);
  257. $document = ['foo' => 'foo'];
  258. $collection->insert($document);
  259. $this->setExpectedException('MongoDuplicateKeyException');
  260. $collection->update(['foo' => 'bar'], ['$set' => ['foo' => 'foo']]);
  261. }
  262. public function testUpdateMany()
  263. {
  264. $document = ['change' => true, 'foo' => 'bar'];
  265. $this->getCollection()->insert($document);
  266. unset($document['_id']);
  267. $this->getCollection()->insert($document);
  268. $document = ['change' => true, 'foo' => 'foo'];
  269. $this->getCollection()->insert($document);
  270. $expected = [
  271. 'ok' => 1.0,
  272. 'nModified' => 2,
  273. 'n' => 3,
  274. 'err' => null,
  275. 'errmsg' => null,
  276. 'updatedExisting' => true,
  277. ];
  278. $result = $this->getCollection()->update(['change' => true], ['$set' => ['foo' => 'foo']], ['multiple' => true]);
  279. $this->assertSame($expected, $result);
  280. $this->assertSame(3, $this->getCheckDatabase()->selectCollection('test')->count(['foo' => 'foo']));
  281. }
  282. public function testUnacknowledgedUpdate()
  283. {
  284. $document = ['foo' => 'bar'];
  285. $this->getCollection()->insert($document);
  286. unset($document['_id']);
  287. $this->getCollection()->insert($document);
  288. $this->assertTrue($this->getCollection()->update($document, ['$set' => ['foo' => 'foo']], ['w' => 0]));
  289. }
  290. public function testRemoveMultiple()
  291. {
  292. $document = ['change' => true, 'foo' => 'bar'];
  293. $this->getCollection()->insert($document);
  294. unset($document['_id']);
  295. $this->getCollection()->insert($document);
  296. $document = ['change' => true, 'foo' => 'foo'];
  297. $this->getCollection()->insert($document);
  298. $expected = [
  299. 'ok' => 1.0,
  300. 'n' => 2,
  301. 'err' => null,
  302. 'errmsg' => null,
  303. ];
  304. $result = $this->getCollection()->remove(['foo' => 'bar']);
  305. $this->assertSame($expected, $result);
  306. $this->assertSame(1, $this->getCheckDatabase()->selectCollection('test')->count());
  307. }
  308. public function testRemoveSingle()
  309. {
  310. $document = ['change' => true, 'foo' => 'bar'];
  311. $this->getCollection()->insert($document);
  312. unset($document['_id']);
  313. $this->getCollection()->insert($document);
  314. unset($document['_id']);
  315. $this->getCollection()->insert($document);
  316. $expected = [
  317. 'ok' => 1.0,
  318. 'n' => 1,
  319. 'err' => null,
  320. 'errmsg' => null,
  321. ];
  322. $result = $this->getCollection()->remove(['foo' => 'bar'], ['justOne' => true]);
  323. $this->assertSame($expected, $result);
  324. $this->assertSame(2, $this->getCheckDatabase()->selectCollection('test')->count());
  325. }
  326. public function testRemoveUnacknowledged()
  327. {
  328. $document = ['change' => true, 'foo' => 'bar'];
  329. $this->getCollection()->insert($document);
  330. unset($document['_id']);
  331. $this->getCollection()->insert($document);
  332. unset($document['_id']);
  333. $this->getCollection()->insert($document);
  334. $this->assertTrue($this->getCollection()->remove(['foo' => 'bar'], ['w' => 0]));
  335. }
  336. public function testFindReturnsCursor()
  337. {
  338. $this->prepareData();
  339. $collection = $this->getCollection();
  340. $this->assertInstanceOf('MongoCursor', $collection->find());
  341. }
  342. public function testCount()
  343. {
  344. $this->prepareData();
  345. $collection = $this->getCollection();
  346. $this->assertSame(3, $collection->count());
  347. $this->assertSame(2, $collection->count(['foo' => 'bar']));
  348. }
  349. public function testCountTimeout()
  350. {
  351. $this->failMaxTimeMS();
  352. $this->setExpectedException('MongoExecutionTimeoutException');
  353. $this->getCollection()->count([], ['maxTimeMS' => 1]);
  354. }
  355. public function testFindOne()
  356. {
  357. $this->prepareData();
  358. $document = $this->getCollection()->findOne(['foo' => 'foo'], ['_id' => false]);
  359. $this->assertSame(['foo' => 'foo'], $document);
  360. }
  361. public function testFindOneNotFound()
  362. {
  363. $document = $this->getCollection()->findOne(['foo' => 'foo'], ['_id' => false]);
  364. $this->assertNull($document);
  365. }
  366. public function testFindOneConnectionIssue()
  367. {
  368. $this->setExpectedException('MongoConnectionException');
  369. $client = $this->getClient([], 'mongodb://localhost:28888?connectTimeoutMS=1');
  370. $collection = $client->selectCollection('mongo-php-adapter', 'test');
  371. $collection->findOne();
  372. }
  373. public function testDistinct()
  374. {
  375. $this->prepareData();
  376. $values = $this->getCollection()->distinct('foo');
  377. $this->assertInternalType('array', $values);
  378. sort($values);
  379. $this->assertEquals(['bar', 'foo'], $values);
  380. }
  381. public function testDistinctWithQuery()
  382. {
  383. $this->prepareData();
  384. $values = $this->getCollection()->distinct('foo', ['foo' => 'bar']);
  385. $this->assertInternalType('array', $values);
  386. $this->assertEquals(['bar'], $values);
  387. }
  388. public function testAggregate()
  389. {
  390. $this->skipTestUnless(extension_loaded('mongo'));
  391. $collection = $this->getCollection();
  392. $this->prepareData();
  393. $pipeline = [
  394. [
  395. '$group' => [
  396. '_id' => '$foo',
  397. 'count' => [ '$sum' => 1 ],
  398. ],
  399. ],
  400. [
  401. '$sort' => ['_id' => 1]
  402. ]
  403. ];
  404. $result = $collection->aggregate($pipeline);
  405. $this->assertInternalType('array', $result);
  406. $this->assertArrayHasKey('result', $result);
  407. $this->assertEquals([
  408. ['_id' => 'bar', 'count' => 2],
  409. ['_id' => 'foo', 'count' => 1],
  410. ], $result['result']);
  411. }
  412. public function testAggregateTimeoutException()
  413. {
  414. $this->skipTestUnless(extension_loaded('mongo'));
  415. $collection = $this->getCollection();
  416. $this->failMaxTimeMS();
  417. $this->setExpectedException('MongoExecutionTimeoutException');
  418. $pipeline = [
  419. [
  420. '$group' => [
  421. '_id' => '$foo',
  422. 'count' => [ '$sum' => 1 ],
  423. ],
  424. ],
  425. [
  426. '$sort' => ['_id' => 1]
  427. ]
  428. ];
  429. $collection->aggregate($pipeline, ['maxTimeMS' => 1]);
  430. }
  431. public function testAggregateCursor()
  432. {
  433. $collection = $this->getCollection();
  434. $this->prepareData();
  435. $pipeline = [
  436. [
  437. '$group' => [
  438. '_id' => '$foo',
  439. 'count' => [ '$sum' => 1 ],
  440. ],
  441. ],
  442. [
  443. '$sort' => ['_id' => 1]
  444. ]
  445. ];
  446. $cursor = $collection->aggregateCursor($pipeline);
  447. $this->assertInstanceOf('MongoCommandCursor', $cursor);
  448. $this->assertEquals([
  449. ['_id' => 'bar', 'count' => 2],
  450. ['_id' => 'foo', 'count' => 1],
  451. ], iterator_to_array($cursor));
  452. }
  453. public function testReadPreference()
  454. {
  455. $collection = $this->getCollection();
  456. $this->assertSame(['type' => \MongoClient::RP_PRIMARY], $collection->getReadPreference());
  457. $this->assertFalse($collection->getSlaveOkay());
  458. $this->assertTrue($collection->setReadPreference(\MongoClient::RP_SECONDARY, [['a' => 'b']]));
  459. $this->assertSame(['type' => \MongoClient::RP_SECONDARY, 'tagsets' => [['a' => 'b']]], $collection->getReadPreference());
  460. $this->assertTrue($collection->getSlaveOkay());
  461. $this->assertTrue($collection->setSlaveOkay(true));
  462. $this->assertSame(['type' => \MongoClient::RP_SECONDARY_PREFERRED, 'tagsets' => [['a' => 'b']]], $collection->getReadPreference());
  463. $this->assertTrue($collection->setSlaveOkay(false));
  464. $this->assertArraySubset(['type' => \MongoClient::RP_PRIMARY], $collection->getReadPreference());
  465. }
  466. public function testReadPreferenceIsSetInDriver()
  467. {
  468. $this->skipTestIf(extension_loaded('mongo'));
  469. $collection = $this->getCollection();
  470. $this->assertTrue($collection->setReadPreference(\MongoClient::RP_SECONDARY, [['a' => 'b']]));
  471. // Only way to check whether options are passed down is through debugInfo
  472. $readPreference = $collection->getCollection()->__debugInfo()['readPreference'];
  473. $this->assertSame(ReadPreference::RP_SECONDARY, $readPreference->getMode());
  474. $this->assertSame([['a' => 'b']], $readPreference->getTagSets());
  475. }
  476. public function testReadPreferenceIsInherited()
  477. {
  478. $database = $this->getDatabase();
  479. $database->setReadPreference(\MongoClient::RP_SECONDARY, [['a' => 'b']]);
  480. $collection = $database->selectCollection('test');
  481. $this->assertSame(['type' => \MongoClient::RP_SECONDARY, 'tagsets' => [['a' => 'b']]], $collection->getReadPreference());
  482. }
  483. public function testWriteConcern()
  484. {
  485. $collection = $this->getCollection();
  486. $this->assertTrue($collection->setWriteConcern('majority', 100));
  487. $this->assertSame(['w' => 'majority', 'wtimeout' => 100], $collection->getWriteConcern());
  488. }
  489. public function testWriteConcernIsSetInDriver()
  490. {
  491. $this->skipTestIf(extension_loaded('mongo'));
  492. $collection = $this->getCollection();
  493. $this->assertTrue($collection->setWriteConcern(2, 100));
  494. // Only way to check whether options are passed down is through debugInfo
  495. $writeConcern = $collection->getCollection()->__debugInfo()['writeConcern'];
  496. $this->assertSame(2, $writeConcern->getW());
  497. $this->assertSame(100, $writeConcern->getWtimeout());
  498. }
  499. public function testWriteConcernIsInherited()
  500. {
  501. $database = $this->getDatabase();
  502. $database->setWriteConcern('majority', 100);
  503. $collection = $database->selectCollection('test');
  504. $this->assertSame(['w' => 'majority', 'wtimeout' => 100], $collection->getWriteConcern());
  505. }
  506. public function testSaveInsert()
  507. {
  508. $id = '54203e08d51d4a1f868b456e';
  509. $collection = $this->getCollection();
  510. $objectId = new \MongoId($id);
  511. $expected = [
  512. 'ok' => 1.0,
  513. 'nModified' => 0,
  514. 'n' => 1,
  515. 'err' => null,
  516. 'errmsg' => null,
  517. 'upserted' => $objectId,
  518. 'updatedExisting' => false,
  519. ];
  520. $document = ['_id' => $objectId, 'foo' => 'bar'];
  521. $this->assertEquals($expected, $collection->save($document));
  522. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  523. $this->assertSame(1, $newCollection->count());
  524. $object = $newCollection->findOne();
  525. $this->assertNotNull($object);
  526. $this->assertAttributeInstanceOf('MongoDB\BSON\ObjectID', '_id', $object);
  527. $this->assertSame($id, (string) $object->_id);
  528. $this->assertObjectHasAttribute('foo', $object);
  529. $this->assertAttributeSame('bar', 'foo', $object);
  530. }
  531. public function testRemoveOne()
  532. {
  533. $id = '54203e08d51d4a1f868b456e';
  534. $collection = $this->getCollection();
  535. $document = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  536. $collection->insert($document);
  537. $collection->remove(['_id' => new \MongoId($id)]);
  538. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  539. $this->assertSame(0, $newCollection->count());
  540. }
  541. public function testSaveUpdate()
  542. {
  543. $expected = [
  544. 'ok' => 1.0,
  545. 'nModified' => 1,
  546. 'n' => 1,
  547. 'err' => null,
  548. 'errmsg' => null,
  549. 'updatedExisting' => true,
  550. ];
  551. $id = '54203e08d51d4a1f868b456e';
  552. $collection = $this->getCollection();
  553. $insertDocument = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  554. $saveDocument = ['_id' => new \MongoId($id), 'foo' => 'foo'];
  555. $collection->insert($insertDocument);
  556. $this->assertSame($expected, $collection->save($saveDocument));
  557. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  558. $this->assertSame(1, $newCollection->count());
  559. $object = $newCollection->findOne();
  560. $this->assertNotNull($object);
  561. $this->assertAttributeInstanceOf('MongoDB\BSON\ObjectID', '_id', $object);
  562. $this->assertSame($id, (string) $object->_id);
  563. $this->assertObjectHasAttribute('foo', $object);
  564. $this->assertAttributeSame('foo', 'foo', $object);
  565. }
  566. public function testSavingShouldReplaceTheWholeDocument() {
  567. $id = '54203e08d51d4a1f868b456e';
  568. $collection = $this->getCollection();
  569. $insertDocument = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  570. $saveDocument = ['_id' => new \MongoId($id)];
  571. $collection->insert($insertDocument);
  572. $collection->save($saveDocument);
  573. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  574. $this->assertSame(1, $newCollection->count());
  575. $object = $newCollection->findOne();
  576. $this->assertNotNull($object);
  577. $this->assertObjectNotHasAttribute('foo', $object);
  578. }
  579. public function testSaveDuplicate()
  580. {
  581. $collection = $this->getCollection();
  582. $collection->createIndex(['foo' => 1], ['unique' => true]);
  583. $document = ['foo' => 'bar'];
  584. $collection->save($document);
  585. $this->setExpectedException('MongoDuplicateKeyException');
  586. unset($document['_id']);
  587. $collection->save($document);
  588. }
  589. public function testSaveEmptyKeys()
  590. {
  591. $document = [];
  592. $this->getCollection()->save($document);
  593. $this->assertSame(1, $this->getCollection()->count());
  594. }
  595. public function testSaveEmptyObject()
  596. {
  597. $document = (object) [];
  598. $this->getCollection()->save($document);
  599. $this->assertSame(1, $this->getCollection()->count());
  600. }
  601. public function testGetDBRef()
  602. {
  603. $collection = $this->getCollection();
  604. $insertDocument = ['_id' => 1, 'foo' => 'bar'];
  605. $collection->insert($insertDocument);
  606. $document = $collection->getDBRef([
  607. '$ref' => 'test',
  608. '$id' => 1,
  609. ]);
  610. $this->assertEquals($insertDocument, $document);
  611. }
  612. public function testCreateDBRef()
  613. {
  614. $collection = $this->getCollection();
  615. $reference = $collection->createDBRef(['_id' => 'foo']);
  616. $this->assertSame(
  617. [
  618. '$ref' => 'test',
  619. '$id' => 'foo',
  620. ],
  621. $reference
  622. );
  623. }
  624. public function testCreateIndex()
  625. {
  626. $expected = [
  627. 'createdCollectionAutomatically' => true,
  628. 'numIndexesBefore' => 1,
  629. 'numIndexesAfter' => 2,
  630. 'ok' => 1.0,
  631. ];
  632. $collection = $this->getCollection();
  633. $this->assertSame($expected, $collection->createIndex(['foo' => 1]));
  634. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  635. $iterator = $newCollection->listIndexes();
  636. $indexes = iterator_to_array($iterator);
  637. $this->assertCount(2, $indexes);
  638. $index = $indexes[1];
  639. $this->assertSame(['foo' => 1], $index->getKey());
  640. $this->assertSame('mongo-php-adapter.test', $index->getNamespace());
  641. }
  642. public function testCreateIndexInvalid()
  643. {
  644. $this->setExpectedException('MongoException', 'index specification has no elements');
  645. $this->getCollection()->createIndex([]);
  646. }
  647. public function testCreateIndexTwice()
  648. {
  649. $this->getCollection()->createIndex(['foo' => 1]);
  650. $expected = [
  651. 'createdCollectionAutomatically' => false,
  652. 'numIndexesBefore' => 2,
  653. 'numIndexesAfter' => 2,
  654. 'note' => 'all indexes already exist',
  655. 'ok' => 1.0
  656. ];
  657. $this->assertSame($expected, $this->getCollection()->createIndex(['foo' => 1]));
  658. }
  659. public function testCreateIndexTwiceWithSameName()
  660. {
  661. $this->getCollection()->createIndex(['foo' => 1], ['name' => 'test_index']);
  662. $expected = [
  663. 'createdCollectionAutomatically' => false,
  664. 'numIndexesBefore' => 2,
  665. 'numIndexesAfter' => 2,
  666. 'note' => 'all indexes already exist',
  667. 'ok' => 1.0
  668. ];
  669. $this->assertSame($expected, $this->getCollection()->createIndex(['foo' => 1], ['name' => 'test_index']));
  670. }
  671. public function testCreateIndexTwiceWithDifferentName()
  672. {
  673. $this->getCollection()->createIndex(['foo' => 1], ['name' => 'test_index']);
  674. $expected = [
  675. 'createdCollectionAutomatically' => false,
  676. 'numIndexesBefore' => 2,
  677. 'numIndexesAfter' => 2,
  678. 'note' => 'all indexes already exist',
  679. 'ok' => 1.0
  680. ];
  681. $this->assertSame($expected, $this->getCollection()->createIndex(['foo' => 1], ['name' => 'index_test']));
  682. }
  683. public function testCreateIndexTwiceWithDifferentOrder()
  684. {
  685. $this->getCollection()->createIndex(['foo' => 1, 'bar' => 1]);
  686. $expected = [
  687. 'createdCollectionAutomatically' => false,
  688. 'numIndexesBefore' => 2,
  689. 'numIndexesAfter' => 3,
  690. 'ok' => 1.0
  691. ];
  692. $this->assertSame($expected, $this->getCollection()->createIndex(['bar' => 1, 'foo' => 1]));
  693. }
  694. public function testCreateIndexesWithDifferentOptions()
  695. {
  696. $this->setExpectedException('MongoResultException');
  697. $this->getCollection()->createIndex(['foo' => 1]);
  698. $this->getCollection()->createIndex(['foo' => 1], ['unique' => true]);
  699. }
  700. /**
  701. * @dataProvider createIndexIgnoredOptions
  702. */
  703. public function testCreateIndexesWithIgnoredOptions($option)
  704. {
  705. $this->getCollection()->createIndex(['foo' => 1]);
  706. $expected = [
  707. 'createdCollectionAutomatically' => false,
  708. 'numIndexesBefore' => 2,
  709. 'numIndexesAfter' => 2,
  710. 'note' => 'all indexes already exist',
  711. 'ok' => 1.0
  712. ];
  713. $this->assertSame($expected, $this->getCollection()->createIndex(['foo' => 1], [$option => true]));
  714. }
  715. public static function createIndexIgnoredOptions()
  716. {
  717. return [
  718. 'background' => ['background'],
  719. 'dropDups' => ['dropDups'],
  720. ];
  721. }
  722. public function testCreateIndexWithSameNameAndDifferentOptions()
  723. {
  724. $this->setExpectedException('MongoResultException');
  725. $this->getCollection()->createIndex(['foo' => 1], ['name' => 'foo']);
  726. $this->getCollection()->createIndex(['bar' => 1], ['name' => 'foo']);
  727. }
  728. public function testEnsureIndex()
  729. {
  730. $expected = [
  731. 'createdCollectionAutomatically' => true,
  732. 'numIndexesBefore' => 1,
  733. 'numIndexesAfter' => 2,
  734. 'ok' => 1.0
  735. ];
  736. $collection = $this->getCollection();
  737. $this->assertEquals($expected, $collection->ensureIndex(['bar' => 1], ['unique' => true]));
  738. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  739. $indexes = iterator_to_array($newCollection->listIndexes());
  740. $this->assertCount(2, $indexes);
  741. $index = $indexes[1];
  742. $this->assertSame(['bar' => 1], $index->getKey());
  743. $this->assertTrue($index->isUnique());
  744. $this->assertSame('mongo-php-adapter.test', $index->getNamespace());
  745. }
  746. public function testEnsureIndexAlreadyExists()
  747. {
  748. $collection = $this->getCollection();
  749. $collection->ensureIndex(['bar' => 1], ['unique' => true]);
  750. $expected = [
  751. 'createdCollectionAutomatically' => false,
  752. 'numIndexesBefore' => 2,
  753. 'numIndexesAfter' => 2,
  754. 'ok' => 1.0,
  755. 'note' => 'all indexes already exist',
  756. ];
  757. $this->assertEquals($expected, $collection->ensureIndex(['bar' => 1], ['unique' => true]));
  758. }
  759. public function testEnsureIndexAlreadyExistsWithDifferentOptions()
  760. {
  761. $collection = $this->getCollection();
  762. $collection->ensureIndex(['bar' => 1], ['unique' => true]);
  763. $this->setExpectedException('MongoResultException', 'Index with name: bar_1 already exists with different options');
  764. $collection->ensureIndex(['bar' => 1]);
  765. }
  766. public function testDeleteIndexUsingIndexName()
  767. {
  768. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  769. $newCollection->createIndex(['bar' => 1], ['name' => 'bar']);
  770. $expected = [
  771. 'nIndexesWas' => 2,
  772. 'errmsg' => 'index not found with name [bar_1]',
  773. 'ok' => 0.0,
  774. 'code' => 27,
  775. ];
  776. $this->assertEquals($expected, $this->getCollection()->deleteIndex('bar'));
  777. $this->assertCount(2, iterator_to_array($newCollection->listIndexes()));
  778. }
  779. public function testDeleteIndexUsingField()
  780. {
  781. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  782. $newCollection->createIndex(['bar' => 1]);
  783. $expected = [
  784. 'nIndexesWas' => 2,
  785. 'ok' => 1.0,
  786. ];
  787. $this->assertSame($expected, $this->getCollection()->deleteIndex('bar'));
  788. $this->assertCount(1, iterator_to_array($newCollection->listIndexes()));
  789. }
  790. public function testDeleteIndexUsingKeys()
  791. {
  792. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  793. $newCollection->createIndex(['bar' => 1]);
  794. $expected = [
  795. 'nIndexesWas' => 2,
  796. 'ok' => 1.0,
  797. ];
  798. $this->assertSame($expected, $this->getcollection()->deleteIndex(['bar' => 1]));
  799. $this->assertCount(1, iterator_to_array($newCollection->listIndexes()));
  800. }
  801. public function testDeleteIndexes()
  802. {
  803. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  804. $newCollection->createIndex(['bar' => 1]);
  805. $expected = [
  806. 'nIndexesWas' => 2,
  807. 'msg' => 'non-_id indexes dropped for collection',
  808. 'ok' => 1.0,
  809. ];
  810. $this->assertSame($expected, $this->getcollection()->deleteIndexes());
  811. $this->assertCount(1, iterator_to_array($newCollection->listIndexes())); // ID index is present by default
  812. }
  813. public function testDeleteIndexesForNonExistingCollection()
  814. {
  815. $expected = [
  816. 'ok' => 0.0,
  817. 'errmsg' => 'ns not found',
  818. 'code' => 26,
  819. ];
  820. $this->assertSame($expected, $this->getcollection('nonExisting')->deleteIndexes());
  821. }
  822. public function testGetIndexInfo()
  823. {
  824. $collection = $this->getCollection();
  825. $collection->createIndex(['foo' => 1]);
  826. $expected = [
  827. [
  828. 'v' => 1,
  829. 'key' => ['_id' => 1],
  830. 'name' => '_id_',
  831. 'ns' => 'mongo-php-adapter.test',
  832. ],
  833. [
  834. 'v' => 1,
  835. 'key' => ['foo' => 1],
  836. 'name' => 'foo_1',
  837. 'ns' => 'mongo-php-adapter.test',
  838. ],
  839. ];
  840. $this->assertSame(
  841. $expected,
  842. $collection->getIndexInfo()
  843. );
  844. }
  845. public function testFindAndModifyUpdate()
  846. {
  847. $id = '54203e08d51d4a1f868b456e';
  848. $collection = $this->getCollection();
  849. $document = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  850. $collection->insert($document);
  851. $document = $collection->findAndModify(
  852. ['_id' => new \MongoId($id)],
  853. ['$set' => ['foo' => 'foo']]
  854. );
  855. $this->assertSame('bar', $document['foo']);
  856. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  857. $this->assertSame(1, $newCollection->count());
  858. $object = $newCollection->findOne();
  859. $this->assertNotNull($object);
  860. $this->assertAttributeSame('foo', 'foo', $object);
  861. }
  862. public function testFindAndModifyUpdateReplace()
  863. {
  864. $id = '54203e08d51d4a1f868b456e';
  865. $collection = $this->getCollection();
  866. $document = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  867. $collection->insert($document);
  868. $document = $collection->findAndModify(
  869. ['_id' => new \MongoId($id)],
  870. ['_id' => new \MongoId($id), 'foo' => 'boo']
  871. );
  872. $this->assertSame('bar', $document['foo']);
  873. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  874. $this->assertSame(1, $newCollection->count());
  875. $object = $newCollection->findOne();
  876. $this->assertNotNull($object);
  877. $this->assertAttributeSame('boo', 'foo', $object);
  878. $this->assertObjectNotHasAttribute('bar', $object);
  879. }
  880. public function testFindAndModifyUpdateReturnNew()
  881. {
  882. $id = '54203e08d51d4a1f868b456e';
  883. $collection = $this->getCollection();
  884. $document = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  885. $collection->insert($document);
  886. $document = $collection->findAndModify(
  887. ['_id' => new \MongoId($id)],
  888. ['$set' => ['foo' => 'foo']],
  889. null,
  890. ['new' => true]
  891. );
  892. $this->assertSame('foo', $document['foo']);
  893. }
  894. public function testFindAndModifyWithFields()
  895. {
  896. $id = '54203e08d51d4a1f868b456e';
  897. $collection = $this->getCollection();
  898. $document = [
  899. '_id' => new \MongoId($id),
  900. 'foo' => 'bar',
  901. 'bar' => 'foo',
  902. ];
  903. $collection->insert($document);
  904. $document = $collection->findAndModify(
  905. ['_id' => new \MongoId($id)],
  906. ['$set' => ['foo' => 'foo']],
  907. ['foo' => true]
  908. );
  909. $this->assertArrayNotHasKey('bar', $document);
  910. $this->assertArrayHasKey('foo', $document);
  911. }
  912. public function testGroup()
  913. {
  914. $collection = $this->getCollection();
  915. $document1 = ['a' => 2];
  916. $collection->insert($document1);
  917. $document2 = ['b' => 5];
  918. $collection->insert($document2);
  919. $document3 = ['a' => 1];
  920. $collection->insert($document3);
  921. $keys = [];
  922. $initial = ["count" => 0];
  923. $reduce = "function (obj, prev) { prev.count++; }";
  924. $condition = ['condition' => ["a" => [ '$gt' => 1]]];
  925. $result = $collection->group($keys, $initial, $reduce, $condition);
  926. $this->assertArraySubset(
  927. [
  928. 'retval' => [['count' => 1.0]],
  929. 'count' => 1.0,
  930. 'keys' => 1,
  931. 'ok' => 1.0,
  932. ],
  933. $result
  934. );
  935. }
  936. public function testMapReduce()
  937. {
  938. $data = array(
  939. array(
  940. 'username' => 'jones',
  941. 'likes' => 20.0,
  942. 'text' => 'Hello world!'
  943. ),
  944. array(
  945. 'username' => 'bob',
  946. 'likes' => 100.0,
  947. 'text' => 'Hello world!'
  948. ),
  949. array(
  950. 'username' => 'bob',
  951. 'likes' => 100.0,
  952. 'text' => 'Hello world!'
  953. ),
  954. );
  955. $collection = $this->getCollection();
  956. $collection->batchInsert($data);
  957. $map = 'function() {
  958. emit(this.username, { count: 1, likes: this.likes });
  959. }';
  960. $reduce = 'function(key, values) {
  961. var result = {count: 0, likes: 0};
  962. values.forEach(function(value) {
  963. result.count += value.count;
  964. result.likes += value.likes;
  965. });
  966. return result;
  967. }';
  968. $finalize = 'function (key, value) { value.test = "test"; return value; }';
  969. $command = [
  970. 'mapreduce' => $this->getCollection()->getName(),
  971. 'map' => new \MongoCode($map),
  972. 'reduce' => new \MongoCode($reduce),
  973. 'query' => (object) [],
  974. 'out' => ['inline' => true],
  975. 'finalize' => new \MongoCode($finalize),
  976. ];
  977. $result = $this->getDatabase()->command($command);
  978. $expected = [
  979. [
  980. '_id' => 'bob',
  981. 'value' => [
  982. 'count' => 2.0,
  983. 'likes' => 200.0,
  984. 'test' => 'test',
  985. ],
  986. ],
  987. [
  988. '_id' => 'jones',
  989. 'value' => [
  990. 'count' => 1.0,
  991. 'likes' => 20.0,
  992. 'test' => 'test',
  993. ],
  994. ],
  995. ];
  996. $this->assertSame(1.0, $result['ok']);
  997. $this->assertSame($expected, $result['results']);
  998. }
  999. public function testFindAndModifyResultException()
  1000. {
  1001. $this->markTestSkipped('Test fails on travis-ci - skipped while investigating this');
  1002. $collection = $this->getCollection();
  1003. $this->setExpectedException('MongoResultException');
  1004. $collection->findAndModify(
  1005. array("inprogress" => false, "name" => "Next promo"),
  1006. array('$unsupportedOperator' => array("tasks" => -1)),
  1007. array("tasks" => true),
  1008. array("new" => true)
  1009. );
  1010. }
  1011. public function testFindAndModifyExceptionTimeout()
  1012. {
  1013. $this->failMaxTimeMS();
  1014. $id = '54203e08d51d4a1f868b456e';
  1015. $collection = $this->getCollection();
  1016. $this->setExpectedException('MongoExecutionTimeoutException');
  1017. $document = $collection->findAndModify(
  1018. ['_id' => new \MongoId($id)],
  1019. null,
  1020. null,
  1021. ['maxTimeMS' => 1, 'remove' => true]
  1022. );
  1023. }
  1024. public function testFindAndModifyRemove()
  1025. {
  1026. $id = '54203e08d51d4a1f868b456e';
  1027. $collection = $this->getCollection();
  1028. $document = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  1029. $collection->insert($document);
  1030. $document = $collection->findAndModify(
  1031. ['_id' => new \MongoId($id)],
  1032. null,
  1033. null,
  1034. ['remove' => true]
  1035. );
  1036. $this->assertEquals('bar', $document['foo']);
  1037. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  1038. $this->assertSame(0, $newCollection->count());
  1039. }
  1040. public function testValidate()
  1041. {
  1042. $collection = $this->getCollection();
  1043. $document = ['foo' => 'bar'];
  1044. $collection->insert($document);
  1045. $result = $collection->validate();
  1046. $this->assertArraySubset(
  1047. [
  1048. 'ns' => 'mongo-php-adapter.test',
  1049. 'nrecords' => 1,
  1050. 'nIndexes' => 1,
  1051. 'keysPerIndex' => ['mongo-php-adapter.test.$_id_' => 1],
  1052. 'valid' => true,
  1053. 'errors' => [],
  1054. 'warning' => 'Some checks omitted for speed. use {full:true} option to do more thorough scan.',
  1055. 'ok' => 1.0
  1056. ],
  1057. $result
  1058. );
  1059. }
  1060. public function testDrop()
  1061. {
  1062. $document = ['foo' => 'bar'];
  1063. $this->getCollection()->insert($document);
  1064. $expected = [
  1065. 'ns' => (string) $this->getCollection(),
  1066. 'nIndexesWas' => 1,
  1067. 'ok' => 1.0
  1068. ];
  1069. $this->assertSame($expected, $this->getCollection()->drop());
  1070. }
  1071. public function testEmptyCollectionName()
  1072. {
  1073. $this->setExpectedException('Exception', 'Collection name cannot be empty');
  1074. new \MongoCollection($this->getDatabase(), '');
  1075. }
  1076. public function testSelectCollectionWithNullBytes()
  1077. {
  1078. $this->setExpectedException('Exception', 'Collection name cannot contain null bytes');
  1079. new \MongoCollection($this->getDatabase(), 'foo' . chr(0));
  1080. }
  1081. public function testSubCollectionWithNullBytes()
  1082. {
  1083. $collection = $this->getCollection();
  1084. $this->assertInstanceOf('MongoCollection', $collection->{'foo' . chr(0)});
  1085. $this->assertSame('test', $collection->getName());
  1086. }
  1087. }
  1088. class PrivatePropertiesStub
  1089. {
  1090. private $foo = 'bar';
  1091. }