3 namespace Drupal\Tests\migrate\Kernel;
5 use Drupal\Core\Database\Driver\sqlite\Connection;
8 * Base class for tests of Migrate source plugins that use a database.
10 abstract class MigrateSqlSourceTestBase extends MigrateSourceTestBase {
13 * Builds an in-memory SQLite database from a set of source data.
15 * @param array $source_data
16 * The source data, keyed by table name. Each table is an array containing
17 * the rows in that table.
19 * @return \Drupal\Core\Database\Driver\sqlite\Connection
20 * The SQLite database connection.
22 protected function getDatabase(array $source_data) {
23 // Create an in-memory SQLite database. Plugins can interact with it like
24 // any other database, and it will cease to exist when the connection is
26 $connection_options = ['database' => ':memory:'];
27 $pdo = Connection::open($connection_options);
28 $connection = new Connection($pdo, $connection_options);
30 // Create the tables and fill them with data.
31 foreach ($source_data as $table => $rows) {
32 // Use the biggest row to build the table schema.
33 $counts = array_map('count', $rows);
36 $pilot = $rows[key($counts)];
39 ->createTable($table, [
40 // SQLite uses loose affinity typing, so it's OK for every field to
42 'fields' => array_map(function() { return ['type' => 'text']; }, $pilot),
45 $fields = array_keys($pilot);
46 $insert = $connection->insert($table)->fields($fields);
47 array_walk($rows, [$insert, 'values']);
55 * Tests the source plugin against a particular data set.
57 * @param array $source_data
58 * The source data that the plugin will read. See getDatabase() for the
60 * @param array $expected_data
61 * The result rows the plugin is expected to return.
62 * @param int $expected_count
63 * (optional) How many rows the source plugin is expected to return.
64 * @param array $configuration
65 * (optional) Configuration for the source plugin.
66 * @param mixed $high_water
67 * (optional) The value of the high water field.
69 * @dataProvider providerSource
71 * @requires extension pdo_sqlite
73 public function testSource(array $source_data, array $expected_data, $expected_count = NULL, array $configuration = [], $high_water = NULL) {
74 $plugin = $this->getPlugin($configuration);
76 // Since we don't yet inject the database connection, we need to use a
77 // reflection hack to set it in the plugin instance.
78 $reflector = new \ReflectionObject($plugin);
79 $property = $reflector->getProperty('database');
80 $property->setAccessible(TRUE);
81 $property->setValue($plugin, $this->getDatabase($source_data));
83 parent::testSource($source_data, $expected_data, $expected_count, $configuration, $high_water);