You are here

class EntityFieldTest in Zircon Profile 8

Same name and namespace in other branches
  1. 8.0 core/modules/system/src/Tests/Entity/EntityFieldTest.php \Drupal\system\Tests\Entity\EntityFieldTest

Tests the Entity Field API.

@group Entity

Hierarchy

Expanded class hierarchy of EntityFieldTest

File

core/modules/system/src/Tests/Entity/EntityFieldTest.php, line 26
Contains \Drupal\system\Tests\Entity\EntityFieldTest.

Namespace

Drupal\system\Tests\Entity
View source
class EntityFieldTest extends EntityUnitTestBase {

  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = array(
    'filter',
    'text',
    'node',
    'user',
    'field_test',
  );

  /**
   * @var string
   */
  protected $entityName;

  /**
   * @var \Drupal\user\Entity\User
   */
  protected $entityUser;

  /**
   * @var string
   */
  protected $entityFieldText;
  protected function setUp() {
    parent::setUp();
    foreach (entity_test_entity_types() as $entity_type_id) {

      // The entity_test schema is installed by the parent.
      if ($entity_type_id != 'entity_test') {
        $this
          ->installEntitySchema($entity_type_id);
      }
    }

    // Create the test field.
    module_load_install('entity_test');
    entity_test_install();

    // Install required default configuration for filter module.
    $this
      ->installConfig(array(
      'system',
      'filter',
    ));
  }

  /**
   * Creates a test entity.
   *
   * @return \Drupal\Core\Entity\EntityInterface
   */
  protected function createTestEntity($entity_type) {
    $this->entityName = $this
      ->randomMachineName();
    $this->entityUser = $this
      ->createUser();
    $this->entityFieldText = $this
      ->randomMachineName();

    // Pass in the value of the name field when creating. With the user
    // field we test setting a field after creation.
    $entity = entity_create($entity_type);
    $entity->user_id->target_id = $this->entityUser
      ->id();
    $entity->name->value = $this->entityName;

    // Set a value for the test field.
    $entity->field_test_text->value = $this->entityFieldText;
    return $entity;
  }

  /**
   * Tests reading and writing properties and field items.
   */
  public function testReadWrite() {

    // All entity variations have to have the same results.
    foreach (entity_test_entity_types() as $entity_type) {
      $this
        ->doTestReadWrite($entity_type);
    }
  }

