mglaman / drupal-test-helpers

Helpers for writing better Kernel and Unit tests for Drupal
GNU General Public License v2.0
10 stars 2 forks source link

CSRF on Kernel tests #1

Closed mglaman closed 1 year ago

mglaman commented 2 years ago

CSRF requires calling stampNew on the session metadata. There's also a trick for rendering CSRF protected routes due to Drupal core leveraging placeholders for delayed rendering.

  /**
   * Get the string URL for a CSRF protected route.
   *
   * @param \Drupal\Core\Url $url
   *   The URL.
   *
   * @return string
   *   The URL string.
   */
  protected function getCsrfUrlString(Url $url): string {
    $context = new RenderContext();
    $url = $this->container->get('renderer')->executeInRenderContext($context, function () use ($url) {
      return $url->toString();
    });
    $bubbleable_metadata = $context->pop();
    assert($bubbleable_metadata instanceof BubbleableMetadata);
    $build = [
      '#plain_text' => $url,
    ];
    $bubbleable_metadata->applyTo($build);
    return (string) $this->container->get('renderer')->renderPlain($build);
  }
  /**
   * Creates a user, its session, and sets it as the current user.
   *
   * @return \Drupal\user\UserInterface
   *   The user.
   */
  protected function createUserWithSession(): UserInterface {
    $this->container->get('session_manager.metadata_bag')->stampNew();
    $user = $this->createUser(['administer site configuration']);
    self::assertNotFalse($user);
    $this->container->get('current_user')->setAccount($user);
    return $user;
  }