LoggingStatementTest.php 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  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\Connection;
  18. use Cake\Database\Driver;
  19. use Cake\Database\DriverInterface;
  20. use Cake\Database\Log\LoggingStatement;
  21. use Cake\Database\Log\QueryLogger;
  22. use Cake\Database\StatementInterface;
  23. use Cake\Log\Log;
  24. use Cake\TestSuite\TestCase;
  25. use DateTime;
  26. use TestApp\Error\Exception\MyPDOException;
  27. /**
  28. * Tests LoggingStatement class
  29. */
  30. class LoggingStatementTest extends TestCase
  31. {
  32. public function setUp(): void
  33. {
  34. parent::setUp();
  35. Log::setConfig('queries', [
  36. 'className' => 'Array',
  37. 'scopes' => ['queriesLog'],
  38. ]);
  39. }
  40. public function tearDown(): void
  41. {
  42. parent::tearDown();
  43. Log::drop('queries');
  44. }
  45. /**
  46. * Tests that queries are logged when executed without params
  47. */
  48. public function testExecuteNoParams(): void
  49. {
  50. $inner = $this->getMockBuilder(StatementInterface::class)->getMock();
  51. $inner->method('rowCount')->will($this->returnValue(3));
  52. $inner->method('execute')->will($this->returnValue(true));
  53. $driver = $this->getMockBuilder(Driver::class)->getMock();
  54. $driver->expects($this->any())
  55. ->method('getRole')
  56. ->will($this->returnValue(Connection::ROLE_WRITE));
  57. $st = $this->getMockBuilder(LoggingStatement::class)
  58. ->onlyMethods(['__get'])
  59. ->setConstructorArgs([$inner, $driver])
  60. ->getMock();
  61. $st->expects($this->any())
  62. ->method('__get')
  63. ->willReturn('SELECT bar FROM foo');
  64. $st->setLogger(new QueryLogger(['connection' => 'test']));
  65. $st->execute();
  66. $st->fetchAll();
  67. $messages = Log::engine('queries')->read();
  68. $this->assertCount(1, $messages);
  69. $this->assertMatchesRegularExpression('/^debug: connection=test role=write duration=\d+ rows=3 SELECT bar FROM foo$/', $messages[0]);
  70. }
  71. /**
  72. * Tests that queries are logged when executed with params
  73. */
  74. public function testExecuteWithParams(): void
  75. {
  76. $inner = $this->getMockBuilder(StatementInterface::class)->getMock();
  77. $inner->method('rowCount')->will($this->returnValue(4));
  78. $inner->method('execute')->will($this->returnValue(true));
  79. $driver = $this->getMockBuilder(Driver::class)->getMock();
  80. $driver->expects($this->any())
  81. ->method('getRole')
  82. ->will($this->returnValue(Connection::ROLE_WRITE));
  83. $st = $this->getMockBuilder(LoggingStatement::class)
  84. ->onlyMethods(['__get'])
  85. ->setConstructorArgs([$inner, $driver])
  86. ->getMock();
  87. $st->expects($this->any())
  88. ->method('__get')
  89. ->willReturn('SELECT bar FROM foo WHERE x=:a AND y=:b');
  90. $st->setLogger(new QueryLogger(['connection' => 'test']));
  91. $st->execute(['a' => 1, 'b' => 2]);
  92. $st->fetchAll();
  93. $messages = Log::engine('queries')->read();
  94. $this->assertCount(1, $messages);
  95. $this->assertMatchesRegularExpression('/^debug: connection=test role=write duration=\d+ rows=4 SELECT bar FROM foo WHERE x=1 AND y=2$/', $messages[0]);
  96. }
  97. /**
  98. * Tests that queries are logged when executed with bound params
  99. */
  100. public function testExecuteWithBinding(): void
  101. {
  102. $inner = $this->getMockBuilder(StatementInterface::class)->getMock();
  103. $inner->method('rowCount')->will($this->returnValue(4));
  104. $inner->method('execute')->will($this->returnValue(true));
  105. $date = new DateTime('2013-01-01');
  106. $inner->expects($this->atLeast(2))
  107. ->method('bindValue')
  108. ->withConsecutive(['a', 1], ['b', $date]);
  109. $driver = $this->getMockBuilder('Cake\Database\Driver')->getMock();
  110. $st = $this->getMockBuilder(LoggingStatement::class)
  111. ->onlyMethods(['__get'])
  112. ->setConstructorArgs([$inner, $driver])
  113. ->getMock();
  114. $st->expects($this->any())
  115. ->method('__get')
  116. ->willReturn('SELECT bar FROM foo WHERE a=:a AND b=:b');
  117. $st->setLogger(new QueryLogger(['connection' => 'test']));
  118. $st->bindValue('a', 1);
  119. $st->bindValue('b', $date, 'date');
  120. $st->execute();
  121. $st->fetchAll();
  122. $st->bindValue('b', new DateTime('2014-01-01'), 'date');
  123. $st->execute();
  124. $st->fetchAll();
  125. $messages = Log::engine('queries')->read();
  126. $this->assertCount(2, $messages);
  127. $this->assertMatchesRegularExpression("/^debug: connection=test role= duration=\d+ rows=4 SELECT bar FROM foo WHERE a='1' AND b='2013-01-01'$/", $messages[0]);
  128. $this->assertMatchesRegularExpression("/^debug: connection=test role= duration=\d+ rows=4 SELECT bar FROM foo WHERE a='1' AND b='2014-01-01'$/", $messages[1]);
  129. }
  130. /**
  131. * Tests that queries are logged despite database errors
  132. */
  133. public function testExecuteWithError(): void
  134. {
  135. $this->skipIf(
  136. version_compare(PHP_VERSION, '8.2.0', '>='),
  137. 'Setting queryString on exceptions does not work on 8.2+'
  138. );
  139. $exception = new MyPDOException('This is bad');
  140. $inner = $this->getMockBuilder(StatementInterface::class)->getMock();
  141. $inner->expects($this->once())
  142. ->method('execute')
  143. ->will($this->throwException($exception));
  144. $driver = $this->getMockBuilder(Driver::class)->getMock();
  145. $driver->expects($this->any())
  146. ->method('getRole')
  147. ->will($this->returnValue(Connection::ROLE_WRITE));
  148. $st = $this->getMockBuilder(LoggingStatement::class)
  149. ->onlyMethods(['__get'])
  150. ->setConstructorArgs([$inner, $driver])
  151. ->getMock();
  152. $st->expects($this->any())
  153. ->method('__get')
  154. ->willReturn('SELECT bar FROM foo');
  155. $st->setLogger(new QueryLogger(['connection' => 'test']));
  156. $this->deprecated(function () use ($st) {
  157. try {
  158. $st->execute();
  159. } catch (MyPDOException $e) {
  160. $this->assertSame('This is bad', $e->getMessage());
  161. $this->assertSame($st->queryString, $e->queryString);
  162. }
  163. });
  164. $messages = Log::engine('queries')->read();
  165. $this->assertCount(1, $messages);
  166. $this->assertMatchesRegularExpression("/^debug: connection=test role=write duration=\d+ rows=0 SELECT bar FROM foo$/", $messages[0]);
  167. }
  168. /**
  169. * Tests setting and getting the logger
  170. */
  171. public function testSetAndGetLogger(): void
  172. {
  173. $logger = new QueryLogger(['connection' => 'test']);
  174. $st = new LoggingStatement(
  175. $this->getMockBuilder(StatementInterface::class)->getMock(),
  176. $this->getMockBuilder(DriverInterface::class)->getMock()
  177. );
  178. $st->setLogger($logger);
  179. $this->assertSame($logger, $st->getLogger());
  180. }
  181. }