function StringItemTest::testGenerateSampleValue

Same name and namespace in other branches
  1. 11.x core/tests/Drupal/Tests/Core/Field/StringItemTest.php \Drupal\Tests\Core\Field\StringItemTest::testGenerateSampleValue()

Tests generating sample values.

@covers ::generateSampleValue
@dataProvider providerMaxLength

Parameters

int $max_length: Maximum field length.

File

core/tests/Drupal/Tests/Core/Field/StringItemTest.php, line 29

Class

StringItemTest
Defines a test for the StringItem field-type.

Namespace

Drupal\Tests\Core\Field

Code

public function testGenerateSampleValue(int $max_length) : void {
  foreach ([
    TRUE,
    FALSE,
  ] as $unique) {
    $definition = $this->prophesize(FieldDefinitionInterface::class);
    $constraints = $unique ? [
      $this->prophesize(UniqueFieldConstraint::class),
    ] : [];
    $definition->getConstraint('UniqueField')
      ->willReturn($constraints);
    $definition->getSetting('max_length')
      ->willReturn($max_length);
    for ($i = 0; $i < 1000; $i++) {
      $sample_value = StringItem::generateSampleValue($definition->reveal());
      // When the field value needs to be unique, the generated sample value
      // should match the maximum length to ensure sufficient entropy.
      if ($unique) {
        $this->assertEquals($max_length, mb_strlen($sample_value['value']));
      }
      else {
        $this->assertLessThanOrEqual($max_length, mb_strlen($sample_value['value']));
      }
    }
  }
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.