setCurrentUser example

/** * Tests the deletion of workspaces. */
  public function testDeletingWorkspaces() {
    $admin = $this->createUser([
      'administer nodes',
      'create workspace',
      'view any workspace',
      'edit any workspace',
      'delete any workspace',
    ]);
    $this->setCurrentUser($admin);

    /** @var \Drupal\workspaces\WorkspaceAssociationInterface $workspace_association */
    $workspace_association = \Drupal::service('workspaces.association');

    // Create a workspace with a very small number of associated node revisions.     $workspace_1 = Workspace::create([
      'id' => 'gibbon',
      'label' => 'Gibbon',
    ]);
    $workspace_1->save();
    $this->workspaceManager->setActiveWorkspace($workspace_1);

    

  public function __construct(ConfigFactoryInterface $config, ConfigurableLanguageManagerInterface $language_manager, LanguageNegotiatorInterface $negotiator, AccountInterface $current_user, ConfigSubscriber $config_subscriber) {
    $this->config = $config;
    $this->languageManager = $language_manager;
    $this->negotiator = $negotiator;
    $this->negotiator->setCurrentUser($current_user);
    $this->configSubscriber = $config_subscriber;
  }

  /** * {@inheritdoc} */
  public function processInbound($path, Request $request) {
    if (!empty($path)) {
      $scope = 'inbound';
      if (!isset($this->processors[$scope])) {
        $this->initProcessors($scope);
      }
$logger = $this->createMock('Psr\Log\LoggerInterface');
    $logger->expects($this->once())
      ->method('log')
      ->with($this->anything()$message$this->callback($expected));
    $channel->addLogger($logger);
    if ($request) {
      $requestStack = new RequestStack();
      $requestStack->push($request);
      $channel->setRequestStack($requestStack);
    }
    if ($current_user) {
      $channel->setCurrentUser($current_user);
    }
    $channel->log(rand(0, 7)$message);
  }

  /** * Tests LoggerChannel::log() recursion protection. * * @covers ::log */
  public function testLogRecursionProtection() {
    $channel = new LoggerChannel('test');
    

  public function get($channel) {
    if (!isset($this->channels[$channel])) {
      $instance = new LoggerChannel($channel);

      // If we have a container set the request_stack and current_user services       // on the channel. It is up to the channel to determine if there is a       // current request.       if ($this->container) {
        $instance->setRequestStack($this->container->get('request_stack'));
        $instance->setCurrentUser($this->container->get('current_user'));
      }

      // Pass the loggers to the channel.       $instance->setLoggers($this->loggers);
      $this->channels[$channel] = $instance;
    }

    return $this->channels[$channel];
  }

  /** * {@inheritdoc} */
// Assert the form class is added to the media source.     $this->assertSame(FileUploadForm::class$image_source_definition['forms']['media_library_add']);
    $this->assertSame(OEmbedForm::class$remote_video_source_definition['forms']['media_library_add']);

    // Assert the media library UI does not contains the add form when the user     // does not have access.     $this->assertEmpty($this->buildLibraryUi('image')['content']['form']);
    $this->assertEmpty($this->buildLibraryUi('remote_video')['content']['form']);

    // Create a user that has access to create the image media type but not the     // remote video media type.     $this->setCurrentUser($this->createUser([
      'create image media',
    ]));
    // Assert the media library UI only contains the add form for the image     // media type.     $this->assertSame('managed_file', $this->buildLibraryUi('image')['content']['form']['container']['upload']['#type']);
    $this->assertEmpty($this->buildLibraryUi('remote_video')['content']['form']);

    // Create a user that has access to create both media types.     $this->setCurrentUser($this->createUser([
      'create image media',
      'create remote_video media',
    ]));

  }

  /** * Get an instance of the normalizer to test. */
  protected function getNormalizer(AccountInterface $current_user = NULL) {
    if (is_null($current_user)) {
      $current_user = $this->setUpCurrentUser();
    }
    else {
      $this->setCurrentUser($current_user);
    }
    $normalizer = new LinkCollectionNormalizer($current_user);
    $normalizer->setSerializer($this->serializer);
    return $normalizer;
  }

}
$this->installSchema('system', ['sequences']);
    $this->installSchema('workspaces', ['workspace_association']);

    $this->createContentType(['type' => 'article']);

    $permissions = array_intersect([
      'administer nodes',
      'create workspace',
      'edit any workspace',
      'view any workspace',
    ]array_keys($this->container->get('user.permissions')->getPermissions()));
    $this->setCurrentUser($this->createUser($permissions));

    $this->workspaces['stage'] = Workspace::create(['id' => 'stage', 'label' => 'Stage']);
    $this->workspaces['stage']->save();
    $this->workspaces['dev'] = Workspace::create(['id' => 'dev', 'parent' => 'stage', 'label' => 'Dev']);
    $this->workspaces['dev']->save();
  }

  /** * Tests the revisions tracked by a workspace. * * @covers ::getTrackedEntities * @covers ::getAssociatedRevisions */

      User::create($values)->save();
    }

    // If we automatically created user account 1, we need to create a regular     // user account before setting up the current user service to avoid     // potential false positives caused by access control bypass.     if ($autocreate_user_1) {
      $user = $this->createUser($original_permissions, NULL, $original_admin$original_values);
    }

    $this->setCurrentUser($user);

    return $user;
  }

  /** * Switch the current logged in user. * * @param \Drupal\Core\Session\AccountInterface $account * The user account object. */
  protected function setCurrentUser(AccountInterface $account) {
    
$nodes = [];
    $node_labels = [];
    foreach ($node_values as $key => $values) {
      $node = Node::create($values);
      $node->save();
      $nodes[$key] = $node;
      $node_labels[$key] = Html::escape($node->label());
    }

    // Test as a non-admin.     $normal_user = $this->createUser(['access content']);
    $this->setCurrentUser($normal_user);
    $referenceable_tests = [
      [
        'arguments' => [
          [NULL, 'CONTAINS'],
        ],
        'result' => [
          'article' => [
            $nodes['published1']->id() => $node_labels['published1'],
            $nodes['published2']->id() => $node_labels['published2'],
          ],
        ],
      ],
$eventDispatcher = $this->container->get('event_dispatcher');
    $kernel = $this->container->get('kernel');

    $eventDispatcher->dispatch(new RequestEvent($kernel, Request::create('http://www.example.com'), HttpKernelInterface::MAIN_REQUEST));

    $this->assertEquals('Australia/Adelaide', date_default_timezone_get());

    $user = $this->createUser([]);
    $user->set('timezone', 'Australia/Lord_Howe');
    $user->save();

    $this->setCurrentUser($user);

    $this->assertEquals('Australia/Lord_Howe', date_default_timezone_get());

  }

}

  public function testWorkspaceAccess($operation$permission) {
    $user = $this->createUser();
    $this->setCurrentUser($user);
    $workspace = Workspace::create(['id' => 'oak']);
    $workspace->save();

    $this->assertFalse($workspace->access($operation$user));

    \Drupal::entityTypeManager()->getAccessControlHandler('workspace')->resetCache();
    $role = $this->createRole([$permission]);
    $user->addRole($role);
    $this->assertTrue($workspace->access($operation$user));
  }

  
