QueryLoggerTest.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. * @return void
  31. */
  32. public function tearDown(): void
  33. {
  34. parent::tearDown();
  35. Log::drop('queryLoggerTest');
  36. Log::drop('queryLoggerTest2');
  37. }
  38. /**
  39. * Tests that the logged query object is passed to the built-in logger using
  40. * the correct scope
  41. *
  42. * @return void
  43. */
  44. public function testLogFunction()
  45. {
  46. $logger = new QueryLogger();
  47. $query = new LoggedQuery();
  48. $query->query = 'SELECT a FROM b where a = ? AND b = ? AND c = ?';
  49. $query->params = ['string', '3', null];
  50. Log::setConfig('queryLoggerTest', [
  51. 'className' => 'Array',
  52. 'scopes' => ['queriesLog'],
  53. ]);
  54. Log::setConfig('queryLoggerTest2', [
  55. 'className' => 'Array',
  56. 'scopes' => ['foo'],
  57. ]);
  58. $logger->log(LogLevel::DEBUG, (string)$query, compact('query'));
  59. $this->assertCount(1, Log::engine('queryLoggerTest')->read());
  60. $this->assertCount(0, Log::engine('queryLoggerTest2')->read());
  61. }
  62. /**
  63. * Tests that the connection name is logged with the query.
  64. *
  65. * @return void
  66. */
  67. public function testLogConnection()
  68. {
  69. $logger = new QueryLogger(['connection' => 'test']);
  70. $query = new LoggedQuery();
  71. $query->query = 'SELECT a';
  72. Log::setConfig('queryLoggerTest', [
  73. 'className' => 'Array',
  74. 'scopes' => ['queriesLog'],
  75. ]);
  76. $logger->log(LogLevel::DEBUG, '', compact('query'));
  77. $this->assertStringContainsString('connection=test duration=', current(Log::engine('queryLoggerTest')->read()));
  78. }
  79. }