MongoDBHandlerTest.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. class MongoDBHandlerTest extends TestCase
  14. {
  15. public function testConstructorShouldThrowExceptionForInvalidMongo()
  16. {
  17. $this->expectException(\InvalidArgumentException::class);
  18. new MongoDBHandler(new \stdClass, 'db', 'collection');
  19. }
  20. public function testHandleWithLibraryClient()
  21. {
  22. if (!(class_exists('MongoDB\Client'))) {
  23. $this->markTestSkipped('mongodb/mongodb not installed');
  24. }
  25. $mongodb = $this->getMockBuilder('MongoDB\Client')
  26. ->disableOriginalConstructor()
  27. ->getMock();
  28. $collection = $this->getMockBuilder('MongoDB\Collection')
  29. ->disableOriginalConstructor()
  30. ->getMock();
  31. $mongodb->expects($this->once())
  32. ->method('selectCollection')
  33. ->with('db', 'collection')
  34. ->will($this->returnValue($collection));
  35. $record = $this->getRecord();
  36. $expected = $record;
  37. $expected['datetime'] = new \MongoDB\BSON\UTCDateTime((int) floor(((float) $record['datetime']->format('U.u')) * 1000));
  38. $collection->expects($this->once())
  39. ->method('insertOne')
  40. ->with($expected);
  41. $handler = new MongoDBHandler($mongodb, 'db', 'collection');
  42. $handler->handle($record);
  43. }
  44. public function testHandleWithDriverManager()
  45. {
  46. if (!(class_exists('MongoDB\Driver\Manager'))) {
  47. $this->markTestSkipped('ext-mongodb not installed');
  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. }