DatabaseExceptionWrapperTest.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. <?php
  2. namespace Drupal\KernelTests\Core\Database;
  3. use Drupal\Core\Database\DatabaseExceptionWrapper;
  4. use Drupal\Core\Database\Database;
  5. use Drupal\KernelTests\KernelTestBase;
  6. /**
  7. * Tests exceptions thrown by queries.
  8. *
  9. * @group Database
  10. */
  11. class DatabaseExceptionWrapperTest extends KernelTestBase {
  12. /**
  13. * Tests the expected database exception thrown for prepared statements.
  14. */
  15. public function testPreparedStatement() {
  16. $connection = Database::getConnection();
  17. try {
  18. // SQLite validates the syntax upon preparing a statement already.
  19. // @throws \PDOException
  20. $query = $connection->prepare('bananas');
  21. // MySQL only validates the syntax upon trying to execute a query.
  22. // @throws \Drupal\Core\Database\DatabaseExceptionWrapper
  23. $connection->query($query);
  24. $this->fail('Expected PDOException or DatabaseExceptionWrapper, none was thrown.');
  25. }
  26. catch (\Exception $e) {
  27. $this->assertTrue($e instanceof \PDOException || $e instanceof DatabaseExceptionWrapper, 'Exception should be an instance of \PDOException or DatabaseExceptionWrapper, thrown ' . get_class($e));
  28. }
  29. }
  30. /**
  31. * Tests the expected database exception thrown for inexistent tables.
  32. */
  33. public function testQueryThrowsDatabaseExceptionWrapperException() {
  34. $this->expectException(DatabaseExceptionWrapper::class);
  35. Database::getConnection()->query('SELECT * FROM {does_not_exist}');
  36. }
  37. }