MongoCollectionTest.php 38 KB

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