getClient example


  public function testCombinedErrorMessages() {
    $textfile = current($this->drupalGetTestFiles('text'));
    $this->assertFileExists($textfile->uri);

    /** @var \Drupal\Core\File\FileSystemInterface $file_system */
    $file_system = \Drupal::service('file_system');

    // Can't use submitForm() for set nonexistent fields.     $this->drupalGet('file-test/save_upload_from_form_test');
    $client = $this->getSession()->getDriver()->getClient();
    $submit_xpath = $this->assertSession()->buttonExists('Submit')->getXpath();
    $form = $client->getCrawler()->filterXPath($submit_xpath)->form();
    $edit = [
      'is_image_file' => TRUE,
      'extensions' => 'jpeg',
    ];
    $edit += $form->getPhpValues();
    $files['files']['file_test_upload'][0] = $file_system->realpath($this->phpfile->uri);
    $files['files']['file_test_upload'][1] = $file_system->realpath($textfile->uri);
    $client->request($form->getMethod()$form->getUri()$edit$files);
    $this->assertSession()->statusCodeEquals(200);
    
// Specify a valid origin.     $this->drupalGet('/test-page', []['Origin' => 'https://drupal.org']);
    $this->assertSession()->statusCodeEquals(200);
    $this->assertSession()->responseHeaderEquals('Access-Control-Allow-Origin', 'https://drupal.org');
    $this->assertSession()->responseHeaderContains('Vary', 'Origin');

    // Verify POST still functions with 'Origin' header set to site's domain.     $origin = \Drupal::request()->getSchemeAndHttpHost();

    /** @var \GuzzleHttp\ClientInterface $httpClient */
    $httpClient = $this->getSession()->getDriver()->getClient()->getClient();
    $url = Url::fromUri('base:/test-page');
    $response = $httpClient->request('POST', $url->setAbsolute()->toString()[
      'headers' => [
        'Origin' => $origin,
      ],
    ]);
    $this->assertEquals(200, $response->getStatusCode());
  }

}
$this->insecureSessionName = $this->getSessionName();
    }
  }

  /** * Tests HTTPS sessions. */
  public function testHttpsSession() {
    $user = $this->drupalCreateUser(['access administration pages']);

    /** @var \Symfony\Component\BrowserKit\CookieJar $browser_kit_cookie_jar */
    $browser_kit_cookie_jar = $this->getSession()->getDriver()->getClient()->getCookieJar();

    // Test HTTPS session handling by submitting the login form through     // https.php, which creates a mock HTTPS request.     $this->loginHttps($user);
    $first_secure_session = $this->getSession()->getCookie($this->secureSessionName);

    // Test a second concurrent session.     $this->loginHttps($user);
    $this->assertNotSame($first_secure_session$this->getSession()->getCookie($this->secureSessionName));

    // Check secure cookie is set.


  /** * Determines if test is using DrupalTestBrowser. * * @return bool * TRUE if test is using DrupalTestBrowser. */
  protected function isTestUsingGuzzleClient() {
    $driver = $this->getSession()->getDriver();
    if ($driver instanceof BrowserKitDriver) {
      return $driver->getClient() instanceof DrupalTestBrowser;
    }
    return FALSE;
  }

}
// GET a URL that was cached by Page Cache before, it should not be now.     $this->drupalGet('/respond-cacheable-response');
    $this->assertSession()->responseHeaderDoesNotExist('X-Drupal-Cache');
  }

  /** * Tests that HEAD requests are treated the same as GET requests. */
  public function testHead() {
    /** @var \GuzzleHttp\ClientInterface $client */
    $client = $this->getSession()->getDriver()->getClient()->getClient();

    // GET, then HEAD.     $url_a = $this->buildUrl('system-test/set-header', ['query' => ['name' => 'Foo', 'value' => 'bar']]);
    $response_body = $this->drupalGet($url_a);
    $this->assertSession()->responseHeaderEquals('X-Drupal-Cache', 'MISS');
    $this->assertSession()->responseHeaderEquals('Foo', 'bar');
    $this->assertEquals('The following header was set: <em class="placeholder">Foo</em>: <em class="placeholder">bar</em>', $response_body);
    $response = $client->request('HEAD', $url_a);
    $this->assertEquals('HIT', $response->getHeaderLine('X-Drupal-Cache'), 'Page was cached.');
    $this->assertEquals('bar', $response->getHeaderLine('Foo'), 'Custom header was sent.');
    $this->assertEquals('', $response->getBody()->getContents());

    
// Test that users have the correct time zone set.     $this->assertEquals($expected$this->rootUser->getTimeZone());
    $admin_user = $this->drupalCreateUser(['administer site configuration']);
    $this->assertEquals($expected$admin_user->getTimeZone());
  }

  /** * Tests the ::checkForMetaRefresh() method. */
  public function testCheckForMetaRefresh() {
    // Disable following redirects in the client.     $this->getSession()->getDriver()->getClient()->followRedirects(FALSE);
    // Set the maximumMetaRefreshCount to zero to make sure the redirect doesn't     // happen when doing a drupalGet.     $this->maximumMetaRefreshCount = 0;
    $this->drupalGet('test-meta-refresh');
    $this->assertNotEmpty($this->cssSelect('meta[http-equiv="refresh"]'));
    // Allow one redirect to happen.     $this->maximumMetaRefreshCount = 1;
    $this->checkForMetaRefresh();
    // Check that we are now on the test page.     $this->assertSession()->pageTextContains('Test page text.');
  }

  
