MongoCollectionTest.php 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260
  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 testDeleteIndexesForNonExistingCollection()
  733. {
  734. $expected = [
  735. 'ok' => 0.0,
  736. 'errmsg' => 'ns not found',
  737. 'code' => 26,
  738. ];
  739. $this->assertSame($expected, $this->getcollection('nonExisting')->deleteIndexes());
  740. }
  741. public function testGetIndexInfo()
  742. {
  743. $collection = $this->getCollection();
  744. $collection->createIndex(['foo' => 1]);
  745. $expected = [
  746. [
  747. 'v' => 1,
  748. 'key' => ['_id' => 1],
  749. 'name' => '_id_',
  750. 'ns' => 'mongo-php-adapter.test',
  751. ],
  752. [
  753. 'v' => 1,
  754. 'key' => ['foo' => 1],
  755. 'name' => 'foo_1',
  756. 'ns' => 'mongo-php-adapter.test',
  757. ],
  758. ];
  759. $this->assertSame(
  760. $expected,
  761. $collection->getIndexInfo()
  762. );
  763. }
  764. public function testFindAndModifyUpdate()
  765. {
  766. $id = '54203e08d51d4a1f868b456e';
  767. $collection = $this->getCollection();
  768. $document = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  769. $collection->insert($document);
  770. $document = $collection->findAndModify(
  771. ['_id' => new \MongoId($id)],
  772. ['$set' => ['foo' => 'foo']]
  773. );
  774. $this->assertSame('bar', $document['foo']);
  775. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  776. $this->assertSame(1, $newCollection->count());
  777. $object = $newCollection->findOne();
  778. $this->assertNotNull($object);
  779. $this->assertAttributeSame('foo', 'foo', $object);
  780. }
  781. public function testFindAndModifyUpdateReplace()
  782. {
  783. $id = '54203e08d51d4a1f868b456e';
  784. $collection = $this->getCollection();
  785. $document = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  786. $collection->insert($document);
  787. $document = $collection->findAndModify(
  788. ['_id' => new \MongoId($id)],
  789. ['_id' => new \MongoId($id), 'foo' => 'boo']
  790. );
  791. $this->assertSame('bar', $document['foo']);
  792. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  793. $this->assertSame(1, $newCollection->count());
  794. $object = $newCollection->findOne();
  795. $this->assertNotNull($object);
  796. $this->assertAttributeSame('boo', 'foo', $object);
  797. $this->assertObjectNotHasAttribute('bar', $object);
  798. }
  799. public function testFindAndModifyUpdateReturnNew()
  800. {
  801. $id = '54203e08d51d4a1f868b456e';
  802. $collection = $this->getCollection();
  803. $document = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  804. $collection->insert($document);
  805. $document = $collection->findAndModify(
  806. ['_id' => new \MongoId($id)],
  807. ['$set' => ['foo' => 'foo']],
  808. null,
  809. ['new' => true]
  810. );
  811. $this->assertSame('foo', $document['foo']);
  812. }
  813. public function testFindAndModifyWithFields()
  814. {
  815. $id = '54203e08d51d4a1f868b456e';
  816. $collection = $this->getCollection();
  817. $document = [
  818. '_id' => new \MongoId($id),
  819. 'foo' => 'bar',
  820. 'bar' => 'foo',
  821. ];
  822. $collection->insert($document);
  823. $document = $collection->findAndModify(
  824. ['_id' => new \MongoId($id)],
  825. ['$set' => ['foo' => 'foo']],
  826. ['foo' => true]
  827. );
  828. $this->assertArrayNotHasKey('bar', $document);
  829. $this->assertArrayHasKey('foo', $document);
  830. }
  831. public function testGroup()
  832. {
  833. $collection = $this->getCollection();
  834. $document1 = ['a' => 2];
  835. $collection->insert($document1);
  836. $document2 = ['b' => 5];
  837. $collection->insert($document2);
  838. $document3 = ['a' => 1];
  839. $collection->insert($document3);
  840. $keys = [];
  841. $initial = ["count" => 0];
  842. $reduce = "function (obj, prev) { prev.count++; }";
  843. $condition = ['condition' => ["a" => [ '$gt' => 1]]];
  844. $result = $collection->group($keys, $initial, $reduce, $condition);
  845. $this->assertArraySubset(
  846. [
  847. 'retval' => [['count' => 1.0]],
  848. 'count' => 1.0,
  849. 'keys' => 1,
  850. 'ok' => 1.0,
  851. ],
  852. $result
  853. );
  854. }
  855. public function testMapReduce()
  856. {
  857. $data = array(
  858. array(
  859. 'username' => 'jones',
  860. 'likes' => 20.0,
  861. 'text' => 'Hello world!'
  862. ),
  863. array(
  864. 'username' => 'bob',
  865. 'likes' => 100.0,
  866. 'text' => 'Hello world!'
  867. ),
  868. array(
  869. 'username' => 'bob',
  870. 'likes' => 100.0,
  871. 'text' => 'Hello world!'
  872. ),
  873. );
  874. $collection = $this->getCollection();
  875. $collection->batchInsert($data);
  876. $map = 'function() {
  877. emit(this.username, { count: 1, likes: this.likes });
  878. }';
  879. $reduce = 'function(key, values) {
  880. var result = {count: 0, likes: 0};
  881. values.forEach(function(value) {
  882. result.count += value.count;
  883. result.likes += value.likes;
  884. });
  885. return result;
  886. }';
  887. $finalize = 'function (key, value) { value.test = "test"; return value; }';
  888. $command = [
  889. 'mapreduce' => $this->getCollection()->getName(),
  890. 'map' => new \MongoCode($map),
  891. 'reduce' => new \MongoCode($reduce),
  892. 'query' => (object) [],
  893. 'out' => ['inline' => true],
  894. 'finalize' => new \MongoCode($finalize),
  895. ];
  896. $result = $this->getDatabase()->command($command);
  897. $expected = [
  898. [
  899. '_id' => 'bob',
  900. 'value' => [
  901. 'count' => 2.0,
  902. 'likes' => 200.0,
  903. 'test' => 'test',
  904. ],
  905. ],
  906. [
  907. '_id' => 'jones',
  908. 'value' => [
  909. 'count' => 1.0,
  910. 'likes' => 20.0,
  911. 'test' => 'test',
  912. ],
  913. ],
  914. ];
  915. $this->assertSame(1.0, $result['ok']);
  916. $this->assertSame($expected, $result['results']);
  917. }
  918. public function testFindAndModifyResultException()
  919. {
  920. $this->markTestSkipped('Test fails on travis-ci - skipped while investigating this');
  921. $collection = $this->getCollection();
  922. $this->setExpectedException('MongoResultException');
  923. $collection->findAndModify(
  924. array("inprogress" => false, "name" => "Next promo"),
  925. array('$unsupportedOperator' => array("tasks" => -1)),
  926. array("tasks" => true),
  927. array("new" => true)
  928. );
  929. }
  930. public function testFindAndModifyExceptionTimeout()
  931. {
  932. $this->failMaxTimeMS();
  933. $id = '54203e08d51d4a1f868b456e';
  934. $collection = $this->getCollection();
  935. $this->setExpectedException('MongoExecutionTimeoutException');
  936. $document = $collection->findAndModify(
  937. ['_id' => new \MongoId($id)],
  938. null,
  939. null,
  940. ['maxTimeMS' => 1, 'remove' => true]
  941. );
  942. }
  943. public function testFindAndModifyRemove()
  944. {
  945. $id = '54203e08d51d4a1f868b456e';
  946. $collection = $this->getCollection();
  947. $document = ['_id' => new \MongoId($id), 'foo' => 'bar'];
  948. $collection->insert($document);
  949. $document = $collection->findAndModify(
  950. ['_id' => new \MongoId($id)],
  951. null,
  952. null,
  953. ['remove' => true]
  954. );
  955. $this->assertEquals('bar', $document['foo']);
  956. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  957. $this->assertSame(0, $newCollection->count());
  958. }
  959. public function testValidate()
  960. {
  961. $collection = $this->getCollection();
  962. $document = ['foo' => 'bar'];
  963. $collection->insert($document);
  964. $result = $collection->validate();
  965. $this->assertArraySubset(
  966. [
  967. 'ns' => 'mongo-php-adapter.test',
  968. 'nrecords' => 1,
  969. 'nIndexes' => 1,
  970. 'keysPerIndex' => ['mongo-php-adapter.test.$_id_' => 1],
  971. 'valid' => true,
  972. 'errors' => [],
  973. 'warning' => 'Some checks omitted for speed. use {full:true} option to do more thorough scan.',
  974. 'ok' => 1.0
  975. ],
  976. $result
  977. );
  978. }
  979. public function testDrop()
  980. {
  981. $document = ['foo' => 'bar'];
  982. $this->getCollection()->insert($document);
  983. $expected = [
  984. 'ns' => (string) $this->getCollection(),
  985. 'nIndexesWas' => 1,
  986. 'ok' => 1.0
  987. ];
  988. $this->assertSame($expected, $this->getCollection()->drop());
  989. }
  990. public function testEmptyCollectionName()
  991. {
  992. $this->setExpectedException('Exception', 'Collection name cannot be empty');
  993. new \MongoCollection($this->getDatabase(), '');
  994. }
  995. public function testSelectCollectionWithNullBytes()
  996. {
  997. $this->setExpectedException('Exception', 'Collection name cannot contain null bytes');
  998. new \MongoCollection($this->getDatabase(), 'foo' . chr(0));
  999. }
  1000. public function testSubCollectionWithNullBytes()
  1001. {
  1002. $collection = $this->getCollection();
  1003. $this->assertInstanceOf('MongoCollection', $collection->{'foo' . chr(0)});
  1004. $this->assertSame('test', $collection->getName());
  1005. }
  1006. }
  1007. class PrivatePropertiesStub
  1008. {
  1009. private $foo = 'bar';
  1010. }