MongoInsertBatchTest.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <?php
  2. namespace Alcaeus\MongoDbAdapter\Tests;
  3. class MongoInsertBatchTest extends TestCase
  4. {
  5. public function testInsertBatch()
  6. {
  7. $batch = new \MongoInsertBatch($this->getCollection());
  8. $this->assertTrue($batch->add(['foo' => 'bar']));
  9. $this->assertTrue($batch->add(['bar' => 'foo']));
  10. $expected = [
  11. 'nInserted' => 2,
  12. 'ok' => true,
  13. ];
  14. $this->assertSame($expected, $batch->execute());
  15. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  16. $this->assertSame(2, $newCollection->count());
  17. $record = $newCollection->findOne();
  18. $this->assertNotNull($record);
  19. $this->assertObjectHasAttribute('foo', $record);
  20. $this->assertAttributeSame('bar', 'foo', $record);
  21. }
  22. public function testInsertBatchError()
  23. {
  24. $collection = $this->getCollection();
  25. $batch = new \MongoInsertBatch($collection);
  26. $collection->createIndex(['foo' => 1], ['unique' => true]);
  27. $this->assertTrue($batch->add(['foo' => 'bar']));
  28. $this->assertTrue($batch->add(['foo' => 'bar']));
  29. $expected = [
  30. 'writeErrors' => [
  31. [
  32. 'index' => 1,
  33. 'code' => 11000,
  34. ]
  35. ],
  36. 'nInserted' => 1,
  37. 'ok' => true,
  38. ];
  39. try {
  40. $batch->execute();
  41. } catch (\MongoWriteConcernException $e) {
  42. $this->assertSame('Failed write', $e->getMessage());
  43. $this->assertArraySubset($expected, $e->getDocument());
  44. }
  45. }
  46. }