AnonymousUserSession example

$this->assertNull(\Drupal::formBuilder()->getCache($wrong_form_build_id$cached_form_state), 'No form returned from cache');
    $cached_form_state_example = $cached_form_state->get('example');
    $this->assertEmpty($cached_form_state_example, 'Cached form state was not loaded');
  }

  /** * Tests the form cache without a logged-in user. */
  public function testNoCacheToken() {
    // Switch to an anonymous user account.     $account_switcher = \Drupal::service('account_switcher');
    $account_switcher->switchTo(new AnonymousUserSession());

    $this->formState->set('example', $this->randomMachineName());
    \Drupal::formBuilder()->setCache($this->formBuildId, $this->form, $this->formState);

    $cached_form_state = new FormState();
    $cached_form = \Drupal::formBuilder()->getCache($this->formBuildId, $cached_form_state);
    $this->assertEquals($this->form['#property']$cached_form['#property']);
    $this->assertArrayNotHasKey('#cache_token', $cached_form, 'Form has no cache token');
    $this->assertEquals($this->formState->get('example')$cached_form_state->get('example'));

    // Restore user account.

  public function getAccount() {
    if (!isset($this->account)) {
      if ($this->id) {
        // After the container is rebuilt, DrupalKernel sets the initial         // account to the id of the logged in user. This is necessary in order         // to refresh the user account reference here.         $this->setAccount($this->loadUserEntity($this->id));
      }
      else {
        $this->account = new AnonymousUserSession();
      }
    }

    return $this->account;
  }

  /** * {@inheritdoc} */
  public function id() {
    return $this->id;
  }


  /** * {@inheritdoc} */
  public function run() {
    // Allow execution to continue even if the request gets cancelled.     @ignore_user_abort(TRUE);

    // Force the current user to anonymous to ensure consistent permissions on     // cron runs.     $this->accountSwitcher->switchTo(new AnonymousUserSession());

    // Try to allocate enough time to run all the hook_cron implementations.     Environment::setTimeLimit(240);

    $return = FALSE;

    // Try to acquire cron lock.     if (!$this->lock->acquire('cron', 900.0)) {
      // Cron is still running normally.       $this->logger->warning('Attempting to re-run cron while it is already running.');
    }
    
protected function setUp($import_test_views = TRUE): void {
    parent::setUp();
    $this->currentUser = $this->container->get('current_user');
    $this->setupPermissionTestData();
  }

  /** * Tests the current user filter handler with anonymous user. */
  public function testFilterCurrentUserAsAnonymous() {
    $column_map = ['uid' => 'uid'];
    $this->currentUser->setAccount(new AnonymousUserSession());

    $view = Views::getView('test_filter_current_user');
    $view->initHandlers();
    $view->filter['uid_current']->value = 0;
    $this->executeView($view);
    $expected[] = ['uid' => 1];
    $expected[] = ['uid' => 2];
    $expected[] = ['uid' => 3];
    $expected[] = ['uid' => 4];
    $this->assertIdenticalResultset($view$expected$column_map, 'Anonymous account can view all accounts when current filter is FALSE.');
    $view->destroy();

    
/** * The router dumper to get all routes. * * @var \Drupal\Core\Routing\MatcherDumper */
  protected $routerDumper;

  /** * Checks the behavior of the page for access denied/not found behaviors. */
  public function testPageResponses() {
    \Drupal::currentUser()->setAccount(new AnonymousUserSession());
    $subrequest = Request::create('/test_page_display_403', 'GET');
    $response = $this->container->get('http_kernel')->handle($subrequest, HttpKernelInterface::SUB_REQUEST);
    $this->assertEquals(403, $response->getStatusCode());

    $subrequest = Request::create('/test_page_display_404', 'GET');
    $response = $this->container->get('http_kernel')->handle($subrequest, HttpKernelInterface::SUB_REQUEST);
    $this->assertEquals(404, $response->getStatusCode());

    $subrequest = Request::create('/test_page_display_200', 'GET');
    $response = $this->container->get('http_kernel')->handle($subrequest, HttpKernelInterface::SUB_REQUEST);
    $this->assertEquals(200, $response->getStatusCode());

    
'skip comment approval',
      'access comments',
    ], 'no edit');

    // An unprivileged user.     $comment_disabled_user = $this->createUser(['access content'], 'disabled');

    $role = Role::load(RoleInterface::ANONYMOUS_ID);
    $role->grantPermission('post comments')
      ->save();

    $anonymous_user = new AnonymousUserSession();

    // Add two fields.     $this->addDefaultCommentField('entity_test', 'entity_test', 'comment');
    $this->addDefaultCommentField('entity_test', 'entity_test', 'comment_other');

    // Create a comment against a test entity.     $host = EntityTest::create();
    $host->save();

    $host2 = EntityTest::create();
    $host2->comment->status = CommentItemInterface::CLOSED;
    
$this->assertLink('Anonymous comment title');
    // Display plugin of the view is showing the name field. When comment     // belongs to an authenticated user the name field has no value.     $comment_author = $this->xpath('//div[contains(@class, :class)]/span[normalize-space(text())=""]', [
      ':class' => 'views-field-subject',
    ]);
    $this->assertNotEmpty($comment_author);
    // When comment belongs to an anonymous user the name field has a value and     // it is rendered correctly.     $this->assertLink('barry (not verified)');

    $account_switcher->switchTo(new AnonymousUserSession());
    $executable = Views::getView($view_id);
    $executable->storage->invalidateCaches();

    $build = $executable->preview();
    $this->setRawContent($renderer->renderRoot($build));

    // No access to user-profiles, so shouldn't be able to see links.     $this->assertNoLink($this->adminUser->label());
    // Note: External users aren't pointing to drupal user profiles.     $this->assertLink('barry (not verified)');
    $this->assertLink('My comment title');
    
