MongoDBHandlerTest.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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\Driver\Manager;
  12. /**
  13. * @requires extension mongodb
  14. */
  15. class MongoDBHandlerTest extends \Monolog\Test\MonologTestCase
  16. {
  17. public function testConstructorShouldThrowExceptionForInvalidMongo()
  18. {
  19. $this->expectException(\TypeError::class);
  20. new MongoDBHandler(new \stdClass, 'db', 'collection');
  21. }
  22. public function testHandleWithLibraryClient()
  23. {
  24. if (!(class_exists('MongoDB\Client'))) {
  25. $this->markTestSkipped('mongodb/mongodb not installed');
  26. }
  27. $mongodb = $this->getMockBuilder('MongoDB\Client')
  28. ->disableOriginalConstructor()
  29. ->getMock();
  30. $collection = $this->getMockBuilder('MongoDB\Collection')
  31. ->disableOriginalConstructor()
  32. ->getMock();
  33. $mongodb->expects($this->once())
  34. ->method('selectCollection')
  35. ->with('db', 'collection')
  36. ->willReturn($collection);
  37. $record = $this->getRecord();
  38. $expected = $record->toArray();
  39. $expected['datetime'] = new \MongoDB\BSON\UTCDateTime((int) floor(((float) $record->datetime->format('U.u')) * 1000));
  40. $collection->expects($this->once())
  41. ->method('insertOne')
  42. ->with($expected);
  43. $handler = new MongoDBHandler($mongodb, 'db', 'collection');
  44. $handler->handle($record);
  45. }
  46. public function testHandleWithDriverManager()
  47. {
  48. /* This can become a unit test once ManagerInterface can be mocked.
  49. * See: https://jira.mongodb.org/browse/PHPC-378
  50. */
  51. $mongodb = new Manager('mongodb://localhost:27017');
  52. $handler = new MongoDBHandler($mongodb, 'test', 'monolog');
  53. $record = $this->getRecord();
  54. try {
  55. $handler->handle($record);
  56. } catch (\RuntimeException $e) {
  57. $this->markTestSkipped('Could not connect to MongoDB server on mongodb://localhost:27017');
  58. }
  59. }
  60. }