View source
<?php
namespace Drupal\Tests\user\Kernel;
use Drupal\Core\Form\FormState;
use Drupal\KernelTests\KernelTestBase;
class UserAccountFormFieldsTest extends KernelTestBase {
protected static $modules = [
'system',
'user',
'field',
];
public function testInstallConfigureForm() {
require_once $this->root . '/core/includes/install.core.inc';
require_once $this->root . '/core/includes/install.inc';
$install_state = install_state_defaults();
$form_state = new FormState();
$form_state
->addBuildInfo('args', [
&$install_state,
]);
$form = $this->container
->get('form_builder')
->buildForm('Drupal\\Core\\Installer\\Form\\SiteConfigureForm', $form_state);
$this
->assertFieldOrder($form['admin_account']['account']);
foreach ([
'mail',
'name',
'pass',
] as $key) {
$this
->assertFalse(isset($form['account'][$key]['#attributes']['autocomplete']), "'{$key}' field: 'autocomplete' attribute not found.");
}
}
public function testUserRegistrationForm() {
$this
->installConfig([
'user',
]);
$this
->config('user.settings')
->set('verify_mail', FALSE)
->save();
$form = $this
->buildAccountForm('register');
$this
->assertFieldOrder($form['account']);
foreach ([
'mail',
'name',
'pass',
] as $key) {
$this
->assertFalse(isset($form['account'][$key]['#attributes']['autocomplete']), "'{$key}' field: 'autocomplete' attribute not found.");
}
}
public function testUserEditForm() {
$this
->installConfig([
'user',
]);
$form = $this
->buildAccountForm('default');
$this
->assertFieldOrder($form['account']);
foreach ([
'mail',
'name',
'pass',
] as $key) {
$this
->assertSame('off', $form['account'][$key]['#attributes']['autocomplete'], "'{$key}' field: 'autocomplete' attribute is 'off'.");
}
}
protected function assertFieldOrder(array $elements) : void {
$name_index = 0;
$name_weight = 0;
$pass_index = 0;
$pass_weight = 0;
$index = 0;
foreach ($elements as $key => $element) {
if ($key === 'name') {
$name_index = $index;
$name_weight = $element['#weight'];
$this
->assertTrue($element['#sorted'], "'name' field is #sorted.");
}
elseif ($key === 'pass') {
$pass_index = $index;
$pass_weight = $element['#weight'];
$this
->assertTrue($element['#sorted'], "'pass' field is #sorted.");
}
$index++;
}
$this
->assertEquals($pass_index - 1, $name_index, "'name' field ({$name_index}) appears before 'pass' field ({$pass_index}).");
$this
->assertLessThan($pass_weight, $name_weight, "'name' field weight ({$name_weight}) should be smaller than 'pass' field weight ({$pass_weight}).");
}
protected function buildAccountForm($operation) {
$entity_type = 'user';
$fields = [];
if ($operation != 'register') {
$fields['uid'] = 2;
}
$entity = $this->container
->get('entity_type.manager')
->getStorage($entity_type)
->create($fields);
return $this->container
->get('entity.form_builder')
->getForm($entity, $operation);
}
}