MongoInsertBatchTest.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. namespace Alcaeus\MongoDbAdapter\Tests\Mongo;
  3. use Alcaeus\MongoDbAdapter\Tests\TestCase;
  4. class MongoInsertBatchTest extends TestCase
  5. {
  6. public function testSerialize()
  7. {
  8. $batch = new \MongoInsertBatch($this->getCollection());
  9. $this->assertIsString(serialize($batch));
  10. }
  11. public function testInsertBatch()
  12. {
  13. $batch = new \MongoInsertBatch($this->getCollection());
  14. $this->assertTrue($batch->add(['foo' => 'bar']));
  15. $this->assertTrue($batch->add(['bar' => 'foo']));
  16. $expected = [
  17. 'nInserted' => 2,
  18. 'ok' => true,
  19. ];
  20. $this->assertSame($expected, $batch->execute());
  21. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  22. $this->assertSame(2, $newCollection->count());
  23. $record = $newCollection->findOne();
  24. $this->assertNotNull($record);
  25. $this->assertSame('bar', $record->foo);
  26. }
  27. public function testInsertBatchWithoutAck()
  28. {
  29. $batch = new \MongoInsertBatch($this->getCollection());
  30. $this->assertTrue($batch->add(['foo' => 'bar']));
  31. $this->assertTrue($batch->add(['bar' => 'foo']));
  32. $expected = [
  33. 'nInserted' => 0,
  34. 'ok' => true,
  35. ];
  36. $this->assertSame($expected, $batch->execute(['w' => 0]));
  37. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  38. $this->assertSame(2, $newCollection->count());
  39. $record = $newCollection->findOne();
  40. $this->assertNotNull($record);
  41. $this->assertSame('bar', $record->foo);
  42. }
  43. public function testInsertBatchError()
  44. {
  45. $collection = $this->getCollection();
  46. $batch = new \MongoInsertBatch($collection);
  47. $collection->createIndex(['foo' => 1], ['unique' => true]);
  48. $this->assertTrue($batch->add(['foo' => 'bar']));
  49. $this->assertTrue($batch->add(['foo' => 'bar']));
  50. $expected = [
  51. 'writeErrors' => [
  52. [
  53. 'index' => 1,
  54. 'code' => 11000,
  55. ]
  56. ],
  57. 'nInserted' => 1,
  58. 'ok' => true,
  59. ];
  60. try {
  61. $batch->execute();
  62. $this->fail('Expected MongoWriteConcernException');
  63. } catch (\MongoWriteConcernException $e) {
  64. $this->assertSame('Failed write', $e->getMessage());
  65. $this->assertSame(911, $e->getCode());
  66. $this->assertMatches($expected, $e->getDocument());
  67. }
  68. }
  69. }