MongoInsertBatchTest.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. } catch (\MongoWriteConcernException $e) {
  48. $this->assertSame('Failed write', $e->getMessage());
  49. $this->assertArraySubset($expected, $e->getDocument());
  50. }
  51. }
  52. }