GithubHelp home page GithubHelp logo

drupal-test-helpers's Introduction

drupal-test-helpers

Helpers for writing better Kernel and Unit tests for Drupal

Traits

The following traits are provided by this library for tests

RequestTrait

Provides methods to assert requests and responses within Kernel tests.

final class RequestTraitTest extends KernelTestBase
{
    use RequestTrait;

    /**
     * @var string[]
     */
    protected static $modules = ['system', 'user'];

    public function testDoRequest(): void
    {
        $this->installConfig(['system']);
        $this->doRequest(Request::create('/user/login'));
        self::assertStringContainsString(
            'Enter your  username.',
            $this->getRawContent()
        );
    }
}

drupal-test-helpers's People

Contributors

mglaman avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

Forkers

joachim-n

drupal-test-helpers's Issues

TestHttpKernel needs to implement TerminableInterface

It doesn't implement TerminableInterface so termination of results doesn't happen, even though the decorated http kernel does.

I discovered in \Drupal\Core\StackMiddleware\StackedHttpKernel::terminate with

      if (!$previous instanceof TerminableInterface && $kernel instanceof TerminableInterface) {
        $kernel->terminate($request, $response);
      }

doFormSubmit should catch EnforcedResponseException when test HTTP kernel is active

        $response = $this->doRequest(Request::create($uri, 'POST', $formData));
        if ($followRedirect && $response->getStatusCode() === Response::HTTP_SEE_OTHER) {
            $request = Request::create((string) $response->headers->get('Location'));
            return $this->doRequest($request);
        }

The doRequest needs to wrap a try/catch and take that exception response.

submitting forms

    $form_data = [
      'name' => 'foo',
      'pass' => 'barbaz',
      // @phpstan-ignore-next-line
      'form_build_id' => (string) $this->cssSelect('input[name="form_build_id"]')[0]->attributes()->value[0],
      // @phpstan-ignore-next-line
      'form_id' => (string) $this->cssSelect('input[name="form_id"]')[0]->attributes()->value[0],
      // @phpstan-ignore-next-line
      'op' => (string) $this->cssSelect('input[name="op"]')[0]->attributes()->value[0],
    ];

Example for performing a login. needs to handle form_token if authenticated for CSRF

Saving HTML outout

The current way this is supported:

Use BrowserHtmlDebugTrait trait and call initBrowserOutputFile during setUp.

Then you can call $this->htmlOutput($this->getRawContent()).

It does not have all the extra output provided by \Drupal\Tests\BrowserHtmlDebugTrait::getResponseLogHandler which is a Guzzle middleware.

CSRF on Kernel tests

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;
  }

decorate the http_kernel service to not catch exceptions

Drupal's http_kernel service is StackedHttpKernel, which has $catch = TRUE.

That means that if the request throws an exception somewhere, the response 500 and you don't know why.

I'm wondering if it would be worth adding a testing_http_kernel which decorates the original service and sets $catch = FALSE. What do you think?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.