ApiTestBase.php in Lightning API 8
File
modules/api_test/tests/src/Functional/ApiTestBase.php
View source
<?php
namespace Drupal\Tests\api_test\Functional;
use Drupal\Component\Serialization\Json;
use Drupal\Core\Url;
use Drupal\Tests\BrowserTestBase;
use Psr\Http\Message\ResponseInterface;
abstract class ApiTestBase extends BrowserTestBase {
protected static $modules = [
'api_test',
];
protected $profile = 'standard';
protected function setUp() {
parent::setUp();
$this
->generateKeys();
}
protected function getToken($client_options) {
$client = $this->container
->get('http_client');
$url = $this
->buildUrl('/oauth/token');
$response = $client
->post($url, $client_options);
$body = $this
->decodeResponse($response);
$this
->assertArrayHasKey('access_token', $body);
return $body['access_token'];
}
protected function generateKeys() {
$account = $this
->drupalCreateUser([], NULL, TRUE);
$this
->drupalLogin($account);
$url = Url::fromRoute('lightning_api.generate_keys');
$this
->drupalGet($url);
$values = [
'dir' => drupal_realpath('temporary://'),
'private_key' => 'private.key',
'public_key' => 'public.key',
];
$conf = getenv('OPENSSL_CONF');
if ($conf) {
$values['conf'] = $conf;
}
$this
->drupalPostForm(NULL, $values, 'Generate keys');
$this
->assertSession()
->pageTextContains('A key pair was generated successfully.');
$this
->drupalLogout();
}
protected function request($endpoint, $method = 'get', $token = NULL, $data = NULL) {
$client = $this->container
->get('http_client');
$options = NULL;
if ($token) {
$options = [
'headers' => [
'Authorization' => 'Bearer ' . $token,
'Content-Type' => 'application/vnd.api+json',
],
];
}
if ($data) {
$options['json'] = $data;
}
$url = $this
->buildUrl($endpoint);
return $client
->{$method}($url, $options);
}
protected function decodeResponse(ResponseInterface $response) {
$body = (string) $response
->getBody();
$data = Json::decode($body);
if (json_last_error() === JSON_ERROR_NONE) {
return $data;
}
else {
$this
->fail($body);
}
}
}