You are here

public function EntityDefinitionUpdateTest::testBaseFieldEntityKeyUpdateWithExistingData in Zircon Profile 8

Same name and namespace in other branches
  1. 8.0 core/modules/system/src/Tests/Entity/EntityDefinitionUpdateTest.php \Drupal\system\Tests\Entity\EntityDefinitionUpdateTest::testBaseFieldEntityKeyUpdateWithExistingData()

Tests updating a base field when it has existing data.

File

core/modules/system/src/Tests/Entity/EntityDefinitionUpdateTest.php, line 755
Contains \Drupal\system\Tests\Entity\EntityDefinitionUpdateTest.

Class

EntityDefinitionUpdateTest
Tests EntityDefinitionUpdateManager functionality.

Namespace

Drupal\system\Tests\Entity

Code

public function testBaseFieldEntityKeyUpdateWithExistingData() {

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

  // Save an entity with the base field populated.
  $this->entityManager
    ->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->entityManager
    ->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();

  // 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->entityDefinitionUpdateManager
      ->applyUpdates();
    $this
      ->fail($message);
  } catch (EntityStorageException $e) {
    $this
      ->pass($message);
  }

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

  // 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) {
    $this
      ->pass($message);
  }
}