3 namespace Drupal\Tests\user\Kernel;
5 use Drupal\Core\Entity\EntityInterface;
6 use Drupal\Core\Language\Language;
7 use Drupal\Core\Render\Element\Email;
8 use Drupal\KernelTests\KernelTestBase;
9 use Drupal\user\Entity\Role;
10 use Drupal\user\Entity\User;
13 * Verify that user validity checks behave as designed.
17 class UserValidationTest extends KernelTestBase {
24 public static $modules = ['field', 'user', 'system'];
29 protected function setUp() {
31 $this->installEntitySchema('user');
32 $this->installSchema('system', ['sequences']);
34 // Make sure that the default roles exist.
35 $this->installConfig(['user']);
40 * Tests user name validation.
42 public function testUsernames() {
44 // '<username>' => ['<description>', 'assert<testName>'].
45 'foo' => ['Valid username', 'assertNull'],
46 'FOO' => ['Valid username', 'assertNull'],
47 'Foo O\'Bar' => ['Valid username', 'assertNull'],
48 'foo@bar' => ['Valid username', 'assertNull'],
49 'foo@example.com' => ['Valid username', 'assertNull'],
50 // invalid domains are allowed in usernames.
51 'foo@-example.com' => ['Valid username', 'assertNull'],
52 'þòøÇߪř€' => ['Valid username', 'assertNull'],
53 // '+' symbol is allowed.
54 'foo+bar' => ['Valid username', 'assertNull'],
56 'ᚠᛇᚻ᛫ᛒᛦᚦ' => ['Valid UTF8 username', 'assertNull'],
57 ' foo' => ['Invalid username that starts with a space', 'assertNotNull'],
58 'foo ' => ['Invalid username that ends with a space', 'assertNotNull'],
59 'foo bar' => ['Invalid username that contains 2 spaces \' \'', 'assertNotNull'],
60 '' => ['Invalid empty username', 'assertNotNull'],
61 'foo/' => ['Invalid username containing invalid chars', 'assertNotNull'],
63 'foo' . chr(0) . 'bar' => ['Invalid username containing chr(0)', 'assertNotNull'],
65 'foo' . chr(13) . 'bar' => ['Invalid username containing chr(13)', 'assertNotNull'],
66 str_repeat('x', USERNAME_MAX_LENGTH + 1) => ['Invalid excessively long username', 'assertNotNull'],
68 foreach ($test_cases as $name => $test_case) {
69 list($description, $test) = $test_case;
70 $result = user_validate_name($name);
71 $this->$test($result, $description . ' (' . $name . ')');
76 * Runs entity validation checks.
78 public function testValidation() {
79 $user = User::create([
81 'mail' => 'test@example.com',
83 $violations = $user->validate();
84 $this->assertEqual(count($violations), 0, 'No violations when validating a default user.');
86 // Only test one example invalid name here, the rest is already covered in
87 // the testUsernames() method in this class.
88 $name = $this->randomMachineName(61);
89 $user->set('name', $name);
90 $violations = $user->validate();
91 $this->assertEqual(count($violations), 1, 'Violation found when name is too long.');
92 $this->assertEqual($violations[0]->getPropertyPath(), 'name');
93 $this->assertEqual($violations[0]->getMessage(), t('The username %name is too long: it must be %max characters or less.', ['%name' => $name, '%max' => 60]));
95 // Create a second test user to provoke a name collision.
96 $user2 = User::create([
98 'mail' => 'existing@example.com',
101 $user->set('name', 'existing');
102 $violations = $user->validate();
103 $this->assertEqual(count($violations), 1, 'Violation found on name collision.');
104 $this->assertEqual($violations[0]->getPropertyPath(), 'name');
105 $this->assertEqual($violations[0]->getMessage(), t('The username %name is already taken.', ['%name' => 'existing']));
107 // Make the name valid.
108 $user->set('name', $this->randomMachineName());
110 $user->set('mail', 'invalid');
111 $violations = $user->validate();
112 $this->assertEqual(count($violations), 1, 'Violation found when email is invalid');
113 $this->assertEqual($violations[0]->getPropertyPath(), 'mail.0.value');
114 $this->assertEqual($violations[0]->getMessage(), t('This value is not a valid email address.'));
116 $mail = $this->randomMachineName(Email::EMAIL_MAX_LENGTH - 11) . '@example.com';
117 $user->set('mail', $mail);
118 $violations = $user->validate();
119 // @todo There are two violations because EmailItem::getConstraints()
120 // overlaps with the implicit constraint of the 'email' property type used
121 // in EmailItem::propertyDefinitions(). Resolve this in
122 // https://www.drupal.org/node/2023465.
123 $this->assertEqual(count($violations), 2, 'Violations found when email is too long');
124 $this->assertEqual($violations[0]->getPropertyPath(), 'mail.0.value');
125 $this->assertEqual($violations[0]->getMessage(), t('%name: the email address can not be longer than @max characters.', ['%name' => $user->get('mail')->getFieldDefinition()->getLabel(), '@max' => Email::EMAIL_MAX_LENGTH]));
126 $this->assertEqual($violations[1]->getPropertyPath(), 'mail.0.value');
127 $this->assertEqual($violations[1]->getMessage(), t('This value is not a valid email address.'));
129 // Provoke an email collision with an existing user.
130 $user->set('mail', 'existing@example.com');
131 $violations = $user->validate();
132 $this->assertEqual(count($violations), 1, 'Violation found when email already exists.');
133 $this->assertEqual($violations[0]->getPropertyPath(), 'mail');
134 $this->assertEqual($violations[0]->getMessage(), t('The email address %mail is already taken.', ['%mail' => 'existing@example.com']));
135 $user->set('mail', NULL);
136 $violations = $user->validate();
137 $this->assertEqual(count($violations), 1, 'Email addresses may not be removed');
138 $this->assertEqual($violations[0]->getPropertyPath(), 'mail');
139 $this->assertEqual($violations[0]->getMessage(), t('@name field is required.', ['@name' => $user->getFieldDefinition('mail')->getLabel()]));
140 $user->set('mail', 'someone@example.com');
142 $user->set('timezone', $this->randomString(33));
143 $this->assertLengthViolation($user, 'timezone', 32, 2, 1);
144 $user->set('timezone', 'invalid zone');
145 $this->assertAllowedValuesViolation($user, 'timezone');
146 $user->set('timezone', NULL);
148 $user->set('init', 'invalid');
149 $violations = $user->validate();
150 $this->assertEqual(count($violations), 1, 'Violation found when init email is invalid');
151 $user->set('init', NULL);
153 $user->set('langcode', 'invalid');
154 $this->assertAllowedValuesViolation($user, 'langcode');
155 $user->set('langcode', NULL);
157 // Only configurable langcodes are allowed for preferred languages.
158 $user->set('preferred_langcode', Language::LANGCODE_NOT_SPECIFIED);
159 $this->assertAllowedValuesViolation($user, 'preferred_langcode');
160 $user->set('preferred_langcode', NULL);
162 $user->set('preferred_admin_langcode', Language::LANGCODE_NOT_SPECIFIED);
163 $this->assertAllowedValuesViolation($user, 'preferred_admin_langcode');
164 $user->set('preferred_admin_langcode', NULL);
166 Role::create(['id' => 'role1'])->save();
167 Role::create(['id' => 'role2'])->save();
169 // Test cardinality of user roles.
170 $user = User::create([
171 'name' => 'role_test',
172 'mail' => 'test@example.com',
173 'roles' => ['role1', 'role2'],
175 $violations = $user->validate();
176 $this->assertEqual(count($violations), 0);
178 $user->roles[1]->target_id = 'unknown_role';
179 $violations = $user->validate();
180 $this->assertEqual(count($violations), 1);
181 $this->assertEqual($violations[0]->getPropertyPath(), 'roles.1.target_id');
182 $this->assertEqual($violations[0]->getMessage(), t('The referenced entity (%entity_type: %name) does not exist.', ['%entity_type' => 'user_role', '%name' => 'unknown_role']));
186 * Verifies that a length violation exists for the given field.
188 * @param \Drupal\core\Entity\EntityInterface $entity
189 * The entity object to validate.
190 * @param string $field_name
191 * The field that violates the maximum length.
193 * Number of characters that was exceeded.
195 * (optional) The number of expected violations. Defaults to 1.
196 * @param int $expected_index
197 * (optional) The index at which to expect the violation. Defaults to 0.
199 protected function assertLengthViolation(EntityInterface $entity, $field_name, $length, $count = 1, $expected_index = 0) {
200 $violations = $entity->validate();
201 $this->assertEqual(count($violations), $count, "Violation found when $field_name is too long.");
202 $this->assertEqual($violations[$expected_index]->getPropertyPath(), "$field_name.0.value");
203 $field_label = $entity->get($field_name)->getFieldDefinition()->getLabel();
204 $this->assertEqual($violations[$expected_index]->getMessage(), t('%name: may not be longer than @max characters.', ['%name' => $field_label, '@max' => $length]));
208 * Verifies that a AllowedValues violation exists for the given field.
210 * @param \Drupal\core\Entity\EntityInterface $entity
211 * The entity object to validate.
212 * @param string $field_name
213 * The name of the field to verify.
215 protected function assertAllowedValuesViolation(EntityInterface $entity, $field_name) {
216 $violations = $entity->validate();
217 $this->assertEqual(count($violations), 1, "Allowed values violation for $field_name found.");
218 $this->assertEqual($violations[0]->getPropertyPath(), $field_name === 'langcode' ? "$field_name.0" : "$field_name.0.value");
219 $this->assertEqual($violations[0]->getMessage(), t('The value you selected is not a valid choice.'));