You are here

public function TestItemTest::testTestItem in Zircon Profile 8

Same name and namespace in other branches
  1. 8.0 core/modules/field/src/Tests/TestItemTest.php \Drupal\field\Tests\TestItemTest::testTestItem()

Tests using entity fields of the field field type.

File

core/modules/field/src/Tests/TestItemTest.php, line 54
Contains \Drupal\field\Tests\TestItemTest.

Class

TestItemTest
Tests the new entity API for the test field type.

Namespace

Drupal\field\Tests

Code

public function testTestItem() {

  // Verify entity creation.
  $entity = entity_create('entity_test');
  $value = rand(1, 10);
  $entity->field_test = $value;
  $entity->name->value = $this
    ->randomMachineName();
  $entity
    ->save();

  // Verify entity has been created properly.
  $id = $entity
    ->id();
  $entity = entity_load('entity_test', $id);
  $this
    ->assertTrue($entity->{$this->fieldName} instanceof FieldItemListInterface, 'Field implements interface.');
  $this
    ->assertTrue($entity->{$this->fieldName}[0] instanceof FieldItemInterface, 'Field item implements interface.');
  $this
    ->assertEqual($entity->{$this->fieldName}->value, $value);
  $this
    ->assertEqual($entity->{$this->fieldName}[0]->value, $value);

  // Verify changing the field value.
  $new_value = rand(1, 10);
  $entity->field_test->value = $new_value;
  $this
    ->assertEqual($entity->{$this->fieldName}->value, $new_value);

  // Read changed entity and assert changed values.
  $entity
    ->save();
  $entity = entity_load('entity_test', $id);
  $this
    ->assertEqual($entity->{$this->fieldName}->value, $new_value);

  // Test the schema for this field type.
  $expected_schema = array(
    'columns' => array(
      'value' => array(
        'type' => 'int',
        'size' => 'medium',
      ),
    ),
    'unique keys' => array(),
    'indexes' => array(
      'value' => array(
        'value',
      ),
    ),
    'foreign keys' => array(),
  );
  $field_schema = BaseFieldDefinition::create('test_field')
    ->getSchema();
  $this
    ->assertEqual($field_schema, $expected_schema);
}