DbCheckTest.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Tests\Unit\Service\Cron\Job;
  4. use App\Service\Cron\Job\DbCheck;
  5. use App\Service\Cron\UI\CronUIInterface;
  6. use Doctrine\DBAL\Connection;
  7. use Doctrine\DBAL\Result;
  8. use Doctrine\DBAL\Schema\AbstractSchemaManager;
  9. use Doctrine\ORM\EntityManagerInterface;
  10. use PHPUnit\Framework\MockObject\MockObject;
  11. use PHPUnit\Framework\TestCase;
  12. use Psr\Log\LoggerInterface;
  13. class DbCheckTest extends TestCase
  14. {
  15. private CronUIInterface|MockObject $ui;
  16. private MockObject|LoggerInterface $logger;
  17. private EntityManagerInterface|MockObject $entityManager;
  18. private Connection|MockObject $connection;
  19. private AbstractSchemaManager|MockObject $schemaManager;
  20. private DbCheck $dbCheck;
  21. public function setUp(): void
  22. {
  23. $this->ui = $this->getMockBuilder(CronUIInterface::class)->disableOriginalConstructor()->getMock();
  24. $this->logger = $this->getMockBuilder(LoggerInterface::class)->disableOriginalConstructor()->getMock();
  25. $this->entityManager = $this->getMockBuilder(EntityManagerInterface::class)->disableOriginalConstructor()->getMock();
  26. $this->connection = $this->getMockBuilder(Connection::class)->disableOriginalConstructor()->getMock();
  27. $this->entityManager->method('getConnection')->willReturn($this->connection);
  28. }
  29. /**
  30. * Sets up common connection expectations.
  31. */
  32. private function setupConnectionExpectations(): void
  33. {
  34. $this->connection->method('connect');
  35. $this->connection->method('isConnected')->willReturn(true);
  36. $this->connection->method('getParams')->willReturn([
  37. 'driver' => 'mysql',
  38. 'host' => 'localhost',
  39. 'port' => '3306',
  40. 'dbname' => 'testdb',
  41. 'user' => 'testuser',
  42. ]);
  43. }
  44. /**
  45. * Creates and sets up a schema manager mock.
  46. */
  47. private function setupSchemaManager(): AbstractSchemaManager|MockObject
  48. {
  49. $schemaManager = $this->getMockBuilder(AbstractSchemaManager::class)->disableOriginalConstructor()->getMock();
  50. $this->connection->method('createSchemaManager')->willReturn($schemaManager);
  51. return $schemaManager;
  52. }
  53. private function getMockFor(string $method): MockObject|DbCheck
  54. {
  55. $dbCheck = $this->getMockBuilder(DbCheck::class)
  56. ->setConstructorArgs([$this->entityManager])
  57. ->setMethodsExcept([$method, 'setLoggerInterface', 'setUI'])
  58. ->getMock();
  59. $dbCheck->setUI($this->ui);
  60. $dbCheck->setLoggerInterface($this->logger);
  61. return $dbCheck;
  62. }
  63. private function getMockWithConnection(string $method): MockObject|DbCheck
  64. {
  65. // Create a mock that allows us to override the private getDbConnection method
  66. $dbCheck = $this->getMockBuilder(DbCheck::class)
  67. ->setConstructorArgs([$this->entityManager])
  68. ->onlyMethods(['getDbConnection'])
  69. ->getMock();
  70. // Mock the getDbConnection method to return our connection
  71. $dbCheck->method('getDbConnection')->willReturn($this->connection);
  72. $dbCheck->setUI($this->ui);
  73. $dbCheck->setLoggerInterface($this->logger);
  74. return $dbCheck;
  75. }
  76. public function testPreview(): void
  77. {
  78. $dbCheck = $this->getMockFor('preview');
  79. $this->ui->expects(self::once())
  80. ->method('print')
  81. ->with('No preview available for this job');
  82. $dbCheck->preview();
  83. }
  84. public function testExecuteWithSuccessfulConnection(): void
  85. {
  86. $dbCheck = $this->getMockFor('execute');
  87. $schemaManager = $this->setupSchemaManager();
  88. $this->setupConnectionExpectations();
  89. $tables = ['table1', 'table2', 'messenger_messages'];
  90. $schemaManager->method('listTableNames')->willReturn($tables);
  91. $result1 = $this->getMockBuilder(Result::class)->disableOriginalConstructor()->getMock();
  92. $result1->method('fetchOne')->willReturn(10);
  93. $result2 = $this->getMockBuilder(Result::class)->disableOriginalConstructor()->getMock();
  94. $result2->method('fetchOne')->willReturn(20);
  95. $this->connection->expects(self::exactly(2))
  96. ->method('executeQuery')
  97. ->willReturnCallback(function ($query) use ($result1, $result2) {
  98. if (strpos($query, 'table1') !== false) {
  99. return $result1;
  100. } elseif (strpos($query, 'table2') !== false) {
  101. return $result2;
  102. }
  103. return $this->getMockBuilder(Result::class)->disableOriginalConstructor()->getMock();
  104. });
  105. $this->logger->expects(self::atLeastOnce())->method('info');
  106. $this->logger->expects(self::atLeastOnce())->method('debug');
  107. $this->logger->expects(self::never())->method('error');
  108. $this->logger->expects(self::never())->method('critical');
  109. $dbCheck->execute();
  110. }
  111. public function testExecuteWithEmptyTables(): void
  112. {
  113. $dbCheck = $this->getMockFor('execute');
  114. $schemaManager = $this->setupSchemaManager();
  115. $this->setupConnectionExpectations();
  116. // Include both regular tables and tables that should be ignored
  117. $tables = ['table1', 'table2', 'messenger_messages', 'enqueue', 'tag_control'];
  118. $schemaManager->method('listTableNames')->willReturn($tables);
  119. $emptyResult = $this->getMockBuilder(Result::class)->disableOriginalConstructor()->getMock();
  120. $emptyResult->method('fetchOne')->willReturn(0);
  121. // We expect exactly 2 queries (for table1 and table2)
  122. // The other tables (messenger_messages, enqueue, tag_control) should be ignored
  123. $this->connection
  124. ->expects(self::exactly(2))
  125. ->method('executeQuery')
  126. ->willReturnCallback(function ($query) use ($emptyResult) {
  127. // Verify that only non-ignored tables are queried
  128. if (strpos($query, 'messenger_messages') !== false
  129. || strpos($query, 'enqueue') !== false
  130. || strpos($query, 'tag_control') !== false) {
  131. $this->fail('Ignored table should not be queried: '.$query);
  132. }
  133. return $emptyResult;
  134. });
  135. // Verify debug logs for ignored tables
  136. $this->logger->expects(self::atLeastOnce())
  137. ->method('debug')
  138. ->with(self::logicalOr(
  139. self::stringContains('Nombre total de tables: 5'),
  140. self::stringContains('Table messenger_messages: -- ignored --'),
  141. self::stringContains('Table enqueue: -- ignored --'),
  142. self::stringContains('Table tag_control: -- ignored --'),
  143. self::stringContains('Table table1: 0 enregistrements'),
  144. self::stringContains('Table table2: 0 enregistrements'),
  145. self::anything() // Allow other debug messages
  146. ));
  147. // Verify critical log for empty tables detection
  148. $this->logger->expects(self::atLeastOnce())
  149. ->method('critical')
  150. ->with(self::stringContains('tables vides détectées'));
  151. // Verify error logs for empty tables list
  152. $this->logger->expects(self::atLeastOnce())
  153. ->method('error')
  154. ->withConsecutive(
  155. [self::identicalTo('Tables vides:')],
  156. [self::stringContains('- table1')],
  157. [self::stringContains('- table2')]
  158. );
  159. $this->logger->expects(self::atLeastOnce())->method('info');
  160. $dbCheck->execute();
  161. }
  162. /**
  163. * Test that the DbCheck class handles connection errors properly.
  164. */
  165. public function testConnectionError(): void
  166. {
  167. $dbCheck = $this->getMockFor('execute');
  168. $this->connection
  169. ->method('connect')
  170. ->willThrowException(new \RuntimeException('Connection error'));
  171. $this->entityManager
  172. ->method('getConnection')
  173. ->willReturn($this->connection);
  174. $this->logger->expects(self::atLeastOnce())->method('info');
  175. $this->logger->expects(self::atLeastOnce())->method('critical');
  176. $this->expectException(\Error::class);
  177. $dbCheck->execute();
  178. }
  179. public function testExecuteWithSchemaError(): void
  180. {
  181. $dbCheck = $this->getMockFor('execute');
  182. $schemaManager = $this->setupSchemaManager();
  183. $this->setupConnectionExpectations();
  184. // Setup schema manager to throw exception
  185. $schemaManager
  186. ->method('listTableNames')
  187. ->willThrowException(new \Exception('Schema error'));
  188. $this->logger->expects(self::atLeastOnce())->method('info');
  189. $this->logger->expects(self::once())->method('critical')
  190. ->with('Erreur lors de la vérification de l\'intégrité des données: Schema error');
  191. $dbCheck->execute();
  192. }
  193. public function testExecuteWithTableQueryException(): void
  194. {
  195. $dbCheck = $this->getMockFor('execute');
  196. $schemaManager = $this->setupSchemaManager();
  197. $this->setupConnectionExpectations();
  198. $tables = ['table1', 'table2', 'messenger_messages'];
  199. $schemaManager->method('listTableNames')->willReturn($tables);
  200. // Make executeQuery throw an exception for table1 but return normal results for table2
  201. $result2 = $this->getMockBuilder(Result::class)->disableOriginalConstructor()->getMock();
  202. $result2->method('fetchOne')->willReturn(20);
  203. $this->connection->expects(self::exactly(2))
  204. ->method('executeQuery')
  205. ->willReturnCallback(function ($query) use ($result2) {
  206. if (strpos($query, 'table1') !== false) {
  207. throw new \Exception('Error executing query on table1');
  208. } elseif (strpos($query, 'table2') !== false) {
  209. return $result2;
  210. }
  211. return $this->getMockBuilder(Result::class)->disableOriginalConstructor()->getMock();
  212. });
  213. // We expect a critical log for the table1 error
  214. $this->logger->expects(self::atLeastOnce())->method('critical')
  215. ->withConsecutive(
  216. [self::anything()],
  217. ['Impossible de vérifier la table table1: Error executing query on table1']
  218. );
  219. $this->logger->expects(self::atLeastOnce())->method('info');
  220. $this->logger->expects(self::atLeastOnce())->method('debug');
  221. $dbCheck->execute();
  222. }
  223. }