  /**
   * Executes the read write test set for a defined entity type.
   *
   * @param string $entity_type
   *   The entity type to run the tests with.
   */
  protected function doTestReadWrite($entity_type) {
    $entity = $this
      ->createTestEntity($entity_type);
    $langcode = 'en';

    // Access the name field.
    $this
      ->assertTrue($entity->name instanceof FieldItemListInterface, format_string('%entity_type: Field implements interface', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertTrue($entity->name[0] instanceof FieldItemInterface, format_string('%entity_type: Field item implements interface', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertEqual($this->entityName, $entity->name->value, format_string('%entity_type: Name value can be read.', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertEqual($this->entityName, $entity->name[0]->value, format_string('%entity_type: Name value can be read through list access.', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertEqual($entity->name
      ->getValue(), array(
      0 => array(
        'value' => $this->entityName,
      ),
    ), format_string('%entity_type: Plain field value returned.', array(
      '%entity_type' => $entity_type,
    )));

    // Change the name.
    $new_name = $this
      ->randomMachineName();
    $entity->name->value = $new_name;
    $this
      ->assertEqual($new_name, $entity->name->value, format_string('%entity_type: Name can be updated and read.', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertEqual($entity->name
      ->getValue(), array(
      0 => array(
        'value' => $new_name,
      ),
    ), format_string('%entity_type: Plain field value reflects the update.', array(
      '%entity_type' => $entity_type,
    )));
    $new_name = $this
      ->randomMachineName();
    $entity->name[0]->value = $new_name;
    $this
      ->assertEqual($new_name, $entity->name->value, format_string('%entity_type: Name can be updated and read through list access.', array(
      '%entity_type' => $entity_type,
    )));

    // Access the user field.
    $this
      ->assertTrue($entity->user_id instanceof FieldItemListInterface, format_string('%entity_type: Field implements interface', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertTrue($entity->user_id[0] instanceof FieldItemInterface, format_string('%entity_type: Field item implements interface', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertEqual($this->entityUser
      ->id(), $entity->user_id->target_id, format_string('%entity_type: User id can be read.', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertEqual($this->entityUser
      ->getUsername(), $entity->user_id->entity->name->value, format_string('%entity_type: User name can be read.', array(
      '%entity_type' => $entity_type,
    )));

    // Change the assigned user by entity.
    $new_user1 = $this
      ->createUser();
    $entity->user_id->entity = $new_user1;
    $this
      ->assertEqual($new_user1
      ->id(), $entity->user_id->target_id, format_string('%entity_type: Updated user id can be read.', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertEqual($new_user1
      ->getUsername(), $entity->user_id->entity->name->value, format_string('%entity_type: Updated username value can be read.', array(
      '%entity_type' => $entity_type,
    )));

    // Change the assigned user by id.
    $new_user2 = $this
      ->createUser();
    $entity->user_id->target_id = $new_user2
      ->id();
    $this
      ->assertEqual($new_user2
      ->id(), $entity->user_id->target_id, format_string('%entity_type: Updated user id can be read.', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertEqual($new_user2
      ->getUsername(), $entity->user_id->entity->name->value, format_string('%entity_type: Updated username value can be read.', array(
      '%entity_type' => $entity_type,
    )));

    // Try unsetting a field property.
    $entity->name->value = NULL;
    $entity->user_id->target_id = NULL;
    $this
      ->assertNull($entity->name->value, format_string('%entity_type: Name field is not set.', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertNull($entity->user_id->target_id, format_string('%entity_type: User ID field is not set.', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertNull($entity->user_id->entity, format_string('%entity_type: User entity field is not set.', array(
      '%entity_type' => $entity_type,
    )));

    // Test setting the values via the typed data API works as well.
    // Change the assigned user by entity.
    $entity->user_id
      ->first()
      ->get('entity')
      ->setValue($new_user2);
    $this
      ->assertEqual($new_user2
      ->id(), $entity->user_id->target_id, format_string('%entity_type: Updated user id can be read.', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertEqual($new_user2
      ->getUsername(), $entity->user_id->entity->name->value, format_string('%entity_type: Updated user name value can be read.', array(
      '%entity_type' => $entity_type,
    )));

    // Change the assigned user by id.
    $entity->user_id
      ->first()
      ->get('target_id')
      ->setValue($new_user2
      ->id());
    $this
      ->assertEqual($new_user2
      ->id(), $entity->user_id->target_id, format_string('%entity_type: Updated user id can be read.', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertEqual($new_user2
      ->getUsername(), $entity->user_id->entity->name->value, format_string('%entity_type: Updated user name value can be read.', array(
      '%entity_type' => $entity_type,
    )));

    // Try unsetting a field.
    $entity->name
      ->first()
      ->get('value')
      ->setValue(NULL);
    $entity->user_id
      ->first()
      ->get('target_id')
      ->setValue(NULL);
    $this
      ->assertNull($entity->name->value, format_string('%entity_type: Name field is not set.', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertNull($entity->user_id->target_id, format_string('%entity_type: User ID field is not set.', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertNull($entity->user_id->entity, format_string('%entity_type: User entity field is not set.', array(
      '%entity_type' => $entity_type,
    )));

    // Create a fresh entity so target_id does not get its property object
    // instantiated, then verify setting a new value via typed data API works.
    $entity2 = entity_create($entity_type, array(
      'user_id' => array(
        'target_id' => $new_user1
          ->id(),
      ),
    ));

    // Access the property object, and set a value.
    $entity2->user_id
      ->first()
      ->get('target_id')
      ->setValue($new_user2
      ->id());
    $this
      ->assertEqual($new_user2
      ->id(), $entity2->user_id->target_id, format_string('%entity_type: Updated user id can be read.', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertEqual($new_user2->name->value, $entity2->user_id->entity->name->value, format_string('%entity_type: Updated user name value can be read.', array(
      '%entity_type' => $entity_type,
    )));

    // Test using isset(), empty() and unset().
    $entity->name->value = 'test unset';
    unset($entity->name->value);
    $this
      ->assertFalse(isset($entity->name->value), format_string('%entity_type: Name is not set.', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertFalse(isset($entity->name[0]->value), format_string('%entity_type: Name is not set.', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertTrue(empty($entity->name->value), format_string('%entity_type: Name is empty.', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertTrue(empty($entity->name[0]->value), format_string('%entity_type: Name is empty.', array(
      '%entity_type' => $entity_type,
    )));
    $entity->name->value = 'a value';
    $this
      ->assertTrue(isset($entity->name->value), format_string('%entity_type: Name is set.', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertTrue(isset($entity->name[0]->value), format_string('%entity_type: Name is set.', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertFalse(empty($entity->name->value), format_string('%entity_type: Name is not empty.', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertFalse(empty($entity->name[0]->value), format_string('%entity_type: Name is not empty.', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertTrue(isset($entity->name[0]), format_string('%entity_type: Name string item is set.', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertFalse(isset($entity->name[1]), format_string('%entity_type: Second name string item is not set as it does not exist', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertTrue(isset($entity->name), format_string('%entity_type: Name field is set.', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertFalse(isset($entity->nameInvalid), format_string('%entity_type: Not existing field is not set.', array(
      '%entity_type' => $entity_type,
    )));
    unset($entity->name[0]);
    $this
      ->assertFalse(isset($entity->name[0]), format_string('%entity_type: Name field item is not set.', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertFalse(isset($entity->name[0]->value), format_string('%entity_type: Name is not set.', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertFalse(isset($entity->name->value), format_string('%entity_type: Name is not set.', array(
      '%entity_type' => $entity_type,
    )));

    // Test emptying a field by assigning an empty value. NULL and array()
    // behave the same.
    foreach ([
      NULL,
      array(),
      'unset',
    ] as $empty) {

      // Make sure a value is present
      $entity->name->value = 'a value';
      $this
        ->assertTrue(isset($entity->name->value), format_string('%entity_type: Name is set.', array(
        '%entity_type' => $entity_type,
      )));

      // Now, empty the field.
      if ($empty === 'unset') {
        unset($entity->name);
      }
      else {
        $entity->name = $empty;
      }
      $this
        ->assertTrue(isset($entity->name), format_string('%entity_type: Name field is set.', array(
        '%entity_type' => $entity_type,
      )));
      $this
        ->assertTrue($entity->name
        ->isEmpty(), format_string('%entity_type: Name field is set.', array(
        '%entity_type' => $entity_type,
      )));
      $this
        ->assertIdentical(count($entity->name), 0, format_string('%entity_type: Name field contains no items.', array(
        '%entity_type' => $entity_type,
      )));
      $this
        ->assertIdentical($entity->name
        ->getValue(), array(), format_string('%entity_type: Name field value is an empty array.', array(
        '%entity_type' => $entity_type,
      )));
      $this
        ->assertFalse(isset($entity->name[0]), format_string('%entity_type: Name field item is not set.', array(
        '%entity_type' => $entity_type,
      )));
      $this
        ->assertFalse(isset($entity->name[0]->value), format_string('%entity_type: First name item value is not set.', array(
        '%entity_type' => $entity_type,
      )));
      $this
        ->assertFalse(isset($entity->name->value), format_string('%entity_type: Name value is not set.', array(
        '%entity_type' => $entity_type,
      )));
    }

    // Access the language field.
    $langcode_key = $this->entityManager
      ->getDefinition($entity_type)
      ->getKey('langcode');
    $this
      ->assertEqual($langcode, $entity->{$langcode_key}->value, format_string('%entity_type: Language code can be read.', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertEqual(\Drupal::languageManager()
      ->getLanguage($langcode), $entity->{$langcode_key}->language, format_string('%entity_type: Language object can be read.', array(
      '%entity_type' => $entity_type,
    )));

    // Change the language by code.
    $entity->{$langcode_key}->value = \Drupal::languageManager()
      ->getDefaultLanguage()
      ->getId();
    $this
      ->assertEqual(\Drupal::languageManager()
      ->getDefaultLanguage()
      ->getId(), $entity->{$langcode_key}->value, format_string('%entity_type: Language code can be read.', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertEqual(\Drupal::languageManager()
      ->getDefaultLanguage(), $entity->{$langcode_key}->language, format_string('%entity_type: Language object can be read.', array(
      '%entity_type' => $entity_type,
    )));

    // Revert language by code then try setting it by language object.
    $entity->{$langcode_key}->value = $langcode;
    $entity->{$langcode_key}->language = \Drupal::languageManager()
      ->getDefaultLanguage();
    $this
      ->assertEqual(\Drupal::languageManager()
      ->getDefaultLanguage()
      ->getId(), $entity->{$langcode_key}->value, format_string('%entity_type: Language code can be read.', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertEqual(\Drupal::languageManager()
      ->getDefaultLanguage(), $entity->{$langcode_key}->language, format_string('%entity_type: Language object can be read.', array(
      '%entity_type' => $entity_type,
    )));

    // Access the text field and test updating.
    $this
      ->assertEqual($entity->field_test_text->value, $this->entityFieldText, format_string('%entity_type: Text field can be read.', array(
      '%entity_type' => $entity_type,
    )));
    $new_text = $this
      ->randomMachineName();
    $entity->field_test_text->value = $new_text;
    $this
      ->assertEqual($entity->field_test_text->value, $new_text, format_string('%entity_type: Updated text field can be read.', array(
      '%entity_type' => $entity_type,
    )));

    // Test creating the entity by passing in plain values.
    $this->entityName = $this
      ->randomMachineName();
    $name_item[0]['value'] = $this->entityName;
    $this->entityUser = $this
      ->createUser();
    $user_item[0]['target_id'] = $this->entityUser
      ->id();
    $this->entityFieldText = $this
      ->randomMachineName();
    $text_item[0]['value'] = $this->entityFieldText;
    $entity = entity_create($entity_type, array(
      'name' => $name_item,
      'user_id' => $user_item,
      'field_test_text' => $text_item,
    ));
    $this
      ->assertEqual($this->entityName, $entity->name->value, format_string('%entity_type: Name value can be read.', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertEqual($this->entityUser
      ->id(), $entity->user_id->target_id, format_string('%entity_type: User id can be read.', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertEqual($this->entityUser
      ->getUsername(), $entity->user_id->entity->name->value, format_string('%entity_type: User name can be read.', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertEqual($this->entityFieldText, $entity->field_test_text->value, format_string('%entity_type: Text field can be read.', array(
      '%entity_type' => $entity_type,
    )));

    // Tests copying field values by assigning the TypedData objects.
    $entity2 = $this
      ->createTestEntity($entity_type);
    $entity2->name = $entity->name;
    $entity2->user_id = $entity->user_id;
    $entity2->field_test_text = $entity->field_test_text;
    $this
      ->assertFalse($entity->name === $entity2->name, format_string('%entity_type: Copying properties results in a different field object.', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertEqual($entity->name->value, $entity2->name->value, format_string('%entity_type: Name field copied.', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertEqual($entity->user_id->target_id, $entity2->user_id->target_id, format_string('%entity_type: User id field copied.', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertEqual($entity->field_test_text->value, $entity2->field_test_text->value, format_string('%entity_type: Text field copied.', array(
      '%entity_type' => $entity_type,
    )));

    // Tests that assigning TypedData objects to non-field properties keeps the
    // assigned value as is.
    $entity2 = $this
      ->createTestEntity($entity_type);
    $entity2->_not_a_field = $entity->name;
    $this
      ->assertTrue($entity2->_not_a_field === $entity->name, format_string('%entity_type: Typed data objects can be copied to non-field properties as is.', array(
      '%entity_type' => $entity_type,
    )));

    // Tests adding a value to a field item list.
    $entity->name[] = 'Another name';
    $this
      ->assertEqual($entity->name[1]->value, 'Another name', format_string('%entity_type: List item added via [] and the first property.', array(
      '%entity_type' => $entity_type,
    )));
    $entity->name[] = array(
      'value' => 'Third name',
    );
    $this
      ->assertEqual($entity->name[2]->value, 'Third name', format_string('%entity_type: List item added via [] and an array of properties.', array(
      '%entity_type' => $entity_type,
    )));
    $entity->name[3] = array(
      'value' => 'Fourth name',
    );
    $this
      ->assertEqual($entity->name[3]->value, 'Fourth name', format_string('%entity_type: List item added via offset and an array of properties.', array(
      '%entity_type' => $entity_type,
    )));
    unset($entity->name[3]);

    // Test removing and empty-ing list items.
    $this
      ->assertEqual(count($entity->name), 3, format_string('%entity_type: List has 3 items.', array(
      '%entity_type' => $entity_type,
    )));
    unset($entity->name[1]);
    $this
      ->assertEqual(count($entity->name), 2, format_string('%entity_type: Second list item has been removed.', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertEqual($entity->name[1]->value, 'Third name', format_string('%entity_type: The subsequent items have been shifted up.', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertEqual($entity->name[1]
      ->getName(), 1, format_string('%entity_type: The items names have been updated to their new delta.', array(
      '%entity_type' => $entity_type,
    )));
    $entity->name[1] = NULL;
    $this
      ->assertEqual(count($entity->name), 2, format_string('%entity_type: Assigning NULL does not reduce array count.', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertTrue($entity->name[1]
      ->isEmpty(), format_string('%entity_type: Assigning NULL empties the item.', array(
      '%entity_type' => $entity_type,
    )));

    // Test using isEmpty().
    unset($entity->name[1]);
    $this
      ->assertFalse($entity->name[0]
      ->isEmpty(), format_string('%entity_type: Name item is not empty.', array(
      '%entity_type' => $entity_type,
    )));
    $entity->name->value = NULL;
    $this
      ->assertTrue($entity->name[0]
      ->isEmpty(), format_string('%entity_type: Name item is empty.', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertTrue($entity->name
      ->isEmpty(), format_string('%entity_type: Name field is empty.', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertEqual(count($entity->name), 1, format_string('%entity_type: Empty item is considered when counting.', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertEqual(count(iterator_to_array($entity->name
      ->getIterator())), count($entity->name), format_string('%entity_type: Count matches iterator count.', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertTrue($entity->name
      ->getValue() === array(
      0 => array(
        'value' => NULL,
      ),
    ), format_string('%entity_type: Name field value contains a NULL value.', array(
      '%entity_type' => $entity_type,
    )));

    // Test using filterEmptyItems().
    $entity->name = array(
      NULL,
      'foo',
    );
    $this
      ->assertEqual(count($entity->name), 2, format_string('%entity_type: List has 2 items.', array(
      '%entity_type' => $entity_type,
    )));
    $entity->name
      ->filterEmptyItems();
    $this
      ->assertEqual(count($entity->name), 1, format_string('%entity_type: The empty item was removed.', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertEqual($entity->name[0]->value, 'foo', format_string('%entity_type: The items were renumbered.', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertEqual($entity->name[0]
      ->getName(), 0, format_string('%entity_type: The deltas were updated in the items.', array(
      '%entity_type' => $entity_type,
    )));

    // Test get and set field values.
    $entity->name = 'foo';
    $this
      ->assertEqual($entity->name[0]
      ->toArray(), array(
      'value' => 'foo',
    ), format_string('%entity_type: Field value has been retrieved via toArray()', array(
      '%entity_type' => $entity_type,
    )));
    $values = $entity
      ->toArray();
    $this
      ->assertEqual($values['name'], array(
      0 => array(
        'value' => 'foo',
      ),
    ), format_string('%entity_type: Field value has been retrieved via toArray() from an entity.', array(
      '%entity_type' => $entity_type,
    )));

    // Make sure the user id can be set to zero.
    $user_item[0]['target_id'] = 0;
    $entity = entity_create($entity_type, array(
      'name' => $name_item,
      'user_id' => $user_item,
      'field_test_text' => $text_item,
    ));
    $this
      ->assertNotNull($entity->user_id->target_id, format_string('%entity_type: User id is not NULL', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertIdentical($entity->user_id->target_id, 0, format_string('%entity_type: User id has been set to 0', array(
      '%entity_type' => $entity_type,
    )));

    // Test setting the ID with the value only.
    $entity = entity_create($entity_type, array(
      'name' => $name_item,
      'user_id' => 0,
      'field_test_text' => $text_item,
    ));
    $this
      ->assertNotNull($entity->user_id->target_id, format_string('%entity_type: User id is not NULL', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertIdentical($entity->user_id->target_id, 0, format_string('%entity_type: User id has been set to 0', array(
      '%entity_type' => $entity_type,
    )));
  }

  /**
   * Tries to save and load an entity again.
   */
  public function testSave() {

    // All entity variations have to have the same results.
    foreach (entity_test_entity_types() as $entity_type) {
      $this
        ->doTestSave($entity_type);
    }
  }

  /**
   * Executes the save tests for the given entity type.
   *
   * @param string $entity_type
   *   The entity type to run the tests with.
   */
  protected function doTestSave($entity_type) {
    $langcode_key = $this->entityManager
      ->getDefinition($entity_type)
      ->getKey('langcode');
    $entity = $this
      ->createTestEntity($entity_type);
    $entity
      ->save();
    $this
      ->assertTrue((bool) $entity
      ->id(), format_string('%entity_type: Entity has received an id.', array(
      '%entity_type' => $entity_type,
    )));
    $entity = entity_load($entity_type, $entity
      ->id());
    $this
      ->assertTrue((bool) $entity
      ->id(), format_string('%entity_type: Entity loaded.', array(
      '%entity_type' => $entity_type,
    )));

    // Access the name field.
    $this
      ->assertEqual(1, $entity->id->value, format_string('%entity_type: ID value can be read.', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertTrue(is_string($entity->uuid->value), format_string('%entity_type: UUID value can be read.', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertEqual('en', $entity->{$langcode_key}->value, format_string('%entity_type: Language code can be read.', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertEqual(\Drupal::languageManager()
      ->getLanguage('en'), $entity->{$langcode_key}->language, format_string('%entity_type: Language object can be read.', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertEqual($this->entityUser
      ->id(), $entity->user_id->target_id, format_string('%entity_type: User id can be read.', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertEqual($this->entityUser
      ->getUsername(), $entity->user_id->entity->name->value, format_string('%entity_type: User name can be read.', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertEqual($this->entityFieldText, $entity->field_test_text->value, format_string('%entity_type: Text field can be read.', array(
      '%entity_type' => $entity_type,
    )));
  }

  /**
   * Tests introspection and getting metadata upfront.
   */
  public function testIntrospection() {

    // All entity variations have to have the same results.
    foreach (entity_test_entity_types() as $entity_type) {
      $this
        ->doTestIntrospection($entity_type);
    }
  }

  /**
   * Executes the introspection tests for the given entity type.
   *
   * @param string $entity_type
   *   The entity type to run the tests with.
   */
  protected function doTestIntrospection($entity_type) {

    // Test getting metadata upfront. The entity types used for this test have
    // a default bundle that is the same as the entity type.
    $definitions = \Drupal::entityManager()
      ->getFieldDefinitions($entity_type, $entity_type);
    $this
      ->assertEqual($definitions['name']
      ->getType(), 'string', $entity_type . ': Name field found.');
    $this
      ->assertEqual($definitions['user_id']
      ->getType(), 'entity_reference', $entity_type . ': User field found.');
    $this
      ->assertEqual($definitions['field_test_text']
      ->getType(), 'text', $entity_type . ': Test-text-field field found.');

    // Test deriving further metadata.
    $this
      ->assertTrue($definitions['name'] instanceof FieldDefinitionInterface);
    $field_item_definition = $definitions['name']
      ->getItemDefinition();
    $this
      ->assertTrue($field_item_definition instanceof ComplexDataDefinitionInterface);
    $this
      ->assertEqual($field_item_definition
      ->getDataType(), 'field_item:string');
    $value_definition = $field_item_definition
      ->getPropertyDefinition('value');
    $this
      ->assertTrue($value_definition instanceof DataDefinitionInterface);
    $this
      ->assertEqual($value_definition
      ->getDataType(), 'string');

    // Test deriving metadata from references.
    $entity_definition = \Drupal\Core\Entity\TypedData\EntityDataDefinition::create($entity_type);
    $langcode_key = $this->entityManager
      ->getDefinition($entity_type)
      ->getKey('langcode');
    $reference_definition = $entity_definition
      ->getPropertyDefinition($langcode_key)
      ->getPropertyDefinition('language')
      ->getTargetDefinition();
    $this
      ->assertEqual($reference_definition
      ->getDataType(), 'language');
    $reference_definition = $entity_definition
      ->getPropertyDefinition('user_id')
      ->getPropertyDefinition('entity')
      ->getTargetDefinition();
    $this
      ->assertTrue($reference_definition instanceof \Drupal\Core\Entity\TypedData\EntityDataDefinitionInterface, 'Definition of the referenced user retrieved.');
    $this
      ->assertEqual($reference_definition
      ->getEntityTypeId(), 'user', 'Referenced entity is of type "user".');

    // Test propagating down.
    $name_definition = $reference_definition
      ->getPropertyDefinition('name');
    $this
      ->assertTrue($name_definition instanceof FieldDefinitionInterface);
    $this
      ->assertEqual($name_definition
      ->getPropertyDefinition('value')
      ->getDataType(), 'string');

    // Test introspecting an entity object.
    // @todo: Add bundles and test bundles as well.
    $entity = entity_create($entity_type);
    $definitions = $entity
      ->getFieldDefinitions();
    $this
      ->assertEqual($definitions['name']
      ->getType(), 'string', $entity_type . ': Name field found.');
    $this
      ->assertEqual($definitions['user_id']
      ->getType(), 'entity_reference', $entity_type . ': User field found.');
    $this
      ->assertEqual($definitions['field_test_text']
      ->getType(), 'text', $entity_type . ': Test-text-field field found.');
    $name_properties = $entity->name
      ->getFieldDefinition()
      ->getPropertyDefinitions();
    $this
      ->assertEqual($name_properties['value']
      ->getDataType(), 'string', $entity_type . ': String value property of the name found.');
    $userref_properties = $entity->user_id
      ->getFieldDefinition()
      ->getPropertyDefinitions();
    $this
      ->assertEqual($userref_properties['target_id']
      ->getDataType(), 'integer', $entity_type . ': Entity id property of the user found.');
    $this
      ->assertEqual($userref_properties['entity']
      ->getDataType(), 'entity_reference', $entity_type . ': Entity reference property of the user found.');
    $textfield_properties = $entity->field_test_text
      ->getFieldDefinition()
      ->getFieldStorageDefinition()
      ->getPropertyDefinitions();
    $this
      ->assertEqual($textfield_properties['value']
      ->getDataType(), 'string', $entity_type . ': String value property of the test-text field found.');
    $this
      ->assertEqual($textfield_properties['format']
      ->getDataType(), 'filter_format', $entity_type . ': String format field of the test-text field found.');
    $this
      ->assertEqual($textfield_properties['processed']
      ->getDataType(), 'string', $entity_type . ': String processed property of the test-text field found.');

    // Make sure provided contextual information is right.
    $entity_adapter = $entity
      ->getTypedData();
    $this
      ->assertIdentical($entity_adapter
      ->getRoot(), $entity_adapter, 'Entity is root object.');
    $this
      ->assertEqual($entity_adapter
      ->getPropertyPath(), '');
    $this
      ->assertEqual($entity_adapter
      ->getName(), '');
    $this
      ->assertEqual($entity_adapter
      ->getParent(), NULL);
    $field = $entity->user_id;
    $this
      ->assertIdentical($field
      ->getRoot()
      ->getValue(), $entity, 'Entity is root object.');
    $this
      ->assertIdentical($field
      ->getEntity(), $entity, 'getEntity() returns the entity.');
    $this
      ->assertEqual($field
      ->getPropertyPath(), 'user_id');
    $this
      ->assertEqual($field
      ->getName(), 'user_id');
    $this
      ->assertIdentical($field
      ->getParent()
      ->getValue(), $entity, 'Parent object matches.');
    $field_item = $field[0];
    $this
      ->assertIdentical($field_item
      ->getRoot()
      ->getValue(), $entity, 'Entity is root object.');
    $this
      ->assertIdentical($field_item
      ->getEntity(), $entity, 'getEntity() returns the entity.');
    $this
      ->assertEqual($field_item
      ->getPropertyPath(), 'user_id.0');
    $this
      ->assertEqual($field_item
      ->getName(), '0');
    $this
      ->assertIdentical($field_item
      ->getParent(), $field, 'Parent object matches.');
    $item_value = $field_item
      ->get('entity');
    $this
      ->assertIdentical($item_value
      ->getRoot()
      ->getValue(), $entity, 'Entity is root object.');
    $this
      ->assertEqual($item_value
      ->getPropertyPath(), 'user_id.0.entity');
    $this
      ->assertEqual($item_value
      ->getName(), 'entity');
    $this
      ->assertIdentical($item_value
      ->getParent(), $field_item, 'Parent object matches.');
  }

  /**
   * Tests iterating over properties.
   */
  public function testIterator() {

    // All entity variations have to have the same results.
    foreach (entity_test_entity_types() as $entity_type) {
      $this
        ->doTestIterator($entity_type);
    }
  }

  /**
   * Executes the iterator tests for the given entity type.
   *
   * @param string $entity_type
   *   The entity type to run the tests with.
   */
  protected function doTestIterator($entity_type) {
    $entity = $this
      ->createTestEntity($entity_type);
    foreach ($entity as $name => $field) {
      $this
        ->assertTrue($field instanceof FieldItemListInterface, $entity_type . ": Field {$name} implements interface.");
      foreach ($field as $delta => $item) {
        $this
          ->assertTrue($field[0] instanceof FieldItemInterface, $entity_type . ": Item {$delta} of field {$name} implements interface.");
        foreach ($item as $value_name => $value_property) {
          $this
            ->assertTrue($value_property instanceof TypedDataInterface, $entity_type . ": Value {$value_name} of item {$delta} of field {$name} implements interface.");
          $value = $value_property
            ->getValue();
          $this
            ->assertTrue(!isset($value) || is_scalar($value) || $value instanceof EntityInterface, $entity_type . ": Value {$value_name} of item {$delta} of field {$name} is a primitive or an entity.");
        }
      }
    }
    $fields = $entity
      ->getFields();
    $this
      ->assertEqual(array_keys($fields), array_keys($entity
      ->getTypedData()
      ->getDataDefinition()
      ->getPropertyDefinitions()), format_string('%entity_type: All fields returned.', array(
      '%entity_type' => $entity_type,
    )));
    $this
      ->assertEqual($fields, iterator_to_array($entity
      ->getIterator()), format_string('%entity_type: Entity iterator iterates over all fields.', array(
      '%entity_type' => $entity_type,
    )));
  }

  /**
   * Tests working with the entity based upon the TypedData API.
   */
  public function testDataStructureInterfaces() {

    // All entity variations have to have the same results.
    foreach (entity_test_entity_types() as $entity_type) {
      $this
        ->doTestDataStructureInterfaces($entity_type);
    }
  }

  /**
   * Executes the data structure interfaces tests for the given entity type.
   *
   * @param string $entity_type
   *   The entity type to run the tests with.
   */
  protected function doTestDataStructureInterfaces($entity_type) {
    $entity = $this
      ->createTestEntity($entity_type);

    // Test using the whole tree of typed data by navigating through the tree of
    // contained properties and getting all contained strings, limited by a
    // certain depth.
    $strings = array();
    $this
      ->getContainedStrings($entity
      ->getTypedData(), 0, $strings);

    // @todo: Once the user entity has defined properties this should contain
    // the user name and other user entity strings as well.
    $target_strings = array(
      $entity->uuid->value,
      'en',
      $this->entityName,
      // Bundle name.
      $entity
        ->bundle(),
      $this->entityFieldText,
      // Field format.
      NULL,
    );
    asort($strings);
    asort($target_strings);
    $this
      ->assertEqual(array_values($strings), array_values($target_strings), format_string('%entity_type: All contained strings found.', array(
      '%entity_type' => $entity_type,
    )));
  }

  /**
   * Recursive helper for getting all contained strings,
   * i.e. properties of type string.
   */
  public function getContainedStrings(TypedDataInterface $wrapper, $depth, array &$strings) {
    if ($wrapper instanceof StringInterface) {
      $strings[] = $wrapper
        ->getValue();
    }

    // Recurse until a certain depth is reached if possible.
    if ($depth < 7) {
      if ($wrapper instanceof \Drupal\Core\TypedData\ListInterface) {
        foreach ($wrapper as $item) {
          $this
            ->getContainedStrings($item, $depth + 1, $strings);
        }
      }
      elseif ($wrapper instanceof \Drupal\Core\TypedData\ComplexDataInterface) {
        foreach ($wrapper as $property) {
          $this
            ->getContainedStrings($property, $depth + 1, $strings);
        }
      }
    }
  }

  /**
   * Makes sure data types are correctly derived for all entity types.
   */
  public function testDataTypes() {
    $types = \Drupal::typedDataManager()
      ->getDefinitions();
    foreach (entity_test_entity_types() as $entity_type) {
      $this
        ->assertTrue($types['entity:' . $entity_type]['class'], 'Entity data type registered.');
    }

    // Check bundle types are provided as well.
    entity_test_create_bundle('bundle');
    $types = \Drupal::typedDataManager()
      ->getDefinitions();
    $this
      ->assertTrue($types['entity:entity_test:bundle']['class'], 'Entity bundle data type registered.');
  }

  /**
   * Tests a base field override on a non-existing base field.
   *
   * @see entity_test_entity_base_field_info_alter()
   */
  public function testBaseFieldNonExistingBaseField() {
    $this->entityManager
      ->getStorage('node_type')
      ->create(array(
      'type' => 'page',
      'name' => 'page',
    ))
      ->save();
    $this->entityManager
      ->clearCachedFieldDefinitions();
    $fields = $this->entityManager
      ->getFieldDefinitions('node', 'page');
    $override = $fields['status']
      ->getConfig('page');
    $override
      ->setLabel($this
      ->randomString())
      ->save();
    \Drupal::state()
      ->set('entity_test.node_remove_status_field', TRUE);
    $this->entityManager
      ->clearCachedFieldDefinitions();
    $fields = $this->entityManager
      ->getFieldDefinitions('node', 'page');

    // A base field override on a non-existing base field should not cause a
    // field definition to come into existence.
    $this
      ->assertFalse(isset($fields['status']), 'Node\'s status base field does not exist.');
  }

  /**
   * Tests creating a field override config for a bundle field.
   *
   * @see entity_test_entity_base_field_info_alter()
   */
  public function testFieldOverrideBundleField() {

    // First make sure the bundle field override in code, which is provided by
    // the test entity works.
    entity_test_create_bundle('some_test_bundle', 'Some test bundle', 'entity_test_field_override');
    $field_definitions = $this->entityManager
      ->getFieldDefinitions('entity_test_field_override', 'entity_test_field_override');
    $this
      ->assertEqual($field_definitions['name']
      ->getDescription(), 'The default description.');
    $this
      ->assertNull($field_definitions['name']
      ->getTargetBundle());
    $field_definitions = $this->entityManager
      ->getFieldDefinitions('entity_test_field_override', 'some_test_bundle');
    $this
      ->assertEqual($field_definitions['name']
      ->getDescription(), 'Custom description.');
    $this
      ->assertEqual($field_definitions['name']
      ->getTargetBundle(), 'some_test_bundle');

    // Now create a config override of the bundle field.
    $field_config = $field_definitions['name']
      ->getConfig('some_test_bundle');
    $field_config
      ->setTranslatable(FALSE);
    $field_config
      ->save();

    // Make sure both overrides are present.
    $this->entityManager
      ->clearCachedFieldDefinitions();
    $field_definitions = $this->entityManager
      ->getFieldDefinitions('entity_test_field_override', 'some_test_bundle');
    $this
      ->assertEqual($field_definitions['name']
      ->getDescription(), 'Custom description.');
    $this
      ->assertEqual($field_definitions['name']
      ->getTargetBundle(), 'some_test_bundle');
    $this
      ->assertFalse($field_definitions['name']
      ->isTranslatable());
  }

  /**
   * Tests validation constraints provided by the Entity API.
   */
  public function testEntityConstraintValidation() {
    $entity = $this
      ->createTestEntity('entity_test');
    $entity
      ->save();

    // Create a reference field item and let it reference the entity.
    $definition = BaseFieldDefinition::create('entity_reference')
      ->setLabel('Test entity')
      ->setSetting('target_type', 'entity_test');
    $reference_field = \Drupal::typedDataManager()
      ->create($definition);
    $reference = $reference_field
      ->appendItem(array(
      'entity' => $entity,
    ))
      ->get('entity');

    // Test validation the typed data object.
    $violations = $reference
      ->validate();
    $this
      ->assertEqual($violations
      ->count(), 0);

    // Test validating an entity of the wrong type.
    $user = $this
      ->createUser();
    $user
      ->save();
    $node = entity_create('node', array(
      'type' => 'page',
      'uid' => $user
        ->id(),
      'title' => $this
        ->randomString(),
    ));
    $reference
      ->setValue($node);
    $violations = $reference
      ->validate();
    $this
      ->assertEqual($violations
      ->count(), 1);

    // Test bundle validation.
    NodeType::create(array(
      'type' => 'article',
    ))
      ->save();
    $definition = BaseFieldDefinition::create('entity_reference')
      ->setLabel('Test entity')
      ->setSetting('target_type', 'node')
      ->setSetting('handler_settings', [
      'target_bundles' => [
        'article' => 'article',
      ],
    ]);
    $reference_field = \Drupal::TypedDataManager()
      ->create($definition);
    $reference_field
      ->appendItem(array(
      'entity' => $node,
    ));
    $violations = $reference_field
      ->validate();
    $this
      ->assertEqual($violations
      ->count(), 1);
    $node = entity_create('node', array(
      'type' => 'article',
      'uid' => $user
        ->id(),
      'title' => $this
        ->randomString(),
    ));
    $node
      ->save();
    $reference_field->entity = $node;
    $violations = $reference_field
      ->validate();
    $this
      ->assertEqual($violations
      ->count(), 0);
  }

  /**
   * Tests getting processed property values via a computed property.
   */
  public function testComputedProperties() {

    // All entity variations have to have the same results.
    foreach (entity_test_entity_types() as $entity_type) {
      $this
        ->doTestComputedProperties($entity_type);
    }
  }

  /**
   * Executes the computed properties tests for the given entity type.
   *
   * @param string $entity_type
   *   The entity type to run the tests with.
   */
  protected function doTestComputedProperties($entity_type) {
    $entity = $this
      ->createTestEntity($entity_type);
    $entity->field_test_text->value = "The <strong>text</strong> text to filter.";
    $entity->field_test_text->format = filter_default_format();
    $target = "<p>The &lt;strong&gt;text&lt;/strong&gt; text to filter.</p>\n";
    $this
      ->assertEqual($entity->field_test_text->processed, $target, format_string('%entity_type: Text is processed with the default filter.', array(
      '%entity_type' => $entity_type,
    )));

    // Save and load entity and make sure it still works.
    $entity
      ->save();
    $entity = entity_load($entity_type, $entity
      ->id());
    $this
      ->assertEqual($entity->field_test_text->processed, $target, format_string('%entity_type: Text is processed with the default filter.', array(
      '%entity_type' => $entity_type,
    )));
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AssertContentTrait::$content protected property The current raw content.
AssertContentTrait::$drupalSettings protected property The drupalSettings value from the current raw $content.
AssertContentTrait::$elements protected property The XML structure parsed from the current raw $content. 2
AssertContentTrait::$plainTextContent protected property The plain-text content of raw $content (text nodes).
AssertContentTrait::assertEscaped protected function Passes if the raw text IS found escaped on the loaded page, fail otherwise.
AssertContentTrait::assertField protected function Asserts that a field exists with the given name or ID.
AssertContentTrait::assertFieldById protected function Asserts that a field exists with the given ID and value.
AssertContentTrait::assertFieldByName protected function Asserts that a field exists with the given name and value.
AssertContentTrait::assertFieldByXPath protected function Asserts that a field exists in the current page by the given XPath.
AssertContentTrait::assertFieldChecked protected function Asserts that a checkbox field in the current page is checked.
AssertContentTrait::assertFieldsByValue protected function Asserts that a field exists in the current page with a given Xpath result.
AssertContentTrait::assertLink protected function Passes if a link with the specified label is found.
AssertContentTrait::assertLinkByHref protected function Passes if a link containing a given href (part) is found.
AssertContentTrait::assertNoDuplicateIds protected function Asserts that each HTML ID is used for just a single element.
AssertContentTrait::assertNoEscaped protected function Passes if the raw text IS NOT found escaped on the loaded page, fail otherwise.
AssertContentTrait::assertNoField protected function Asserts that a field does not exist with the given name or ID.
AssertContentTrait::assertNoFieldById protected function Asserts that a field does not exist with the given ID and value.
AssertContentTrait::assertNoFieldByName protected function Asserts that a field does not exist with the given name and value.
AssertContentTrait::assertNoFieldByXPath protected function Asserts that a field does not exist or its value does not match, by XPath.
AssertContentTrait::assertNoFieldChecked protected function Asserts that a checkbox field in the current page is not checked.
AssertContentTrait::assertNoLink protected function Passes if a link with the specified label is not found.
AssertContentTrait::assertNoLinkByHref protected function Passes if a link containing a given href (part) is not found.
AssertContentTrait::assertNoLinkByHrefInMainRegion protected function Passes if a link containing a given href is not found in the main region.
AssertContentTrait::assertNoOption protected function Asserts that a select option in the current page does not exist.
AssertContentTrait::assertNoOptionSelected protected function Asserts that a select option in the current page is not checked.
AssertContentTrait::assertNoPattern protected function Triggers a pass if the perl regex pattern is not found in raw content.
AssertContentTrait::assertNoRaw protected function Passes if the raw text is NOT found on the loaded page, fail otherwise.
AssertContentTrait::assertNoText protected function Passes if the page (with HTML stripped) does not contains the text.
AssertContentTrait::assertNoTitle protected function Pass if the page title is not the given string.
AssertContentTrait::assertNoUniqueText protected function Passes if the text is found MORE THAN ONCE on the text version of the page.
AssertContentTrait::assertOption protected function Asserts that a select option in the current page exists.
AssertContentTrait::assertOptionSelected protected function Asserts that a select option in the current page is checked.
AssertContentTrait::assertOptionSelectedWithDrupalSelector protected function Asserts that a select option in the current page is checked.
AssertContentTrait::assertOptionWithDrupalSelector protected function Asserts that a select option in the current page exists.
AssertContentTrait::assertPattern protected function Triggers a pass if the Perl regex pattern is found in the raw content.
AssertContentTrait::assertRaw protected function Passes if the raw text IS found on the loaded page, fail otherwise.
AssertContentTrait::assertText protected function Passes if the page (with HTML stripped) contains the text.
AssertContentTrait::assertTextHelper protected function Helper for assertText and assertNoText.
AssertContentTrait::assertTextPattern protected function Asserts that a Perl regex pattern is found in the plain-text content.
AssertContentTrait::assertThemeOutput protected function Asserts themed output.
AssertContentTrait::assertTitle protected function Pass if the page title is the given string.
AssertContentTrait::assertUniqueText protected function Passes if the text is found ONLY ONCE on the text version of the page.
AssertContentTrait::assertUniqueTextHelper protected function Helper for assertUniqueText and assertNoUniqueText.
AssertContentTrait::buildXPathQuery protected function Builds an XPath query.
AssertContentTrait::constructFieldXpath protected function Helper: Constructs an XPath for the given set of attributes and value.
AssertContentTrait::cssSelect protected function Searches elements using a CSS selector in the raw content.
AssertContentTrait::getAllOptions protected function Get all option elements, including nested options, in a select.
AssertContentTrait::getDrupalSettings protected function Gets the value of drupalSettings for the currently-loaded page.
AssertContentTrait::getRawContent protected function Gets the current raw content.
AssertContentTrait::getSelectedItem protected function Get the selected value from a select field.
AssertContentTrait::getTextContent protected function Retrieves the plain-text content from the current raw content.
AssertContentTrait::getUrl protected function Get the current URL from the cURL handler. 1
AssertContentTrait::parse protected function Parse content returned from curlExec using DOM and SimpleXML.
AssertContentTrait::removeWhiteSpace protected function Removes all white-space between HTML tags from the raw content.
AssertContentTrait::setDrupalSettings protected function Sets the value of drupalSettings for the currently-loaded page.
AssertContentTrait::setRawContent protected function Sets the raw content (e.g. HTML).
AssertContentTrait::xpath protected function Performs an xpath search on the contents of the internal browser.
AssertHelperTrait::castSafeStrings protected function Casts MarkupInterface objects into strings.
EntityFieldTest::$entityFieldText protected property
EntityFieldTest::$entityName protected property
EntityFieldTest::$entityUser protected property
EntityFieldTest::$modules public static property Modules to enable. Overrides EntityUnitTestBase::$modules
EntityFieldTest::createTestEntity protected function Creates a test entity.
EntityFieldTest::doTestComputedProperties protected function Executes the computed properties tests for the given entity type.
EntityFieldTest::doTestDataStructureInterfaces protected function Executes the data structure interfaces tests for the given entity type.
EntityFieldTest::doTestIntrospection protected function Executes the introspection tests for the given entity type.
EntityFieldTest::doTestIterator protected function Executes the iterator tests for the given entity type.
EntityFieldTest::doTestReadWrite protected function Executes the read write test set for a defined entity type.
EntityFieldTest::doTestSave protected function Executes the save tests for the given entity type.
EntityFieldTest::getContainedStrings public function Recursive helper for getting all contained strings, i.e. properties of type string.
EntityFieldTest::setUp protected function Performs setup tasks before each individual test method is run. Overrides EntityUnitTestBase::setUp
EntityFieldTest::testBaseFieldNonExistingBaseField public function Tests a base field override on a non-existing base field.
EntityFieldTest::testComputedProperties public function Tests getting processed property values via a computed property.
EntityFieldTest::testDataStructureInterfaces public function Tests working with the entity based upon the TypedData API.
EntityFieldTest::testDataTypes public function Makes sure data types are correctly derived for all entity types.
EntityFieldTest::testEntityConstraintValidation public function Tests validation constraints provided by the Entity API.
EntityFieldTest::testFieldOverrideBundleField public function Tests creating a field override config for a bundle field.
EntityFieldTest::testIntrospection public function Tests introspection and getting metadata upfront.
EntityFieldTest::testIterator public function Tests iterating over properties.
EntityFieldTest::testReadWrite public function Tests reading and writing properties and field items.
EntityFieldTest::testSave public function Tries to save and load an entity again.
EntityUnitTestBase::$entityManager protected property The entity manager service.
EntityUnitTestBase::$generatedIds protected property A list of generated identifiers.
EntityUnitTestBase::$state protected property The state service.
EntityUnitTestBase::createUser protected function Creates a user.
EntityUnitTestBase::generateRandomEntityId protected function Generates a random ID avoiding collisions.
EntityUnitTestBase::getHooksInfo protected function Returns the entity_test hook invocation info.
EntityUnitTestBase::installModule protected function Installs a module and refreshes services.
EntityUnitTestBase::refreshServices protected function Refresh services. 1
EntityUnitTestBase::reloadEntity protected function Reloads the given entity from the storage and returns it.
EntityUnitTestBase::uninstallModule protected function Uninstalls a module and refreshes services.
KernelTestBase::$configDirectories protected property The configuration directories for this test run.
KernelTestBase::$keyValueFactory protected property A KeyValueMemoryFactory instance to use when building the container.
KernelTestBase::$moduleFiles private property
KernelTestBase::$streamWrappers protected property Array of registered stream wrappers.
KernelTestBase::$themeFiles private property
KernelTestBase::beforePrepareEnvironment protected function Act on global state information before the environment is altered for a test. Overrides TestBase::beforePrepareEnvironment
KernelTestBase::containerBuild public function Sets up the base service container for this test. 12
KernelTestBase::defaultLanguageData protected function Provides the data for setting the default language on the container. 1
KernelTestBase::disableModules protected function Disables modules for this test.
KernelTestBase::enableModules protected function Enables modules for this test.
KernelTestBase::installConfig protected function Installs default configuration for a given list of modules.
KernelTestBase::installEntitySchema protected function Installs the storage schema for a specific entity type.
KernelTestBase::installSchema protected function Installs a specific table from a module schema definition.
KernelTestBase::prepareConfigDirectories protected function Create and set new configuration directories. 1
KernelTestBase::registerStreamWrapper protected function Registers a stream wrapper for this test.
KernelTestBase::render protected function Renders a render array.
KernelTestBase::tearDown protected function Performs cleanup tasks after each individual test method has been run. Overrides TestBase::tearDown
KernelTestBase::__construct function Constructor for Test. Overrides TestBase::__construct
RandomGeneratorTrait::$randomGenerator protected property The random generator.
RandomGeneratorTrait::getRandomGenerator protected function Gets the random generator for the utility methods.
RandomGeneratorTrait::randomMachineName protected function Generates a unique random string containing letters and numbers.
RandomGeneratorTrait::randomObject public function Generates a random PHP object.
RandomGeneratorTrait::randomString public function Generates a pseudo-random string of ASCII characters of codes 32 to 126.
RandomGeneratorTrait::randomStringValidate public function Callback for random string validation.
SessionTestTrait::$sessionName protected property The name of the session cookie.
SessionTestTrait::generateSessionName protected function Generates a session cookie name.
SessionTestTrait::getSessionName protected function Returns the session name in use on the child site.
TestBase::$assertions protected property Assertions thrown in that test case.
TestBase::$configImporter protected property The config importer that can used in a test. 5
TestBase::$configSchemaCheckerExclusions protected static property An array of config object names that are excluded from schema checking.
TestBase::$container protected property The dependency injection container used in the test.
TestBase::$databasePrefix protected property The database prefix of this test run.
TestBase::$dieOnFail public property Whether to die in case any test assertion fails.
TestBase::$httpAuthCredentials protected property HTTP authentication credentials (<username>:<password>).
TestBase::$httpAuthMethod protected property HTTP authentication method (specified as a CURLAUTH_* constant).
TestBase::$kernel protected property The DrupalKernel instance used in the test. 1
TestBase::$originalConf protected property The original configuration (variables), if available.
TestBase::$originalConfig protected property The original configuration (variables).
TestBase::$originalConfigDirectories protected property The original configuration directories.
TestBase::$originalContainer protected property The original container.
TestBase::$originalFileDirectory protected property The original file directory, before it was changed for testing purposes.
TestBase::$originalLanguage protected property The original language.
TestBase::$originalPrefix protected property The original database prefix when running inside Simpletest.
TestBase::$originalProfile protected property The original installation profile.
TestBase::$originalSessionName protected property The name of the session cookie of the test-runner.
TestBase::$originalSettings protected property The settings array.
TestBase::$originalShutdownCallbacks protected property The original array of shutdown function callbacks. 1
TestBase::$originalSite protected property The site directory of the original parent site.
TestBase::$originalUser protected property The original user, before testing began. 1
TestBase::$privateFilesDirectory protected property The private file directory for the test environment.
TestBase::$publicFilesDirectory protected property The public file directory for the test environment.
TestBase::$results public property Current results of this test case.
TestBase::$siteDirectory protected property The site directory of this test run.
TestBase::$skipClasses protected property This class is skipped when looking for the source of an assertion.
TestBase::$strictConfigSchema protected property Set to TRUE to strict check all configuration saved. 4
TestBase::$tempFilesDirectory protected property The temporary file directory for the test environment.
TestBase::$testId protected property The test run ID.
TestBase::$timeLimit protected property Time limit for the test.
TestBase::$translationFilesDirectory protected property The translation file directory for the test environment.
TestBase::$verbose public property TRUE if verbose debugging is enabled.
TestBase::$verboseClassName protected property Safe class name for use in verbose output filenames.
TestBase::$verboseDirectory protected property Directory where verbose output files are put.
TestBase::$verboseDirectoryUrl protected property URL to the verbose output file directory.
TestBase::$verboseId protected property Incrementing identifier for verbose output filenames.
TestBase::assert protected function Internal helper: stores the assert.
TestBase::assertEqual protected function Check to see if two values are equal.
TestBase::assertErrorLogged protected function Asserts that a specific error has been logged to the PHP error log.
TestBase::assertFalse protected function Check to see if a value is false.
TestBase::assertIdentical protected function Check to see if two values are identical.
TestBase::assertIdenticalObject protected function Checks to see if two objects are identical.
TestBase::assertNoErrorsLogged protected function Asserts that no errors have been logged to the PHP error.log thus far.
TestBase::assertNotEqual protected function Check to see if two values are not equal.
TestBase::assertNotIdentical protected function Check to see if two values are not identical.
TestBase::assertNotNull protected function Check to see if a value is not NULL.
TestBase::assertNull protected function Check to see if a value is NULL.
TestBase::assertTrue protected function Check to see if a value is not false.
TestBase::changeDatabasePrefix private function Changes the database connection to the prefixed one.
TestBase::checkRequirements protected function Checks the matching requirements for Test. 2
TestBase::config protected function Configuration accessor for tests. Returns non-overridden configuration.
TestBase::configImporter public function Returns a ConfigImporter object to import test importing of configuration. 5
TestBase::copyConfig public function Copies configuration objects from source storage to target storage.
TestBase::deleteAssert public static function Delete an assertion record by message ID.
TestBase::error protected function Fire an error assertion. 3
TestBase::errorHandler public function Handle errors during test runs.
TestBase::exceptionHandler protected function Handle exceptions.
TestBase::fail protected function Fire an assertion that is always negative.
TestBase::filePreDeleteCallback public static function Ensures test files are deletable within file_unmanaged_delete_recursive().
TestBase::generatePermutations public static function Converts a list of possible parameters into a stack of permutations.
TestBase::getAssertionCall protected function Cycles through backtrace until the first non-assertion method is found.
TestBase::getConfigSchemaExclusions protected function Gets the config schema exclusions for this test.
TestBase::getDatabaseConnection public static function Returns the database connection to the site running Simpletest.
TestBase::getDatabasePrefix public function Gets the database prefix.
TestBase::getTempFilesDirectory public function Gets the temporary files directory.
TestBase::insertAssert public static function Store an assertion from outside the testing context.
TestBase::pass protected function Fire an assertion that is always positive.
TestBase::prepareDatabasePrefix private function Generates a database prefix for running tests.
TestBase::prepareEnvironment private function Prepares the current environment for running the test.
TestBase::restoreEnvironment private function Cleans up the test environment and restores the original environment.
TestBase::run public function Run all tests in this class. 1
TestBase::settingsSet protected function Changes in memory settings.
TestBase::storeAssertion protected function Helper method to store an assertion record in the configured database.
TestBase::verbose protected function Logs a verbose message in a text file.