You are here

public function SqlImportTest::testImportActual in MongoDB 8.2

@covers ::getCollections @covers ::importPersistent @covers ::importExpirable

@dataProvider importProvider

File

modules/mongodb_storage/tests/src/Kernel/SqlImportTest.php, line 149

Class

SqlImportTest
Tests the import for the commands.mongodb.storage.import_keyvalue command.

Namespace

Drupal\Tests\mongodb_storage\Kernel

Code

public function testImportActual(string $table, string $service, string $prefix) {
  $columns = [];
  switch ($table) {
    case SqlImport::KVE_TABLE:
      $columns = array_keys(DatabaseStorageExpirable::schemaDefinition()['fields']);
      break;
    case SqlImport::KVP_TABLE:
      $columns = array_keys(DatabaseStorage::schemaDefinition()['fields']);
      break;
    default:
      $this
        ->fail("Unexpected table requested: {$table}.");
  }
  $actualPreDbCount = $this
    ->countTable($table);
  $this
    ->assertEquals(0, $actualPreDbCount);
  $actualPreMgCount = count($this
    ->getKvCollectionNames($prefix));
  $this
    ->assertEquals(0, $actualPreMgCount);

  // Avoid inserting nothing, or too much data.
  $rowCount = mt_rand(1, 100);
  $rows = [];
  $collection = $this
    ->randomMachineName();
  for ($i = 0; $i < $rowCount; $i++) {

    // Have a good chance to keep more than one value per collection.
    if (mt_rand(0, 10) >= 8) {
      $collection = $this
        ->randomMachineName();
    }
    $name = $this
      ->randomMachineName();

    // DatabaseStorage stores values as serialized PHP.
    $value = serialize($this
      ->randomString(1024));
    $row = [
      $collection,
      $name,
      $value,
    ];
    if (count($columns) === 4) {

      // Ensure test will have time to run before MongoDB expires data.
      $row[] = time() + 180;
    }
    $rows[] = $row;
  }
  $expectedCollections = [];
  foreach ($rows as $row) {
    $expectedCollections[$row[0]][$row[1]] = unserialize($row[2]);
  }
  ksort($expectedCollections);
  foreach ($expectedCollections as $name => &$values) {
    ksort($values);
  }
  $insert = $this->database
    ->insert($table)
    ->fields($columns);
  foreach ($rows as $row) {
    $insert
      ->values($row);
  }
  $insert
    ->execute();
  $this
    ->expectOutputString(self::IMPORT_OUTPUT);
  $this->sqlImport
    ->import();
  $keyValue = $this->container
    ->get($service);
  $mongoCollections = $this
    ->getKvCollectionNames($prefix);
  $this
    ->assertEquals(array_keys($expectedCollections), $mongoCollections, "Collection names match");
  foreach ($expectedCollections as $collectionName => $expected) {
    $all = $keyValue
      ->get($collectionName)
      ->getAll();
    ksort($all);
    $this
      ->assertEquals($expected, $all);
  }
}