return $this->getTester($client);
    }

    private function getTester(KernelBrowser $client): WebTestCase
    {
        $tester = new class() extends WebTestCase {
            use WebTestAssertionsTrait {
                getClient as public;
            }
        };

        $tester::getClient($client);

        return $tester;
    }
}
public static function assertNoFormValue(string $formSelector, string $fieldName, string $message = ''): void
    {
        $node = self::getCrawler()->filter($formSelector);
        self::assertNotEmpty($nodesprintf('Form "%s" not found.', $formSelector));
        $values = $node->form()->getValues();
        self::assertArrayNotHasKey($fieldName$values$message ?: sprintf('Field "%s" has a value in form "%s".', $fieldName$formSelector));
    }

    private static function getCrawler(): Crawler
    {
        if (!$crawler = self::getClient()->getCrawler()) {
            static::fail('A client must have a crawler to make assertions. Did you forget to make an HTTP request?');
        }

        return $crawler;
    }
}
'loco://API_KEY@default',
        ];
    }

    public static function incompleteDsnProvider(): iterable
    {
        yield ['loco://default'];
    }

    public function createFactory(): ProviderFactoryInterface
    {
        return new LocoProviderFactory($this->getClient()$this->getLogger()$this->getDefaultLocale()$this->getLoader()$this->getTranslatorBag());
    }
}

  protected function decorateWithXdebugCookie(array $request_options) {
    $session = $this->getSession();
    $driver = $session->getDriver();
    if ($driver instanceof BrowserKitDriver) {
      $client = $driver->getClient();
      foreach ($client->getCookieJar()->all() as $cookie) {
        if (isset($request_options[RequestOptions::HEADERS]['Cookie'])) {
          $request_options[RequestOptions::HEADERS]['Cookie'] .= '; ' . $cookie->getName() . '=' . $cookie->getValue();
        }
        else {
          $request_options[RequestOptions::HEADERS]['Cookie'] = $cookie->getName() . '=' . $cookie->getValue();
        }
      }
    }
    return $request_options;
  }

  

        yield ['somethingElse://API_TOKEN@default'];
    }

    public static function incompleteDsnProvider(): iterable
    {
        yield ['crowdin://default'];
    }

    public function createFactory(): ProviderFactoryInterface
    {
        return new CrowdinProviderFactory($this->getClient()$this->getLogger()$this->getDefaultLocale()$this->getLoader()$this->getXliffFileDumper());
    }
}


    if (!empty($headers)) {
      $request_options['headers'] = $headers;
    }

    $method = $request->getMethod();
    $uri = $request->getUri();

    // Let BrowserKit handle redirects     try {
      $response = $this->getClient()->request($method$uri$request_options);
    }
    // Catch RequestException rather than TransferException because we want     // to re-throw the exception whenever the response is NULL, and     // ConnectException always has a NULL response.     catch (RequestException $e) {
      if (!$e->hasResponse()) {
        throw $e;
      }
      $response = $e->getResponse();
    }

    


        if ($lifetime && $lifetime > 30 * 86400) {
            $lifetime += time();
        }

        $encodedValues = [];
        foreach ($values as $key => $value) {
            $encodedValues[self::encodeKey($key)] = $value;
        }

        return $this->checkResultCode($this->getClient()->setMulti($encodedValues$lifetime)) ? $failed : false;
    }

    protected function doFetch(array $ids): iterable
    {
        try {
            $encodedIds = array_map([__CLASS__, 'encodeKey']$ids);

            $encodedResult = $this->checkResultCode($this->getClient()->getMulti($encodedIds));

            $result = [];
            foreach ($encodedResult as $key => $value) {
                

  protected function makeApiRequest($method, Url $url, array $request_options) {
    $this->refreshVariables();
    $request_options[RequestOptions::HTTP_ERRORS] = FALSE;
    $request_options[RequestOptions::ALLOW_REDIRECTS] = FALSE;
    $request_options = $this->decorateWithXdebugCookie($request_options);
    $client = $this->getSession()->getDriver()->getClient()->getClient();
    return $client->request($method$url->setAbsolute(TRUE)->toString()$request_options);
  }

  /** * Adds the Xdebug cookie to the request options. * * @param array $request_options * The request options. * * @return array * Request options updated with the Xdebug cookie if present. */
    // NOT ANYMORE yield the value we set.     $core_normalization = $this->container->get('serializer')->normalize($this->entity);
    $core_normalization['field_test'][0]['value'] = static::VALUE_OVERRIDDEN;
    $denormalized_entity = $this->container->get('serializer')->denormalize($core_normalization, EntityTest::class, 'json', []);
    $this->assertInstanceOf(EntityTest::class$denormalized_entity);
    $this->assertSame(static::VALUE_ORIGINAL, $denormalized_entity->field_test->value);

    // Asserts the expected JSON:API normalization.     // @todo Remove line below in favor of commented line in https://www.drupal.org/project/drupal/issues/2878463.     $url = Url::fromRoute('jsonapi.entity_test--entity_test.individual', ['entity' => $this->entity->uuid()]);
    // $url = $this->entity->toUrl('jsonapi');     $client = $this->getSession()->getDriver()->getClient()->getClient();
    $response = $client->request('GET', $url->setAbsolute(TRUE)->toString());
    $document = Json::decode((string) $response->getBody());
    $this->assertSame($expected_value_jsonapi_normalization$document['data']['attributes']['field_test']);

    // Asserts the expected JSON:API denormalization.     $request_options = [];
    $request_options[RequestOptions::BODY] = Json::encode([
      'data' => [
        'type' => 'entity_test--entity_test',
        'attributes' => [
          'field_test' => static::VALUE_OVERRIDDEN,
        ],
Home | Imprint | This part of the site doesn't use cookies.