MongoDBHandlerTest.php 2.2 KB

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