MongoInsertBatchTest.php 1.6 KB

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