// The current user is allowed to view user labels.     $this->assertEntityAccess([
      'create' => FALSE,
      'update' => FALSE,
      'delete' => FALSE,
      'view' => FALSE,
      'view label' => TRUE,
    ]$user);

    // Switch to an anonymous user account.     $account_switcher = \Drupal::service('account_switcher');
    $account_switcher->switchTo(new AnonymousUserSession());

    // The anonymous user is allowed to view the anonymous user label.     $this->assertEntityAccess([
      'create' => FALSE,
      'update' => FALSE,
      'delete' => FALSE,
      'view' => FALSE,
      'view label' => TRUE,
    ]$anonymous_user);

    // The anonymous user is allowed to view user labels.
    // idea being if you were properly logged out you should be seeing a login     // screen.     $assert_session = $this->assertSession();
    $destination = Url::fromRoute('user.page')->toString();
    $this->drupalGet(Url::fromRoute('user.logout', []['query' => ['destination' => $destination]]));
    $assert_session->fieldExists('name');
    $assert_session->fieldExists('pass');

    // @see BrowserTestBase::drupalUserIsLoggedIn()     unset($this->loggedInUser->sessionId);
    $this->loggedInUser = FALSE;
    \Drupal::currentUser()->setAccount(new AnonymousUserSession());
  }

  /** * Returns WebAssert object. * * @param string $name * (optional) Name of the session. Defaults to the active session. * * @return \Drupal\Tests\WebAssert * A new web-assert option for asserting the presence of elements with. */
  

class AnonymousUserSessionTest extends UnitTestCase {

