You are here

public function EntityDefinitionUpdateTest::testBaseFieldEntityKeyUpdateWithExistingData in Drupal 9

Same name and namespace in other branches
  1. 8 core/tests/Drupal/KernelTests/Core/Entity/EntityDefinitionUpdateTest.php \Drupal\KernelTests\Core\Entity\EntityDefinitionUpdateTest::testBaseFieldEntityKeyUpdateWithExistingData()

Tests updating a base field when it has existing data.

File

core/tests/Drupal/KernelTests/Core/Entity/EntityDefinitionUpdateTest.php, line 1132

Class

EntityDefinitionUpdateTest
Tests EntityDefinitionUpdateManager functionality.

Namespace

Drupal\KernelTests\Core\Entity

Code

public function testBaseFieldEntityKeyUpdateWithExistingData() {

  // Add the base field and run the update.
  $this
    ->addBaseField();
  $this
    ->applyEntityUpdates();

  // Save an entity with the base field populated.
  $this->entityTypeManager
    ->getStorage('entity_test_update')
    ->create([
    'new_base_field' => $this
      ->randomString(),
  ])
    ->save();

  // Save an entity with the base field not populated.

  /** @var \Drupal\entity_test\Entity\EntityTestUpdate $entity */
  $entity = $this->entityTypeManager
    ->getStorage('entity_test_update')
    ->create();
  $entity
    ->save();

  // Promote the base field to an entity key. This will trigger the addition
  // of a NOT NULL constraint.
  $this
    ->makeBaseFieldEntityKey();

  // Field storage CRUD operations use the last installed entity type
  // definition so we need to update it before doing any other field storage
  // updates.
  $this->entityDefinitionUpdateManager
    ->updateEntityType($this->state
    ->get('entity_test_update.entity_type'));

  // Try to apply the update and verify they fail since we have a NULL value.
  $message = 'An error occurs when trying to enabling NOT NULL constraints with NULL data.';
  try {
    $this
      ->applyEntityUpdates();
    $this
      ->fail($message);
  } catch (EntityStorageException $e) {

    // Expected exception; just continue testing.
  }

  // Check that the update is correctly applied when no NULL data is left.
  $entity
    ->set('new_base_field', $this
    ->randomString());
  $entity
    ->save();
  $this
    ->applyEntityUpdates();

  // Check that the update actually applied a NOT NULL constraint.
  $entity
    ->set('new_base_field', NULL);
  $message = 'The NOT NULL constraint was correctly applied.';
  try {
    $entity
      ->save();
    $this
      ->fail($message);
  } catch (EntityStorageException $e) {

    // Expected exception; just continue testing.
  }
}