MongoInsertBatchTest.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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 testInsertBatchWithoutAck()
  29. {
  30. $batch = new \MongoInsertBatch($this->getCollection());
  31. $this->assertTrue($batch->add(['foo' => 'bar']));
  32. $this->assertTrue($batch->add(['bar' => 'foo']));
  33. $expected = [
  34. 'nInserted' => 0,
  35. 'ok' => true,
  36. ];
  37. $this->assertSame($expected, $batch->execute(['w' => 0]));
  38. $newCollection = $this->getCheckDatabase()->selectCollection('test');
  39. $this->assertSame(2, $newCollection->count());
  40. $record = $newCollection->findOne();
  41. $this->assertNotNull($record);
  42. $this->assertObjectHasAttribute('foo', $record);
  43. $this->assertAttributeSame('bar', 'foo', $record);
  44. }
  45. public function testInsertBatchError()
  46. {
  47. $collection = $this->getCollection();
  48. $batch = new \MongoInsertBatch($collection);
  49. $collection->createIndex(['foo' => 1], ['unique' => true]);
  50. $this->assertTrue($batch->add(['foo' => 'bar']));
  51. $this->assertTrue($batch->add(['foo' => 'bar']));
  52. $expected = [
  53. 'writeErrors' => [
  54. [
  55. 'index' => 1,
  56. 'code' => 11000,
  57. ]
  58. ],
  59. 'nInserted' => 1,
  60. 'ok' => true,
  61. ];
  62. try {
  63. $batch->execute();
  64. $this->fail('Expected MongoWriteConcernException');
  65. } catch (\MongoWriteConcernException $e) {
  66. $this->assertSame('Failed write', $e->getMessage());
  67. $this->assertSame(911, $e->getCode());
  68. $this->assertArraySubset($expected, $e->getDocument());
  69. }
  70. }
  71. }