  /** * Tests the method getRoles exclude or include locked roles based in param. * * @covers ::getRoles * @todo Move roles constants to a class/interface */
  public function testUserGetRoles() {
    $anonymous_user = new AnonymousUserSession();
    $this->assertEquals([RoleInterface::ANONYMOUS_ID]$anonymous_user->getRoles());
    $this->assertEquals([]$anonymous_user->getRoles(TRUE));
  }

}

  public function testCliPublishing() {
    $this->initializeWorkspacesModule();
    $this->switchToWorkspace('stage');

    // Add a workspace-specific revision to a pre-existing node.     $node = $this->entityTypeManager->getStorage('node')->load(2);
    $node->title->value = 'stage - 2 - r3 - published';
    $node->save();

    // Switch to an anonymous user account and the 'Live' workspace.     \Drupal::service('account_switcher')->switchTo(new AnonymousUserSession());
    \Drupal::service('workspaces.manager')->switchToLive();

    // Publish the workspace as anonymous, simulating a CLI request.     $this->workspaces['stage']->publish();
  }

  /** * Tests entity query overrides without any conditions. */
  public function testEntityQueryWithoutConditions() {
    $this->initializeWorkspacesModule();
    

  private function generateLogEntries($count$options = []) {
    global $base_root;

    $user = !empty($this->adminUser) ? $this->adminUser : new AnonymousUserSession();

    // Prepare the fields to be logged.     $log = $options + [
      'channel'     => 'custom',
      'message'     => 'Dblog test log message',
      'variables'   => [],
      'severity'    => RfcLogLevel::NOTICE,
      'link'        => NULL,
      'uid'         => $user->id(),
      'request_uri' => $base_root . \Drupal::request()->getRequestUri(),
      'referer'     => \Drupal::request()->server->get('HTTP_REFERER'),
      
$this->assertInstanceOf(OptionsProviderInterface::class$data);

    $filtered_html_user = $this->createUser(
      [FilterFormat::load('filtered_html')->getPermissionName()],
      NULL,
      FALSE,
      ['uid' => 2]
    );

    // Test with anonymous user.     $user = new AnonymousUserSession();
    \Drupal::currentUser()->setAccount($user);

    $expected_available_options = [
      'filtered_html' => 'Filtered HTML',
      'full_html' => 'Full HTML',
      'filter_test' => 'Test format',
      'plain_text' => 'Plain text',
    ];

    $available_values = $data->getPossibleValues();
    $this->assertEquals(array_keys($expected_available_options)$available_values);
    
    $comment->setPublished();
    $comment->save();
    $view = Views::getView('test_comment');
    $view->preview();

    // Check if I can see the comment approve link on an approved comment.     $approve_comment = $view->style_plugin->getField(1, 'approve_comment');
    $this->assertEmpty((string) $approve_comment, "Didn't find a comment approve link for an already approved comment.");

    // Check if I can see the comment approve link on an approved comment as an     // anonymous user.     $account_switcher->switchTo(new AnonymousUserSession());
    // Set the comment as unpublished again.     $comment->setUnpublished();
    $comment->save();

    $view = Views::getView('test_comment');
    $view->preview();
    $replyto_comment = $view->style_plugin->getField(0, 'approve_comment');
    $this->assertEmpty((string) $replyto_comment, "I can't approve the comment as an anonymous user.");
  }

  /** * Tests the comment reply link. */

  protected function handleAccess(Request $request) {
    /** @var \Drupal\Core\Authentication\AuthenticationManager $authentication_manager */
    $authentication_manager = $this->getContainer()->get('authentication');
    $account = $authentication_manager->authenticate($request) ?: new AnonymousUserSession();

    /** @var \Drupal\Core\Session\AccountProxyInterface $current_user */
    $current_user = $this->getContainer()->get('current_user');
    $current_user->setAccount($account);

    /** @var \Drupal\system\Access\DbUpdateAccessCheck $db_update_access */
    $db_update_access = $this->getContainer()->get('access_check.db_update');

    if (!Settings::get('update_free_access', FALSE) && !$db_update_access->access($account)->isAllowed()) {
      throw new AccessDeniedHttpException('In order to run update.php you need to either have "Administer software updates" permission or have set $settings[\'update_free_access\'] in your settings.php.');
    }
  }
Home | Imprint | This part of the site doesn't use cookies.