QueryLoggerTest.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  5. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  6. *
  7. * Licensed under The MIT License
  8. * For full copyright and license information, please see the LICENSE.txt
  9. * Redistributions of files must retain the above copyright notice.
  10. *
  11. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  12. * @link https://cakephp.org CakePHP(tm) Project
  13. * @since 3.0.0
  14. * @license https://opensource.org/licenses/mit-license.php MIT License
  15. */
  16. namespace Cake\Test\TestCase\Database\Log;
  17. use Cake\Database\Log\LoggedQuery;
  18. use Cake\Database\Log\QueryLogger;
  19. use Cake\Log\Log;
  20. use Cake\TestSuite\TestCase;
  21. use Psr\Log\LogLevel;
  22. /**
  23. * Tests QueryLogger class
  24. */
  25. class QueryLoggerTest extends TestCase
  26. {
  27. /**
  28. * Tear down
  29. */
  30. public function tearDown(): void
  31. {
  32. parent::tearDown();
  33. Log::drop('queryLoggerTest');
  34. Log::drop('queryLoggerTest2');
  35. }
  36. /**
  37. * Tests that the logged query object is passed to the built-in logger using
  38. * the correct scope
  39. */
  40. public function testLogFunction(): void
  41. {
  42. $logger = new QueryLogger(['connection' => '']);
  43. $query = new LoggedQuery();
  44. $query->setContext([
  45. 'query' => 'SELECT a FROM b where a = ? AND b = ? AND c = ?',
  46. 'params' => ['string', '3', null],
  47. ]);
  48. Log::setConfig('queryLoggerTest', [
  49. 'className' => 'Array',
  50. 'scopes' => ['queriesLog'],
  51. ]);
  52. Log::setConfig('queryLoggerTest2', [
  53. 'className' => 'Array',
  54. 'scopes' => ['foo'],
  55. ]);
  56. $logger->log(LogLevel::DEBUG, (string)$query, compact('query'));
  57. $this->assertCount(1, Log::engine('queryLoggerTest')->read());
  58. $this->assertCount(0, Log::engine('queryLoggerTest2')->read());
  59. }
  60. /**
  61. * Tests that the connection name is logged with the query.
  62. */
  63. public function testLogConnection(): void
  64. {
  65. $logger = new QueryLogger(['connection' => 'test']);
  66. $query = new LoggedQuery();
  67. $query->setContext(['query' => 'SELECT a']);
  68. Log::setConfig('queryLoggerTest', [
  69. 'className' => 'Array',
  70. 'scopes' => ['queriesLog'],
  71. ]);
  72. $logger->log(LogLevel::DEBUG, '', compact('query'));
  73. $this->assertStringContainsString('connection=test duration=', current(Log::engine('queryLoggerTest')->read()));
  74. }
  75. }