You are here

public function SqlQueryTest::testGetConnection in Drupal 10

Same name and namespace in other branches
  1. 9 core/modules/views/tests/src/Kernel/Plugin/SqlQueryTest.php \Drupal\Tests\views\Kernel\Plugin\SqlQueryTest::testGetConnection()

Tests the method \Drupal\views\Plugin\views\query\Sql::getConnection().

@covers \Drupal\views\Plugin\views\query\Sql::getConnection

This needs to be a kernel test because the tested method uses the method \Drupal\Core\Database\Database::getConnection() which is a 'final' method and therefore cannot be mocked.

File

core/modules/views/tests/src/Kernel/Plugin/SqlQueryTest.php, line 92

Class

SqlQueryTest
Tests the sql query plugin.

Namespace

Drupal\Tests\views\Kernel\Plugin

Code

public function testGetConnection() {
  $view = Views::getView('test_view');
  $view
    ->setDisplay();

  // Add 3 database connections for the different options that the method
  // getConnection() supports.
  $connection_info = Database::getConnectionInfo('default');
  Database::addConnectionInfo('default', 'replica', $connection_info['default']);
  Database::addConnectionInfo('corefake', 'default', $connection_info['default']);
  Database::addConnectionInfo('corefake', 'replica', $connection_info['default']);

  // Test the database connection with no special options set.
  $this
    ->assertSame('default', $view
    ->getQuery()
    ->getConnection()
    ->getKey());
  $this
    ->assertSame('default', $view
    ->getQuery()
    ->getConnection()
    ->getTarget());

  // Test the database connection with the option 'replica' set to TRUE;
  $view
    ->getQuery()->options['replica'] = TRUE;
  $this
    ->assertSame('default', $view
    ->getQuery()
    ->getConnection()
    ->getKey());
  $this
    ->assertSame('replica', $view
    ->getQuery()
    ->getConnection()
    ->getTarget());

  // Test the database connection with the view 'base_database' set.
  $view
    ->getQuery()->options['replica'] = FALSE;
  $view->base_database = 'corefake';
  $this
    ->assertSame('corefake', $view
    ->getQuery()
    ->getConnection()
    ->getKey());
  $this
    ->assertSame('default', $view
    ->getQuery()
    ->getConnection()
    ->getTarget());

  // Test the database connection with the view 'base_database' set and the
  // option 'replica' set to TRUE.
  $view
    ->getQuery()->options['replica'] = TRUE;
  $this
    ->assertSame('corefake', $view
    ->getQuery()
    ->getConnection()
    ->getKey());
  $this
    ->assertSame('replica', $view
    ->getQuery()
    ->getConnection()
    ->getTarget());

  // Clean up the created database connections.
  Database::closeConnection('replica', 'default');
  Database::closeConnection('default', 'corefake');
  Database::closeConnection('replica', 'corefake');
}