MongoDBHandlerTest.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php declare(strict_types=1);
  2. /*
  3. * This file is part of the Monolog package.
  4. *
  5. * (c) Jordi Boggiano <j.boggiano@seld.be>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Monolog\Handler;
  11. use MongoDB\BSON\UTCDateTime;
  12. use MongoDB\Client;
  13. use MongoDB\Collection;
  14. use MongoDB\Driver\Manager;
  15. use Monolog\Test\TestCase;
  16. class MongoDBHandlerTest extends TestCase
  17. {
  18. public function setUp(): void
  19. {
  20. if (!extension_loaded('mongodb')) {
  21. $this->markTestSkipped('ext-mongodb not installed');
  22. }
  23. }
  24. public function testConstructorShouldThrowExceptionForInvalidMongo()
  25. {
  26. $this->expectException(\InvalidArgumentException::class);
  27. new MongoDBHandler(new \stdClass, 'db', 'collection');
  28. }
  29. public function testHandleWithLibraryClient()
  30. {
  31. if (!class_exists(Client::class)) {
  32. $this->markTestSkipped('mongodb/mongodb not installed');
  33. }
  34. $client = $this->getMockBuilder(Client::class)
  35. ->disableOriginalConstructor()
  36. ->getMock();
  37. $collection = $this->getMockBuilder(Collection::class)
  38. ->disableOriginalConstructor()
  39. ->getMock();
  40. $client->expects($this->once())
  41. ->method('getCollection')
  42. ->with('db', 'collection')
  43. ->will($this->returnValue($collection));
  44. $record = $this->getRecord();
  45. $expected = $record;
  46. $expected['datetime'] = new UTCDateTime((int) floor(((float) $record['datetime']->format('U.u')) * 1000));
  47. $collection->expects($this->once())
  48. ->method('insertOne')
  49. ->with($expected);
  50. $handler = new MongoDBHandler($client, 'db', 'collection');
  51. $handler->handle($record);
  52. }
  53. public function testHandleWithDriverManager()
  54. {
  55. /* This can become a unit test once ManagerInterface can be mocked.
  56. * See: https://jira.mongodb.org/browse/PHPC-378
  57. */
  58. $mongodb = new Manager('mongodb://localhost:27017');
  59. $handler = new MongoDBHandler($mongodb, 'test', 'monolog');
  60. $record = $this->getRecord();
  61. try {
  62. $handler->handle($record);
  63. } catch (\RuntimeException $e) {
  64. $this->markTestSkipped('Could not connect to MongoDB server on mongodb://localhost:27017');
  65. }
  66. }
  67. }