class UserAuthenticationTest
Tests Drupal\user\UserAuthentication.
Attributes
#[CoversClass(UserAuthentication::class)]
#[Group('user')]
Hierarchy
- class \Drupal\Tests\UnitTestCase uses \Drupal\Tests\DrupalTestCaseTrait, \Drupal\Tests\PhpUnitCompatibilityTrait, \Prophecy\PhpUnit\ProphecyTrait, \Drupal\TestTools\Extension\DeprecationBridge\ExpectDeprecationTrait, \Drupal\Tests\RandomGeneratorTrait extends \PHPUnit\Framework\TestCase
- class \Drupal\Tests\user\Unit\UserAuthenticationTest extends \Drupal\Tests\UnitTestCase
Expanded class hierarchy of UserAuthenticationTest
File
-
core/
modules/ user/ tests/ src/ Unit/ UserAuthenticationTest.php, line 29
Namespace
Drupal\Tests\user\UnitView source
class UserAuthenticationTest extends UnitTestCase {
/**
* The mock user storage.
*
* @var \Drupal\Core\Entity\EntityStorageInterface|\PHPUnit\Framework\MockObject\MockObject
*/
protected $userStorage;
/**
* The mocked password service.
*
* @var \Drupal\Core\Password\PasswordInterface|\PHPUnit\Framework\MockObject\Stub
*/
protected $passwordService;
/**
* The user auth object under test.
*
* @var \Drupal\user\UserAuthentication
*/
protected UserAuthentication $userAuth;
/**
* The test username.
*
* @var string
*/
protected string $username = 'test_user';
/**
* The test password.
*
* @var string
*/
protected string $password = 'password';
/**
* {@inheritdoc}
*/
protected function setUp() : void {
parent::setUp();
$this->userStorage = $this->createMock('Drupal\\Core\\Entity\\EntityStorageInterface');
/** @var \Drupal\Core\Entity\EntityTypeManagerInterface|\PHPUnit\Framework\MockObject\Stub $entity_type_manager */
$entity_type_manager = $this->createStub(EntityTypeManagerInterface::class);
$entity_type_manager->method('getStorage')
->with('user')
->willReturn($this->userStorage);
$this->passwordService = $this->createStub(PasswordInterface::class);
$this->userAuth = new UserAuthentication($entity_type_manager, $this->passwordService);
}
/**
* Tests lookupAccount() with a valid username.
*/
public function testLookupAccountWithValidUsername() : void {
$this->userStorage
->expects($this->once())
->method('loadByProperties')
->with([
'name' => $this->username,
])
->willReturn([
$this->createStub(User::class),
]);
$this->assertInstanceOf(User::class, $this->userAuth
->lookupAccount($this->username));
}
/**
* Tests lookupAccount() with an invalid username.
*/
public function testLookupAccountWithInvalidUsername() : void {
$this->userStorage
->expects($this->once())
->method('loadByProperties')
->with([
'name' => 'invalidUser',
])
->willReturn([]);
$this->assertFalse($this->userAuth
->lookupAccount('invalidUser'));
}
/**
* Tests the authenticate method with an incorrect password.
*/
public function testAuthenticateWithIncorrectPassword() : void {
$this->userStorage
->expects($this->once())
->method('loadByProperties')
->with([
'name' => $this->username,
])
->willReturn([
$this->createStub(User::class),
]);
$this->passwordService
->method('check')
->willReturn(FALSE);
$user = $this->userAuth
->lookupAccount($this->username);
$this->assertFalse($this->userAuth
->authenticateAccount($user, $this->password));
}
/**
* Tests the authenticate method with a correct password.
*/
public function testAuthenticateWithCorrectPassword() : void {
$testUser = $this->createPartialMock(User::class, [
'id',
'getPassword',
]);
$this->userStorage
->expects($this->once())
->method('loadByProperties')
->with([
'name' => $this->username,
])
->willReturn([
$testUser,
]);
$this->passwordService
->method('check')
->willReturn(TRUE);
$user = $this->userAuth
->lookupAccount($this->username);
$this->assertTrue($this->userAuth
->authenticateAccount($user, $this->password));
}
/**
* Tests the authenticate method with a correct password.
*
* We discovered in https://www.drupal.org/node/2563751 that logging in with a
* password that is literally "0" was not possible. This test ensures that
* this regression can't happen again.
*/
public function testAuthenticateWithZeroPassword() : void {
$testUser = $this->createPartialMock(User::class, [
'id',
'getPassword',
]);
$this->userStorage
->expects($this->once())
->method('loadByProperties')
->with([
'name' => $this->username,
])
->willReturn([
$testUser,
]);
$this->passwordService
->method('check')
->with('0', 0)
->willReturn(TRUE);
$user = $this->userAuth
->lookupAccount($this->username);
$this->assertTrue($this->userAuth
->authenticateAccount($user, '0'));
}
/**
* Tests the authenticate method with a correct password & new password hash.
*/
public function testAuthenticateWithCorrectPasswordAndNewPasswordHash() : void {
$testUser = $this->createPartialMock(User::class, [
'id',
'setPassword',
'save',
'getPassword',
]);
$testUser->expects($this->once())
->method('setPassword')
->with($this->password);
$testUser->expects($this->once())
->method('save');
$this->userStorage
->expects($this->once())
->method('loadByProperties')
->with([
'name' => $this->username,
])
->willReturn([
$testUser,
]);
$this->passwordService
->method('check')
->willReturn(TRUE);
$this->passwordService
->method('needsRehash')
->willReturn(TRUE);
$user = $this->userAuth
->lookupAccount($this->username);
$this->assertTrue($this->userAuth
->authenticateAccount($user, $this->password));
}
/**
* Tests the auth that ends in a redirect from subdomain to TLD.
*/
public function testAddCheckToUrlForTrustedRedirectResponse() : void {
$this->userStorage
->expects($this->never())
->method('loadByProperties');
$site_domain = 'site.com';
$frontend_url = "https://{$site_domain}";
$backend_url = "https://api.{$site_domain}";
$request = Request::create($backend_url);
$response = new TrustedRedirectResponse($frontend_url);
$request_context = $this->createStub(RequestContext::class);
$request_context->method('getCompleteBaseUrl')
->willReturn($backend_url);
$container = new ContainerBuilder();
$container->set('router.request_context', $request_context);
\Drupal::setContainer($container);
$session_mock = $this->createMock(SessionInterface::class);
$session_mock->expects($this->once())
->method('has')
->with('check_logged_in')
->willReturn(TRUE);
$session_mock->expects($this->once())
->method('remove')
->with('check_logged_in');
$event = new ResponseEvent($this->createStub(HttpKernelInterface::class), $request, HttpKernelInterface::MAIN_REQUEST, $response);
$request->setSession($session_mock);
$cookie = new Cookie($this->createStub(SessionConfigurationInterface::class), $this->createStub(Connection::class), $this->createStub(MessengerInterface::class));
$cookie->addCheckToUrl($event);
$this->assertSame("{$frontend_url}?check_logged_in=1", $response->getTargetUrl());
}
/**
* Tests the auth that ends in a redirect from subdomain with a fragment to TLD.
*/
public function testAddCheckToUrlForTrustedRedirectResponseWithFragment() : void {
$this->userStorage
->expects($this->never())
->method('loadByProperties');
$site_domain = 'site.com';
$frontend_url = "https://{$site_domain}";
$backend_url = "https://api.{$site_domain}";
$request = Request::create($backend_url);
$response = new TrustedRedirectResponse($frontend_url . '#a_fragment');
$request_context = $this->createStub(RequestContext::class);
$request_context->method('getCompleteBaseUrl')
->willReturn($backend_url);
$container = new ContainerBuilder();
$container->set('router.request_context', $request_context);
\Drupal::setContainer($container);
$session_mock = $this->createMock(SessionInterface::class);
$session_mock->expects($this->once())
->method('has')
->with('check_logged_in')
->willReturn(TRUE);
$session_mock->expects($this->once())
->method('remove')
->with('check_logged_in');
$event = new ResponseEvent($this->createStub(HttpKernelInterface::class), $request, HttpKernelInterface::MAIN_REQUEST, $response);
$request->setSession($session_mock);
$cookie = new Cookie($this->createStub(SessionConfigurationInterface::class), $this->createStub(Connection::class), $this->createStub(MessengerInterface::class));
$cookie->addCheckToUrl($event);
$this->assertSame("{$frontend_url}?check_logged_in=1#a_fragment", $response->getTargetUrl());
}
}
Members
| Title Sort descending | Deprecated | Modifiers | Object type | Summary | Overriden Title | Overrides |
|---|---|---|---|---|---|---|
| DrupalTestCaseTrait::checkErrorHandlerOnTearDown | public | function | Checks the test error handler after test execution. | 1 | ||
| ExpectDeprecationTrait::expectDeprecation | Deprecated | public | function | Adds an expected deprecation. | ||
| ExpectDeprecationTrait::regularExpressionForFormatDescription | private | function | ||||
| RandomGeneratorTrait::getRandomGenerator | protected | function | Gets the random generator for the utility methods. | |||
| RandomGeneratorTrait::randomMachineName | protected | function | Generates a unique random string containing letters and numbers. | |||
| RandomGeneratorTrait::randomObject | public | function | Generates a random PHP object. | |||
| RandomGeneratorTrait::randomString | public | function | Generates a pseudo-random string of ASCII characters of codes 32 to 126. | |||
| UnitTestCase::$root | protected | property | The app root. | |||
| UnitTestCase::getClassResolverStub | protected | function | Returns a stub class resolver. | |||
| UnitTestCase::getConfigFactoryStub | public | function | Returns a stub config factory that behaves according to the passed array. | |||
| UnitTestCase::getContainerWithCacheTagsInvalidator | protected | function | Sets up a container with a cache tags invalidator. | |||
| UnitTestCase::getStringTranslationStub | public | function | Returns a stub translation manager that just returns the passed string. | |||
| UnitTestCase::setDebugDumpHandler | public static | function | Registers the dumper CLI handler when the DebugDump extension is enabled. | |||
| UnitTestCase::setupMockIterator | protected | function | Set up a traversable class mock to return specific items when iterated. | |||
| UserAuthenticationTest::$password | protected | property | The test password. | |||
| UserAuthenticationTest::$passwordService | protected | property | The mocked password service. | |||
| UserAuthenticationTest::$userAuth | protected | property | The user auth object under test. | |||
| UserAuthenticationTest::$username | protected | property | The test username. | |||
| UserAuthenticationTest::$userStorage | protected | property | The mock user storage. | |||
| UserAuthenticationTest::setUp | protected | function | Overrides UnitTestCase::setUp | |||
| UserAuthenticationTest::testAddCheckToUrlForTrustedRedirectResponse | public | function | Tests the auth that ends in a redirect from subdomain to TLD. | |||
| UserAuthenticationTest::testAddCheckToUrlForTrustedRedirectResponseWithFragment | public | function | Tests the auth that ends in a redirect from subdomain with a fragment to TLD. | |||
| UserAuthenticationTest::testAuthenticateWithCorrectPassword | public | function | Tests the authenticate method with a correct password. | |||
| UserAuthenticationTest::testAuthenticateWithCorrectPasswordAndNewPasswordHash | public | function | Tests the authenticate method with a correct password & new password hash. | |||
| UserAuthenticationTest::testAuthenticateWithIncorrectPassword | public | function | Tests the authenticate method with an incorrect password. | |||
| UserAuthenticationTest::testAuthenticateWithZeroPassword | public | function | Tests the authenticate method with a correct password. | |||
| UserAuthenticationTest::testLookupAccountWithInvalidUsername | public | function | Tests lookupAccount() with an invalid username. | |||
| UserAuthenticationTest::testLookupAccountWithValidUsername | public | function | Tests lookupAccount() with a valid username. |
Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.