MongoDBHandlerTest.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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 PHPUnit\Framework\Attributes\RequiresPhpExtension;
  16. #[RequiresPhpExtension('mongodb')]
  17. class MongoDBHandlerTest extends \Monolog\Test\MonologTestCase
  18. {
  19. public function testConstructorShouldThrowExceptionForInvalidMongo()
  20. {
  21. $this->expectException(\TypeError::class);
  22. new MongoDBHandler(new \stdClass, 'db', 'collection');
  23. }
  24. public function testHandleWithLibraryClient()
  25. {
  26. if (!class_exists(Client::class)) {
  27. $this->markTestSkipped('mongodb/mongodb not installed');
  28. }
  29. $client = $this->getMockBuilder(Client::class)
  30. ->disableOriginalConstructor()
  31. ->getMock();
  32. $collection = $this->getMockBuilder(Collection::class)
  33. ->disableOriginalConstructor()
  34. ->getMock();
  35. $client->expects($this->once())
  36. ->method('getCollection')
  37. ->with('db', 'collection')
  38. ->willReturn($collection);
  39. $record = $this->getRecord();
  40. $expected = $record->toArray();
  41. $expected['datetime'] = new UTCDateTime((int) floor(((float) $record->datetime->format('U.u')) * 1000));
  42. $collection->expects($this->once())
  43. ->method('insertOne')
  44. ->with($expected);
  45. $handler = new MongoDBHandler($client, 'db', 'collection');
  46. $handler->handle($record);
  47. }
  48. public function testHandleWithDriverManager()
  49. {
  50. $manager = new Manager('mongodb://localhost:27017');
  51. $handler = new MongoDBHandler($manager, 'test', 'monolog');
  52. $record = $this->getRecord();
  53. try {
  54. $handler->handle($record);
  55. } catch (\RuntimeException $e) {
  56. $this->markTestSkipped('Could not connect to MongoDB server on mongodb://localhost:27017');
  57. }
  58. }
  59. }