You are here

public function CurrentUserContextTest::testGetAvailableContexts in Drupal 9

Same name and namespace in other branches
  1. 8 core/modules/user/tests/src/Kernel/ContextProvider/CurrentUserContextTest.php \Drupal\Tests\user\Kernel\ContextProvider\CurrentUserContextTest::testGetAvailableContexts()

@covers ::getAvailableContexts

File

core/modules/user/tests/src/Kernel/ContextProvider/CurrentUserContextTest.php, line 34

Class

CurrentUserContextTest
@coversDefaultClass \Drupal\user\ContextProvider\CurrentUserContext

Namespace

Drupal\Tests\user\Kernel\ContextProvider

Code

public function testGetAvailableContexts() {
  $context_repository = $this->container
    ->get('context.repository');

  // Test an authenticated account.
  $authenticated = User::create([
    'name' => $this
      ->randomMachineName(),
  ]);
  $authenticated
    ->save();
  $authenticated = User::load($authenticated
    ->id());
  $this->container
    ->get('current_user')
    ->setAccount($authenticated);
  $contexts = $context_repository
    ->getAvailableContexts();
  $this
    ->assertArrayHasKey('@user.current_user_context:current_user', $contexts);
  $this
    ->assertSame('entity:user', $contexts['@user.current_user_context:current_user']
    ->getContextDefinition()
    ->getDataType());
  $this
    ->assertTrue($contexts['@user.current_user_context:current_user']
    ->hasContextValue());
  $this
    ->assertNotNull($contexts['@user.current_user_context:current_user']
    ->getContextValue());

  // Test an anonymous account.
  $anonymous = $this
    ->prophesize(AccountInterface::class);
  $anonymous
    ->id()
    ->willReturn(0);
  $this->container
    ->get('current_user')
    ->setAccount($anonymous
    ->reveal());
  $contexts = $context_repository
    ->getAvailableContexts();
  $this
    ->assertArrayHasKey('@user.current_user_context:current_user', $contexts);
  $this
    ->assertSame('entity:user', $contexts['@user.current_user_context:current_user']
    ->getContextDefinition()
    ->getDataType());
  $this
    ->assertFalse($contexts['@user.current_user_context:current_user']
    ->hasContextValue());
}