function UpdateApiEntityDefinitionUpdateTest::testSingleUpdates

Tests that individual updates applied sequentially work as expected.

File

core/modules/system/tests/src/Functional/Entity/Update/UpdateApiEntityDefinitionUpdateTest.php, line 43

Class

UpdateApiEntityDefinitionUpdateTest
Tests performing entity updates through the Update API.

Namespace

Drupal\Tests\system\Functional\Entity\Update

Code

public function testSingleUpdates() {
    // Create a test entity.
    $user_ids = [
        mt_rand(),
        mt_rand(),
    ];
    $entity = EntityTest::create([
        'name' => $this->randomString(),
        'user_id' => $user_ids,
    ]);
    $entity->save();
    // Check that only a single value is stored for 'user_id'.
    $entity = $this->reloadEntity($entity);
    $this->assertCount(1, $entity->user_id);
    $this->assertEqual($entity->user_id->target_id, $user_ids[0]);
    // Make 'user_id' multiple by applying updates.
    $this->enableUpdates('entity_test', 'entity_definition_updates', 8001);
    $this->applyUpdates();
    // Ensure the 'entity_test__user_id' table got created.
    $this->assertTrue(\Drupal::database()->schema()
        ->tableExists('entity_test__user_id'));
    // Check that data was correctly migrated.
    $entity = $this->reloadEntity($entity);
    $this->assertCount(1, $entity->user_id);
    $this->assertEqual($entity->user_id->target_id, $user_ids[0]);
    // Store multiple data and check it is correctly stored.
    $entity->user_id = $user_ids;
    $entity->save();
    $entity = $this->reloadEntity($entity);
    $this->assertCount(2, $entity->user_id);
    $this->assertEqual($entity->user_id[0]->target_id, $user_ids[0]);
    $this->assertEqual($entity->user_id[1]->target_id, $user_ids[1]);
    // Make 'user_id' single again by applying updates.
    $this->enableUpdates('entity_test', 'entity_definition_updates', 8002);
    $this->applyUpdates();
    // Check that data was correctly migrated/dropped.
    $entity = $this->reloadEntity($entity);
    $this->assertCount(1, $entity->user_id);
    $this->assertEqual($entity->user_id->target_id, $user_ids[0]);
    // Check that only a single value is stored for 'user_id' again.
    $entity->user_id = $user_ids;
    $entity->save();
    $entity = $this->reloadEntity($entity);
    $this->assertCount(1, $entity->user_id);
    $this->assertEqual($entity->user_id[0]->target_id, $user_ids[0]);
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.