MongoInsertBatchTest.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. 'errmsg' => 'E11000 duplicate key error collection: mongo-php-adapter.test index: foo_1 dup key: { : "bar" }',
  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->assertSame($expected, $e->getDocument());
  45. }
  46. }
  47. }