MongoDBHandlerTest.php 2.4 KB

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