3 namespace Drupal\field\Tests;
5 use Drupal\Core\Entity\EntityInterface;
6 use Drupal\Core\Language\LanguageInterface;
7 use Drupal\simpletest\WebTestBase;
10 * Parent class for Field API tests.
12 * @deprecated Scheduled for removal in Drupal 9.0.0.
13 * Use \Drupal\Tests\field\Functional\FieldTestBase instead.
15 abstract class FieldTestBase extends WebTestBase {
18 * Generate random values for a field_test field.
21 * Number of values to generate.
23 * An array of random values, in the format expected for field values.
25 public function _generateTestFieldValues($cardinality) {
27 for ($i = 0; $i < $cardinality; $i++) {
28 // field_test fields treat 0 as 'empty value'.
29 $values[$i]['value'] = mt_rand(1, 127);
35 * Assert that a field has the expected values in an entity.
37 * This function only checks a single column in the field values.
39 * @param \Drupal\Core\Entity\EntityInterface $entity
42 * The name of the field to test
43 * @param $expected_values
44 * The array of expected values.
46 * (Optional) The language code for the values. Defaults to
47 * \Drupal\Core\Language\LanguageInterface::LANGCODE_DEFAULT.
49 * (Optional) The name of the column to check. Defaults to 'value'.
51 public function assertFieldValues(EntityInterface $entity, $field_name, $expected_values, $langcode = LanguageInterface::LANGCODE_DEFAULT, $column = 'value') {
52 // Re-load the entity to make sure we have the latest changes.
53 $storage = $this->container->get('entity_type.manager')
54 ->getStorage($entity->getEntityTypeId());
55 $storage->resetCache([$entity->id()]);
56 $e = $storage->load($entity->id());
58 $field = $values = $e->getTranslation($langcode)->$field_name;
59 // Filter out empty values so that they don't mess with the assertions.
60 $field->filterEmptyItems();
61 $values = $field->getValue();
62 $this->assertEqual(count($values), count($expected_values), 'Expected number of values were saved.');
63 foreach ($expected_values as $key => $value) {
64 $this->assertEqual($values[$key][$column], $value, format_string('Value @value was saved correctly.', ['@value' => $value]));