DbCheckTest.php 10 KB

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