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