$this->container->set('logger.factory', $logger_factory);
    $this->installEntitySchema('user');

    // Test unavailable plugin.     $config = $this->config('language.types');
    $config->set('configurable', [LanguageInterface::TYPE_URL]);
    $config->set('negotiation.language_url.enabled', [
      self::CLASS => -3,
    ]);
    $config->save();
    $languageNegotiator = $this->container->get('language_negotiator');
    $languageNegotiator->setCurrentUser($this->prophesize('Drupal\Core\Session\AccountInterface')->reveal());
    try {
      $languageNegotiator->initializeType(LanguageInterface::TYPE_URL);
    }
    catch (PluginNotFoundException $exception) {
      $this->fail('Plugin not found exception unhandled.');
    }
    $log_message = $logger->cleanLogs()[0];
    $this->assertEquals('error', $log_message[0]);
    $this->assertStringContainsString('The "Drupal\Tests\language\Kernel\LanguageNegotiatorPluginTest" plugin does not exist.', $log_message[1]);
  }

}
    $this->workspaces['live'] = Workspace::create(['id' => 'live', 'label' => 'Live']);
    $this->workspaces['live']->save();
    $this->workspaces['stage'] = Workspace::create(['id' => 'stage', 'label' => 'Stage']);
    $this->workspaces['stage']->save();

    $permissions = array_intersect([
      'administer nodes',
      'create workspace',
      'edit any workspace',
      'view any workspace',
    ]array_keys($this->container->get('user.permissions')->getPermissions()));
    $this->setCurrentUser($this->createUser($permissions));
  }

  /** * Sets a given workspace as active. * * @param string $workspace_id * The ID of the workspace to switch to. */
  protected function switchToWorkspace($workspace_id) {
    // Switch the test runner's context to the specified workspace.     $workspace = $this->entityTypeManager->getStorage('workspace')->load($workspace_id);
    
$view->argument['name']->argument_validated = NULL;

    $this->assertTrue($view->argument['name']->setArgument($this->names[4]));
    $this->assertEquals($this->names[4]$view->argument['name']->getTitle());
  }

  /** * Tests the access checking in term name argument validator plugin. */
  public function testArgumentValidatorTermNameAccess() {
    $this->installConfig(['user']);
    $this->setCurrentUser($this->createUser(['access content']));
    $view = Views::getView('test_taxonomy_name_argument');
    $view->initHandlers();

    // Enable access checking on validator.     $view->argument['name']->options['validate_options']['access'] = TRUE;
    // Allow all bundles.     $view->argument['name']->options['validate_options']['bundles'] = [];

    // A uniquely named unpublished term in an allowed bundle.     $this->terms[0]->setUnpublished()->save();
    $this->assertFalse($view->argument['name']->setArgument($this->names[0]));
    
/** @var \Drupal\node\NodeInterface $node */
    $node = Node::load(6);
    $node->setTitle('a' . $this->randomMachineName());
    $node->save();
    $this->doTestRenderedOutput($this->editorUser);
  }

  /** * Tests that rows are not cached when the none cache plugin is used. */
  public function testNoCaching() {
    $this->setCurrentUser($this->regularUser);
    $view = Views::getView('test_row_render_cache_none');
    $view->setDisplay();
    $view->preview();

    /** @var \Drupal\Core\Render\RenderCacheInterface $render_cache */
    $render_cache = $this->container->get('render_cache');

    /** @var \Drupal\views\Plugin\views\cache\CachePluginBase $cache_plugin */
    $cache_plugin = $view->display_handler->getPlugin('cache');

    foreach ($view->result as $row) {
      
Home | Imprint | This part of the site doesn't use cookies.