DatabaseExceptionWrapperTest.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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 (\PDOException $e) {
  27. $this->pass('Expected PDOException was thrown.');
  28. }
  29. catch (DatabaseExceptionWrapper $e) {
  30. $this->pass('Expected DatabaseExceptionWrapper was thrown.');
  31. }
  32. catch (\Exception $e) {
  33. $this->fail("Thrown exception is not a PDOException:\n" . (string) $e);
  34. }
  35. }
  36. /**
  37. * Tests the expected database exception thrown for inexistent tables.
  38. */
  39. public function testQueryThrowsDatabaseExceptionWrapperException() {
  40. $connection = Database::getConnection();
  41. try {
  42. $connection->query('SELECT * FROM {does_not_exist}');
  43. $this->fail('Expected PDOException, none was thrown.');
  44. }
  45. catch (DatabaseExceptionWrapper $e) {
  46. $this->pass('Expected DatabaseExceptionWrapper was thrown.');
  47. }
  48. catch (\Exception $e) {
  49. $this->fail("Thrown exception is not a DatabaseExceptionWrapper:\n" . (string) $e);
  50. }
  51. }
  52. }