You are here

public function OpenIDConnectTest::testCreateUser in OpenID Connect / OAuth client 8

Same name and namespace in other branches
  1. 2.x tests/src/Unit/OpenIDConnectTest.php \Drupal\Tests\openid_connect\Unit\OpenIDConnectTest::testCreateUser()

Test for the createUser method.

@dataProvider dataProviderForCreateUser

Parameters

string $sub: The sub to use.

array $userinfo: The userinfo array containing the email key.

string $client_name: The client name for the user.

bool $status: The user status.

bool $duplicate: Whether to test a duplicate username.

File

tests/src/Unit/OpenIDConnectTest.php, line 436

Class

OpenIDConnectTest
Provides tests for the OpenID Connect module.

Namespace

Drupal\Tests\openid_connect\Unit

Code

public function testCreateUser(string $sub, array $userinfo, string $client_name, bool $status, bool $duplicate) : void {

  // Mock the expected username.
  $expectedUserName = 'oidc_' . $client_name . '_' . md5($sub);

  // If the preferred username is defined, use it instead.
  if (array_key_exists('preferred_username', $userinfo)) {
    $expectedUserName = trim($userinfo['preferred_username']);
  }

  // If the name key exists, use it.
  if (array_key_exists('name', $userinfo)) {
    $expectedUserName = trim($userinfo['name']);
  }
  $expectedAccountArray = [
    'name' => $duplicate ? "{$expectedUserName}_1" : $expectedUserName,
    'pass' => 'TestPassword123',
    'mail' => $userinfo['email'],
    'init' => $userinfo['email'],
    'status' => $status,
    'openid_connect_client' => $client_name,
    'openid_connect_sub' => $sub,
  ];

  // Mock the user account to be created.
  $account = $this
    ->createMock(UserInterface::class);
  $account
    ->expects($this
    ->once())
    ->method('save')
    ->willReturn(1);
  $this->userStorage
    ->expects($this
    ->once())
    ->method('create')
    ->with($expectedAccountArray)
    ->willReturn($account);
  if ($duplicate) {
    $this->userStorage
      ->expects($this
      ->exactly(2))
      ->method('loadByProperties')
      ->withConsecutive([
      [
        'name' => $expectedUserName,
      ],
    ], [
      [
        'name' => "{$expectedUserName}_1",
      ],
    ])
      ->willReturnOnConsecutiveCalls([
      1,
    ], []);
  }
  else {
    $this->userStorage
      ->expects($this
      ->once())
      ->method('loadByProperties')
      ->with([
      'name' => $expectedUserName,
    ])
      ->willReturn([]);
  }
  $actualResult = $this->openIdConnect
    ->createUser($sub, $userinfo, $client_name, $status);
  $this
    ->assertInstanceOf('\\Drupal\\user\\UserInterface', $actualResult);
}