diff --git a/core/tests/Drupal/KernelTests/Core/Validation/UniqueFieldConstraintTest.php b/core/tests/Drupal/KernelTests/Core/Validation/UniqueFieldConstraintTest.php new file mode 100644 index 0000000000..bd4333b001 --- /dev/null +++ b/core/tests/Drupal/KernelTests/Core/Validation/UniqueFieldConstraintTest.php @@ -0,0 +1,115 @@ +installEntitySchema('entity_test_string_id'); + + EntityTestStringId::create([ + 'id' => 'foo', + 'name' => $this->randomString(), + ])->save(); + + // Reload the entity. + $entity = EntityTestStringId::load('foo'); + + // Check that an existing entity validates when the value is preserved. + $violations = $entity->name->validate(); + $this->assertCount(0, $violations); + + // Create a new entity with a different ID and a different field value. + EntityTestStringId::create([ + 'id' => 'bar', + 'name' => $this->randomString(), + ]); + + // Check that a new entity with a different field value validates. + $violations = $entity->name->validate(); + $this->assertCount(0, $violations); + } + + /** + * Tests cases when validation raises violations for entities with string IDs. + * + * @param string|int|null $id + * The entity ID. + * + * @covers ::validate + * + * @dataProvider providerTestEntityWithStringIdWithViolation + */ + public function testEntityWithStringIdWithViolation($id) { + $this->installEntitySchema('entity_test_string_id'); + + $value = $this->randomString(); + + EntityTestStringId::create([ + 'id' => 'first_entity', + 'name' => $value, + ])->save(); + + $entity = EntityTestStringId::create([ + 'id' => $id, + 'name' => $value, + ]); + /** @var \Symfony\Component\Validator\ConstraintViolationList $violations */ + $violations = $entity->get('name')->validate(); + + $message = new FormattableMarkup('A @entity_type with @field_name %value already exists.', [ + '%value' => $value, + '@entity_type' => $entity->getEntityType()->getLowercaseLabel(), + '@field_name' => 'Name', + ]); + + // Check that the validation has created the appropriate violation. + $this->assertCount(1, $violations); + $this->assertEquals($message, $violations[0]->getMessage()); + } + + /** + * Data provider for ::testEntityWithStringIdWithViolation(). + * + * @return array + * An array of test cases. + * + * @see self::testEntityWithStringIdWithViolation() + */ + public function providerTestEntityWithStringIdWithViolation() { + return [ + 'without an id' => [NULL], + 'zero as integer' => [0], + 'zero as string' => ["0"], + 'non-zero as integer' => [mt_rand(1, 127)], + 'non-zero as string' => [(string) mt_rand(1, 127)], + 'alphanumeric' => [$this->randomMachineName()], + ]; + } + +}