MongoInsertBatchTest.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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->assertInternalType('string', 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->assertObjectHasAttribute('foo', $record);
  26. $this->assertAttributeSame('bar', 'foo', $record);
  27. }
  28. public function testInsertBatchError()
  29. {
  30. $collection = $this->getCollection();
  31. $batch = new \MongoInsertBatch($collection);
  32. $collection->createIndex(['foo' => 1], ['unique' => true]);
  33. $this->assertTrue($batch->add(['foo' => 'bar']));
  34. $this->assertTrue($batch->add(['foo' => 'bar']));
  35. $expected = [
  36. 'writeErrors' => [
  37. [
  38. 'index' => 1,
  39. 'code' => 11000,
  40. ]
  41. ],
  42. 'nInserted' => 1,
  43. 'ok' => true,
  44. ];
  45. try {
  46. $batch->execute();
  47. $this->fail('Expected MongoWriteConcernException');
  48. } catch (\MongoWriteConcernException $e) {
  49. $this->assertSame('Failed write', $e->getMessage());
  50. $this->assertSame(911, $e->getCode());
  51. $this->assertArraySubset($expected, $e->getDocument());
  52. }
  53. }
  54. }