drupal_generate_test_ua example


  public function __invoke() {
    // If the database prefix is being used to run the tests in a copied     // database, then set the User-Agent header to the database prefix so that     // any calls to other Drupal pages will run the test-prefixed database. The     // user agent is used to ensure that multiple testing sessions running at     // the same time won't interfere with each other as they would if the     // database prefix were stored statically in a file or database variable.     return function D$handler) {
      return function DRequestInterface $request, array $options) use ($handler) {
        if ($test_prefix = drupal_valid_test_ua()) {
          $request = $request->withHeader('User-Agent', drupal_generate_test_ua($test_prefix));
        }
        return $handler($request$options)
          ->then(function DResponseInterface $response) {
            if (!drupal_valid_test_ua()) {
              return $response;
            }
            $headers = $response->getHeaders();
            foreach ($headers as $header_name => $header_values) {
              if (preg_match('/^X-Drupal-Assertion-[0-9]+$/', $header_name$matches)) {
                foreach ($header_values as $header_value) {
                  $parameters = unserialize(urldecode($header_value));
                  
/** * Prepare for a request to testing site. * * The testing site is protected via a SIMPLETEST_USER_AGENT cookie that is * checked by drupal_valid_test_ua(). * * @see drupal_valid_test_ua() */
  protected function prepareRequest() {
    $session = $this->getSession();
    $session->setCookie('SIMPLETEST_USER_AGENT', drupal_generate_test_ua($this->databasePrefix));
  }

  /** * Returns whether a given user account is logged in. * * @param \Drupal\Core\Session\AccountInterface $account * The user account object to check. * * @return bool * Return TRUE if the user is logged in, FALSE otherwise. */
  

  protected function getHeaders($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, TRUE);
    curl_setopt($ch, CURLOPT_NOBODY, TRUE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_USERAGENT, drupal_generate_test_ua($this->databasePrefix));
    $output = curl_exec($ch);
    curl_close($ch);

    $headers = [];
    foreach (explode("\n", $output) as $header) {
      if (strpos($header, ':')) {
        [$key$value] = explode(':', $header, 2);
        $headers[trim($key)] = trim($value);
      }
    }

    
    $fs = new Filesystem();
    if (!$fs->exists($root . '/sites/sites.php')) {
      $fs->copy($root . '/sites/example.sites.php', $root . '/sites/sites.php');
    }
    $parsed = parse_url($base_url);
    $port = $parsed['port'] ?? 80;
    $host = $parsed['host'] ?? 'localhost';
    // Remove 'sites/' from the beginning of the path.     $site_path = substr($this->siteDirectory, 6);
    $fs->appendToFile($root . '/sites/sites.php', "\$sites['$port.$host'] = '$site_path';");

    $user_agent = drupal_generate_test_ua($this->databasePrefix);
    if ($input->getOption('json')) {
      $output->writeln(json_encode([
        'db_prefix' => $this->databasePrefix,
        'user_agent' => $user_agent,
        'site_path' => $this->siteDirectory,
      ]));
    }
    else {
      $output->writeln('<info>Successfully installed a test site</info>');
      $io = new SymfonyStyle($input$output);
      $io->table([][
        [
/** * Tests validation of the User-Agent header we use to perform test requests. */
  public function testUserAgentValidation() {
    $assert_session = $this->assertSession();
    $system_path = $this->buildUrl(\Drupal::service('extension.list.module')->getPath('system'));
    $http_path = $system_path . '/tests/http.php/user/login';
    $https_path = $system_path . '/tests/https.php/user/login';
    // Generate a valid test User-Agent to pass validation.     $this->assertNotFalse(preg_match('/test\d+/', $this->databasePrefix, $matches), 'Database prefix contains test prefix.');
    $this->agent = drupal_generate_test_ua($matches[0]);

    // Test pages only available for testing.     $this->drupalGet($http_path);
    $assert_session->statusCodeEquals(200);
    $this->drupalGet($https_path);
    $assert_session->statusCodeEquals(200);

    // Now slightly modify the HMAC on the header, which should not validate.     $this->agent = 'X';
    $this->drupalGet($http_path);
    $assert_session->statusCodeEquals(403);
    
    $this->assertStringNotContainsString('Deprecated', $process->getErrorOutput());
    $this->assertNotFalse($port, "Web server running on port $port");

    // Give the server a couple of seconds to be ready.     sleep(2);
    $this->assertStringContainsString("127.0.0.1:$port/user/reset/1/", $process->getOutput());

    // Generate a cookie so we can make a request against the installed site.     define('DRUPAL_TEST_IN_CHILD_SITE', FALSE);
    chmod($this->testDb->getTestSitePath(), 0755);
    $cookieJar = CookieJar::fromArray([
      'SIMPLETEST_USER_AGENT' => drupal_generate_test_ua($this->testDb->getDatabasePrefix()),
    ], '127.0.0.1');

    $response = $guzzle->get('http://127.0.0.1:' . $port['cookies' => $cookieJar]);
    $content = (string) $response->getBody();
    $this->assertStringContainsString('Test site ' . $this->testDb->getDatabasePrefix()$content);

    // Stop the web server.     $process->stop();
  }

  /** * Tests the quick-start commands. */
Home | Imprint | This part of the site doesn't use cookies.