MongoClientTest.php 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. namespace Alcaeus\MongoDbAdapter\Tests;
  3. /**
  4. * @author alcaeus <alcaeus@alcaeus.org>
  5. */
  6. class MongoClientTest extends TestCase
  7. {
  8. public function testConnectAndDisconnect()
  9. {
  10. $client = $this->getClient();
  11. $this->assertTrue($client->connected);
  12. $client->close();
  13. $this->assertFalse($client->connected);
  14. }
  15. public function testClientWithoutAutomaticConnect()
  16. {
  17. $client = $this->getClient([]);
  18. $this->assertFalse($client->connected);
  19. }
  20. public function testGetDb()
  21. {
  22. $client = $this->getClient();
  23. $db = $client->selectDB('mongo-php-adapter');
  24. $this->assertInstanceOf('\MongoDB', $db);
  25. $this->assertSame('mongo-php-adapter', (string) $db);
  26. }
  27. public function testGetDbProperty()
  28. {
  29. $client = $this->getClient();
  30. $db = $client->{'mongo-php-adapter'};
  31. $this->assertInstanceOf('\MongoDB', $db);
  32. $this->assertSame('mongo-php-adapter', (string) $db);
  33. }
  34. public function testGetCollection()
  35. {
  36. $client = $this->getClient();
  37. $collection = $client->selectCollection('mongo-php-adapter', 'test');
  38. $this->assertInstanceOf('MongoCollection', $collection);
  39. $this->assertSame('mongo-php-adapter.test', (string) $collection);
  40. }
  41. public function testGetHosts()
  42. {
  43. $client = $this->getClient();
  44. $this->assertArraySubset(
  45. [
  46. 'localhost:27017' => [
  47. 'host' => 'localhost',
  48. 'port' => 27017,
  49. 'health' => 1,
  50. 'state' => 1,
  51. ],
  52. ],
  53. $client->getHosts()
  54. );
  55. }
  56. public function testReadPreference()
  57. {
  58. $client = $this->getClient();
  59. $this->assertSame(['type' => \MongoClient::RP_PRIMARY], $client->getReadPreference());
  60. $this->assertTrue($client->setReadPreference(\MongoClient::RP_SECONDARY, ['a' => 'b']));
  61. $this->assertSame(['type' => \MongoClient::RP_SECONDARY, 'tagsets' => ['a' => 'b']], $client->getReadPreference());
  62. }
  63. public function testWriteConcern()
  64. {
  65. $client = $this->getClient();
  66. $this->assertSame(['w' => 1, 'wtimeout' => 0], $client->getWriteConcern());
  67. $this->assertTrue($client->setWriteConcern('majority', 100));
  68. $this->assertSame(['w' => 'majority', 'wtimeout' => 100], $client->getWriteConcern());
  69. }
  70. /**
  71. * @param array|null $options
  72. * @return \MongoClient
  73. */
  74. protected function getClient($options = null)
  75. {
  76. $args = ['mongodb://localhost'];
  77. if ($options !== null) {
  78. $args[] = $options;
  79. }
  80. $reflection = new \ReflectionClass('MongoClient');
  81. return $reflection->newInstanceArgs($args);
  82. }
  83. }