annotate core/modules/user/tests/src/Kernel/UserValidationTest.php @ 19:fa3358dc1485 tip

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