Version 1
[yaffs-website] / web / core / tests / Drupal / KernelTests / Core / Database / DatabaseExceptionWrapperTest.php
1 <?php
2
3 namespace Drupal\KernelTests\Core\Database;
4
5 use Drupal\Core\Database\DatabaseExceptionWrapper;
6 use Drupal\Core\Database\Database;
7 use Drupal\KernelTests\KernelTestBase;
8
9 /**
10  * Tests exceptions thrown by queries.
11  *
12  * @group Database
13  */
14 class DatabaseExceptionWrapperTest extends KernelTestBase {
15
16   /**
17    * Tests the expected database exception thrown for prepared statements.
18    */
19   public function testPreparedStatement() {
20     $connection = Database::getConnection();
21     try {
22       // SQLite validates the syntax upon preparing a statement already.
23       // @throws \PDOException
24       $query = $connection->prepare('bananas');
25
26       // MySQL only validates the syntax upon trying to execute a query.
27       // @throws \Drupal\Core\Database\DatabaseExceptionWrapper
28       $connection->query($query);
29
30       $this->fail('Expected PDOException or DatabaseExceptionWrapper, none was thrown.');
31     }
32     catch (\PDOException $e) {
33       $this->pass('Expected PDOException was thrown.');
34     }
35     catch (DatabaseExceptionWrapper $e) {
36       $this->pass('Expected DatabaseExceptionWrapper was thrown.');
37     }
38     catch (\Exception $e) {
39       $this->fail("Thrown exception is not a PDOException:\n" . (string) $e);
40     }
41   }
42
43   /**
44    * Tests the expected database exception thrown for inexistent tables.
45    */
46   public function testQueryThrowsDatabaseExceptionWrapperException() {
47     $connection = Database::getConnection();
48     try {
49       $connection->query('SELECT * FROM {does_not_exist}');
50       $this->fail('Expected PDOException, none was thrown.');
51     }
52     catch (DatabaseExceptionWrapper $e) {
53       $this->pass('Expected DatabaseExceptionWrapper was thrown.');
54     }
55     catch (\Exception $e) {
56       $this->fail("Thrown exception is not a DatabaseExceptionWrapper:\n" . (string) $e);
57     }
58   }
59
60 }