View source
<?php
namespace Drupal\rest\Tests;
@trigger_error(__NAMESPACE__ . '\\RESTTestBase is deprecated in Drupal 8.3.x-dev and will be removed before Drupal 9.0.0. Use \\Drupal\\Tests\\rest\\Functional\\ResourceTestBase and \\Drupal\\Tests\\rest\\Functional\\EntityResource\\EntityResourceTestBase instead. Only retained for contributed module tests that may be using this base class.', E_USER_DEPRECATED);
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Config\Entity\ConfigEntityType;
use Drupal\node\NodeInterface;
use Drupal\rest\RestResourceConfigInterface;
use Drupal\simpletest\WebTestBase;
use GuzzleHttp\Cookie\FileCookieJar;
use GuzzleHttp\Cookie\SetCookie;
abstract class RESTTestBase extends WebTestBase {
protected $resourceConfigStorage;
protected $defaultFormat;
protected $defaultMimeType;
protected $testEntityType = 'entity_test';
protected $defaultAuth;
protected $responseBody;
public static $modules = [
'rest',
'entity_test',
];
protected $response;
protected function setUp() {
parent::setUp();
$this->defaultFormat = 'hal_json';
$this->defaultMimeType = 'application/hal+json';
$this->defaultAuth = [
'cookie',
];
$this->resourceConfigStorage = $this->container
->get('entity_type.manager')
->getStorage('rest_resource_config');
if (in_array('node', static::$modules)) {
$this
->drupalCreateContentType([
'name' => 'resttest',
'type' => 'resttest',
]);
}
$this->cookieFile = $this->publicFilesDirectory . '/cookie.jar';
}
protected function cookies() {
$cookies = [];
foreach ($this->cookies as $key => $cookie) {
$cookies[$key][] = $cookie['value'];
}
$request = \Drupal::request();
$cookies = NestedArray::mergeDeep($cookies, $this
->extractCookiesFromRequest($request));
$cookie_jar = new FileCookieJar($this->cookieFile);
foreach ($cookies as $key => $cookie_values) {
foreach ($cookie_values as $cookie_value) {
if ($cookie_value !== 'deleted') {
$cookie_jar
->setCookie(new SetCookie([
'Name' => $key,
'Value' => $cookie_value,
'Domain' => $request
->getHost(),
]));
}
}
}
return $cookie_jar;
}
protected function httpRequest($url, $method, $body = NULL, $mime_type = NULL, $csrf_token = NULL) {
if (!isset($mime_type)) {
$mime_type = $this->defaultMimeType;
}
if (!in_array($method, [
'GET',
'HEAD',
'OPTIONS',
'TRACE',
])) {
$requested_token = $this
->drupalGet('session/token');
}
$client = \Drupal::httpClient();
$url = $this
->buildUrl($url);
$options = [
'http_errors' => FALSE,
'cookies' => $this
->cookies(),
'curl' => [
CURLOPT_HEADERFUNCTION => [
&$this,
'curlHeaderCallback',
],
],
];
switch ($method) {
case 'GET':
$options += [
'headers' => [
'Accept' => $mime_type,
],
];
$response = $client
->get($url, $options);
break;
case 'HEAD':
$response = $client
->head($url, $options);
break;
case 'POST':
$options += [
'headers' => $csrf_token !== FALSE ? [
'Content-Type' => $mime_type,
'X-CSRF-Token' => $csrf_token === NULL ? $requested_token : $csrf_token,
] : [
'Content-Type' => $mime_type,
],
'body' => $body,
];
$response = $client
->post($url, $options);
break;
case 'PUT':
$options += [
'headers' => $csrf_token !== FALSE ? [
'Content-Type' => $mime_type,
'X-CSRF-Token' => $csrf_token === NULL ? $requested_token : $csrf_token,
] : [
'Content-Type' => $mime_type,
],
'body' => $body,
];
$response = $client
->put($url, $options);
break;
case 'PATCH':
$options += [
'headers' => $csrf_token !== FALSE ? [
'Content-Type' => $mime_type,
'X-CSRF-Token' => $csrf_token === NULL ? $requested_token : $csrf_token,
] : [
'Content-Type' => $mime_type,
],
'body' => $body,
];
$response = $client
->patch($url, $options);
break;
case 'DELETE':
$options += [
'headers' => $csrf_token !== FALSE ? [
'Content-Type' => $mime_type,
'X-CSRF-Token' => $csrf_token === NULL ? $requested_token : $csrf_token,
] : [],
];
$response = $client
->delete($url, $options);
break;
}
$this->response = $response;
$this->responseBody = (string) $response
->getBody();
$this
->setRawContent($this->responseBody);
$this
->refreshVariables();
$this
->verbose($method . ' request to: ' . $url . '<hr />Code: ' . $this->response
->getStatusCode() . (isset($options['headers']) ? '<hr />Request headers: ' . nl2br(print_r($options['headers'], TRUE)) : '') . (isset($options['body']) ? '<hr />Request body: ' . nl2br(print_r($options['body'], TRUE)) : '') . '<hr />Response headers: ' . nl2br(print_r($response
->getHeaders(), TRUE)) . '<hr />Response body: ' . $this->responseBody);
return $this->responseBody;
}
protected function assertResponse($code, $message = '', $group = 'Browser') {
if (!isset($this->response)) {
return parent::assertResponse($code, $message, $group);
}
return $this
->assertEqual($code, $this->response
->getStatusCode(), $message ? $message : "HTTP response expected {$code}, actual {$this->response->getStatusCode()}", $group);
}
protected function drupalGetHeaders($all_requests = FALSE) {
if (!isset($this->response)) {
return parent::drupalGetHeaders($all_requests);
}
$lowercased_keys = array_map('strtolower', array_keys($this->response
->getHeaders()));
return array_map(function (array $header) {
return implode(', ', $header);
}, array_combine($lowercased_keys, array_values($this->response
->getHeaders())));
}
protected function drupalGetHeader($name, $all_requests = FALSE) {
if (!isset($this->response)) {
return parent::drupalGetHeader($name, $all_requests);
}
if ($header = $this->response
->getHeader($name)) {
return implode(', ', $header);
}
}
protected function entityCreate($entity_type) {
return $this->container
->get('entity_type.manager')
->getStorage($entity_type)
->create($this
->entityValues($entity_type));
}
protected function entityValues($entity_type_id) {
switch ($entity_type_id) {
case 'entity_test':
return [
'name' => $this
->randomMachineName(),
'user_id' => 1,
'field_test_text' => [
0 => [
'value' => $this
->randomString(),
'format' => 'plain_text',
],
],
];
case 'config_test':
return [
'id' => $this
->randomMachineName(),
'label' => 'Test label',
];
case 'node':
return [
'title' => $this
->randomString(),
'type' => 'resttest',
];
case 'node_type':
return [
'type' => 'article',
'name' => $this
->randomMachineName(),
];
case 'user':
return [
'name' => $this
->randomMachineName(),
];
case 'comment':
return [
'subject' => $this
->randomMachineName(),
'entity_type' => 'node',
'comment_type' => 'comment',
'comment_body' => $this
->randomString(),
'entity_id' => 'invalid',
'field_name' => 'comment',
];
case 'taxonomy_vocabulary':
return [
'vid' => 'tags',
'name' => $this
->randomMachineName(),
];
case 'block':
$this->container
->get('theme_installer')
->install([
'bartik',
]);
return [
'id' => strtolower($this
->randomMachineName(8)),
'plugin' => 'system_powered_by_block',
'theme' => 'bartik',
'region' => 'header',
];
default:
if ($this
->isConfigEntity($entity_type_id)) {
return $this
->configEntityValues($entity_type_id);
}
return [];
}
}
protected function enableService($resource_type, $method = 'GET', $format = NULL, array $auth = []) {
if ($resource_type) {
$resource_config_id = str_replace(':', '.', $resource_type);
$resource_config = $this->resourceConfigStorage
->load($resource_config_id);
if (!$resource_config) {
$resource_config = $this->resourceConfigStorage
->create([
'id' => $resource_config_id,
'granularity' => RestResourceConfigInterface::METHOD_GRANULARITY,
'configuration' => [],
]);
}
$configuration = $resource_config
->get('configuration');
if (is_array($format)) {
for ($i = 0; $i < count($format); $i++) {
$configuration[$method]['supported_formats'][] = $format[$i];
}
}
else {
if ($format == NULL) {
$format = $this->defaultFormat;
}
$configuration[$method]['supported_formats'][] = $format;
}
if (!is_array($auth) || empty($auth)) {
$auth = $this->defaultAuth;
}
foreach ($auth as $auth_provider) {
$configuration[$method]['supported_auth'][] = $auth_provider;
}
$resource_config
->set('configuration', $configuration);
$resource_config
->save();
}
else {
foreach ($this->resourceConfigStorage
->loadMultiple() as $resource_config) {
$resource_config
->delete();
}
}
$this
->rebuildCache();
}
protected function rebuildCache() {
$this->container
->get('router.builder')
->rebuildIfNeeded();
}
protected function curlExec($curl_options, $redirect = FALSE) {
unset($this->response);
if (!isset($curl_options[CURLOPT_CUSTOMREQUEST])) {
if (!empty($curl_options[CURLOPT_HTTPGET])) {
$curl_options[CURLOPT_CUSTOMREQUEST] = 'GET';
}
if (!empty($curl_options[CURLOPT_POST])) {
$curl_options[CURLOPT_CUSTOMREQUEST] = 'POST';
}
}
return parent::curlExec($curl_options, $redirect);
}
protected function entityPermissions($entity_type_id, $operation) {
switch ($entity_type_id) {
case 'entity_test':
switch ($operation) {
case 'view':
return [
'view test entity',
];
case 'create':
case 'update':
case 'delete':
return [
'administer entity_test content',
];
}
case 'node':
switch ($operation) {
case 'view':
return [
'access content',
];
case 'create':
return [
'create resttest content',
];
case 'update':
return [
'edit any resttest content',
];
case 'delete':
return [
'delete any resttest content',
];
}
case 'comment':
switch ($operation) {
case 'view':
return [
'access comments',
];
case 'create':
return [
'post comments',
'skip comment approval',
];
case 'update':
return [
'edit own comments',
];
case 'delete':
return [
'administer comments',
];
}
break;
case 'user':
switch ($operation) {
case 'view':
return [
'access user profiles',
];
default:
return [
'administer users',
];
}
default:
if ($this
->isConfigEntity($entity_type_id)) {
$entity_type = \Drupal::entityTypeManager()
->getDefinition($entity_type_id);
if ($admin_permission = $entity_type
->getAdminPermission()) {
return [
$admin_permission,
];
}
}
}
return [];
}
protected function loadEntityFromLocationHeader($location_url) {
$url_parts = explode('/', $location_url);
$id = end($url_parts);
return $this->container
->get('entity_type.manager')
->getStorage($this->testEntityType)
->load($id);
}
protected function removeNodeFieldsForNonAdminUsers(NodeInterface $node) {
$node
->set('status', NULL);
$node
->set('created', NULL);
$node
->set('changed', NULL);
$node
->set('promote', NULL);
$node
->set('sticky', NULL);
$node
->set('revision_timestamp', NULL);
$node
->set('revision_log', NULL);
$node
->set('uid', NULL);
return $node;
}
protected function assertResponseBody($expected, $message = '', $group = 'REST Response') {
return $this
->assertIdentical($expected, $this->responseBody, $message ? $message : strtr('Response body @expected (expected) is equal to @response (actual).', [
'@expected' => var_export($expected, TRUE),
'@response' => var_export($this->responseBody, TRUE),
]), $group);
}
protected function isConfigEntity($entity_type_id) {
return \Drupal::entityTypeManager()
->getDefinition($entity_type_id) instanceof ConfigEntityType;
}
protected function configEntityValues($entity_type_id) {
$entity_type = \Drupal::entityTypeManager()
->getDefinition($entity_type_id);
$keys = $entity_type
->getKeys();
$values = [];
foreach ($keys as $key) {
if ($key === 'id' || $key === 'label') {
$values[$key] = $this
->randomMachineName();
}
}
switch ($entity_type_id) {
case 'block':
$values['plugin'] = 'system_powered_by_block';
break;
}
return $values;
}
}