3 namespace Drupal\rest\Tests;
5 use Drupal\Component\Utility\NestedArray;
6 use Drupal\Core\Config\Entity\ConfigEntityType;
7 use Drupal\node\NodeInterface;
8 use Drupal\rest\RestResourceConfigInterface;
9 use Drupal\simpletest\WebTestBase;
10 use GuzzleHttp\Cookie\FileCookieJar;
11 use GuzzleHttp\Cookie\SetCookie;
14 * Test helper class that provides a REST client method to send HTTP requests.
16 * @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.
18 abstract class RESTTestBase extends WebTestBase {
21 * The REST resource config storage.
23 * @var \Drupal\Core\Entity\EntityStorageInterface
25 protected $resourceConfigStorage;
28 * The default serialization format to use for testing REST operations.
32 protected $defaultFormat;
35 * The default MIME type to use for testing REST operations.
39 protected $defaultMimeType;
42 * The entity type to use for testing.
46 protected $testEntityType = 'entity_test';
49 * The default authentication provider to use for testing REST operations.
53 protected $defaultAuth;
57 * The raw response body from http request operations.
61 protected $responseBody;
68 public static $modules = ['rest', 'entity_test'];
73 * @var \Psr\Http\Message\ResponseInterface
77 protected function setUp() {
79 $this->defaultFormat = 'hal_json';
80 $this->defaultMimeType = 'application/hal+json';
81 $this->defaultAuth = ['cookie'];
82 $this->resourceConfigStorage = $this->container->get('entity_type.manager')->getStorage('rest_resource_config');
83 // Create a test content type for node testing.
84 if (in_array('node', static::$modules)) {
85 $this->drupalCreateContentType(['name' => 'resttest', 'type' => 'resttest']);
88 $this->cookieFile = $this->publicFilesDirectory . '/cookie.jar';
92 * Calculates cookies used by guzzle later.
94 * @return \GuzzleHttp\Cookie\CookieJarInterface
95 * The used CURL options in guzzle.
97 protected function cookies() {
100 foreach ($this->cookies as $key => $cookie) {
101 $cookies[$key][] = $cookie['value'];
104 $request = \Drupal::request();
105 $cookies = NestedArray::mergeDeep($cookies, $this->extractCookiesFromRequest($request));
107 $cookie_jar = new FileCookieJar($this->cookieFile);
108 foreach ($cookies as $key => $cookie_values) {
109 foreach ($cookie_values as $cookie_value) {
110 // setcookie() sets the value of a cookie to be deleted, when its gonna
112 if ($cookie_value !== 'deleted') {
113 $cookie_jar->setCookie(new SetCookie(['Name' => $key, 'Value' => $cookie_value, 'Domain' => $request->getHost()]));
122 * Helper function to issue a HTTP request with simpletest's cURL.
124 * @param string|\Drupal\Core\Url $url
125 * A Url object or system path.
126 * @param string $method
127 * HTTP method, one of GET, POST, PUT or DELETE.
128 * @param string $body
129 * The body for POST and PUT.
130 * @param string $mime_type
131 * The MIME type of the transmitted content.
132 * @param bool $csrf_token
133 * If NULL, a CSRF token will be retrieved and used. If FALSE, omit the
134 * X-CSRF-Token request header (to simulate developer error). Otherwise, the
135 * passed in value will be used as the value for the X-CSRF-Token request
136 * header (to simulate developer error, by sending an invalid CSRF token).
139 * The content returned from the request.
141 protected function httpRequest($url, $method, $body = NULL, $mime_type = NULL, $csrf_token = NULL) {
142 if (!isset($mime_type)) {
143 $mime_type = $this->defaultMimeType;
145 if (!in_array($method, ['GET', 'HEAD', 'OPTIONS', 'TRACE'])) {
146 // GET the CSRF token first for writing requests.
147 $requested_token = $this->drupalGet('session/token');
150 $client = \Drupal::httpClient();
151 $url = $this->buildUrl($url);
154 'http_errors' => FALSE,
155 'cookies' => $this->cookies(),
157 CURLOPT_HEADERFUNCTION => [&$this, 'curlHeaderCallback'],
164 'Accept' => $mime_type,
167 $response = $client->get($url, $options);
171 $response = $client->head($url, $options);
176 'headers' => $csrf_token !== FALSE ? [
177 'Content-Type' => $mime_type,
178 'X-CSRF-Token' => ($csrf_token === NULL ? $requested_token : $csrf_token),
180 'Content-Type' => $mime_type,
184 $response = $client->post($url, $options);
189 'headers' => $csrf_token !== FALSE ? [
190 'Content-Type' => $mime_type,
191 'X-CSRF-Token' => ($csrf_token === NULL ? $requested_token : $csrf_token),
193 'Content-Type' => $mime_type,
197 $response = $client->put($url, $options);
202 'headers' => $csrf_token !== FALSE ? [
203 'Content-Type' => $mime_type,
204 'X-CSRF-Token' => ($csrf_token === NULL ? $requested_token : $csrf_token),
206 'Content-Type' => $mime_type,
210 $response = $client->patch($url, $options);
215 'headers' => $csrf_token !== FALSE ? [
216 'Content-Type' => $mime_type,
217 'X-CSRF-Token' => ($csrf_token === NULL ? $requested_token : $csrf_token),
220 $response = $client->delete($url, $options);
224 $this->response = $response;
225 $this->responseBody = (string) $response->getBody();
226 $this->setRawContent($this->responseBody);
228 // Ensure that any changes to variables in the other thread are picked up.
229 $this->refreshVariables();
231 $this->verbose($method . ' request to: ' . $url .
232 '<hr />Code: ' . $this->response->getStatusCode() .
233 (isset($options['headers']) ? '<hr />Request headers: ' . nl2br(print_r($options['headers'], TRUE)) : '') .
234 (isset($options['body']) ? '<hr />Request body: ' . nl2br(print_r($options['body'], TRUE)) : '') .
235 '<hr />Response headers: ' . nl2br(print_r($response->getHeaders(), TRUE)) .
236 '<hr />Response body: ' . $this->responseBody);
238 return $this->responseBody;
244 protected function assertResponse($code, $message = '', $group = 'Browser') {
245 if (!isset($this->response)) {
246 return parent::assertResponse($code, $message, $group);
248 return $this->assertEqual($code, $this->response->getStatusCode(), $message ? $message : "HTTP response expected $code, actual {$this->response->getStatusCode()}", $group);
254 protected function drupalGetHeaders($all_requests = FALSE) {
255 if (!isset($this->response)) {
256 return parent::drupalGetHeaders($all_requests);
258 $lowercased_keys = array_map('strtolower', array_keys($this->response->getHeaders()));
259 return array_map(function (array $header) {
260 return implode(', ', $header);
261 }, array_combine($lowercased_keys, array_values($this->response->getHeaders())));
267 protected function drupalGetHeader($name, $all_requests = FALSE) {
268 if (!isset($this->response)) {
269 return parent::drupalGetHeader($name, $all_requests);
271 if ($header = $this->response->getHeader($name)) {
272 return implode(', ', $header);
277 * Creates entity objects based on their types.
279 * @param string $entity_type
280 * The type of the entity that should be created.
282 * @return \Drupal\Core\Entity\EntityInterface
283 * The new entity object.
285 protected function entityCreate($entity_type) {
286 return $this->container->get('entity_type.manager')
287 ->getStorage($entity_type)
288 ->create($this->entityValues($entity_type));
292 * Provides an array of suitable property values for an entity type.
294 * Required properties differ from entity type to entity type, so we keep a
295 * minimum mapping here.
297 * @param string $entity_type_id
298 * The ID of the type of entity that should be created.
301 * An array of values keyed by property name.
303 protected function entityValues($entity_type_id) {
304 switch ($entity_type_id) {
307 'name' => $this->randomMachineName(),
309 'field_test_text' => [0 => [
310 'value' => $this->randomString(),
311 'format' => 'plain_text',
316 'id' => $this->randomMachineName(),
317 'label' => 'Test label',
320 return ['title' => $this->randomString(), 'type' => 'resttest'];
324 'name' => $this->randomMachineName(),
327 return ['name' => $this->randomMachineName()];
331 'subject' => $this->randomMachineName(),
332 'entity_type' => 'node',
333 'comment_type' => 'comment',
334 'comment_body' => $this->randomString(),
335 'entity_id' => 'invalid',
336 'field_name' => 'comment',
338 case 'taxonomy_vocabulary':
341 'name' => $this->randomMachineName(),
344 // Block placements depend on themes, ensure Bartik is installed.
345 $this->container->get('theme_installer')->install(['bartik']);
347 'id' => strtolower($this->randomMachineName(8)),
348 'plugin' => 'system_powered_by_block',
350 'region' => 'header',
353 if ($this->isConfigEntity($entity_type_id)) {
354 return $this->configEntityValues($entity_type_id);
361 * Enables the REST service interface for a specific entity type.
363 * @param string|false $resource_type
364 * The resource type that should get REST API enabled or FALSE to disable all
366 * @param string $method
367 * The HTTP method to enable, e.g. GET, POST etc.
368 * @param string|array $format
369 * (Optional) The serialization format, e.g. hal_json, or a list of formats.
371 * (Optional) The list of valid authentication methods.
373 protected function enableService($resource_type, $method = 'GET', $format = NULL, array $auth = []) {
374 if ($resource_type) {
375 // Enable REST API for this entity type.
376 $resource_config_id = str_replace(':', '.', $resource_type);
378 /** @var \Drupal\rest\RestResourceConfigInterface $resource_config */
379 $resource_config = $this->resourceConfigStorage->load($resource_config_id);
380 if (!$resource_config) {
381 $resource_config = $this->resourceConfigStorage->create([
382 'id' => $resource_config_id,
383 'granularity' => RestResourceConfigInterface::METHOD_GRANULARITY,
384 'configuration' => []
387 $configuration = $resource_config->get('configuration');
389 if (is_array($format)) {
390 for ($i = 0; $i < count($format); $i++) {
391 $configuration[$method]['supported_formats'][] = $format[$i];
395 if ($format == NULL) {
396 $format = $this->defaultFormat;
398 $configuration[$method]['supported_formats'][] = $format;
401 if (!is_array($auth) || empty($auth)) {
402 $auth = $this->defaultAuth;
404 foreach ($auth as $auth_provider) {
405 $configuration[$method]['supported_auth'][] = $auth_provider;
408 $resource_config->set('configuration', $configuration);
409 $resource_config->save();
412 foreach ($this->resourceConfigStorage->loadMultiple() as $resource_config) {
413 $resource_config->delete();
416 $this->rebuildCache();
420 * Rebuilds routing caches.
422 protected function rebuildCache() {
423 $this->container->get('router.builder')->rebuildIfNeeded();
429 * This method is overridden to deal with a cURL quirk: the usage of
430 * CURLOPT_CUSTOMREQUEST cannot be unset on the cURL handle, so we need to
431 * override it every time it is omitted.
433 protected function curlExec($curl_options, $redirect = FALSE) {
434 unset($this->response);
436 if (!isset($curl_options[CURLOPT_CUSTOMREQUEST])) {
437 if (!empty($curl_options[CURLOPT_HTTPGET])) {
438 $curl_options[CURLOPT_CUSTOMREQUEST] = 'GET';
440 if (!empty($curl_options[CURLOPT_POST])) {
441 $curl_options[CURLOPT_CUSTOMREQUEST] = 'POST';
444 return parent::curlExec($curl_options, $redirect);
448 * Provides the necessary user permissions for entity operations.
450 * @param string $entity_type_id
452 * @param string $operation
453 * The operation, one of 'view', 'create', 'update' or 'delete'.
456 * The set of user permission strings.
458 protected function entityPermissions($entity_type_id, $operation) {
459 switch ($entity_type_id) {
461 switch ($operation) {
463 return ['view test entity'];
467 return ['administer entity_test content'];
470 switch ($operation) {
472 return ['access content'];
474 return ['create resttest content'];
476 return ['edit any resttest content'];
478 return ['delete any resttest content'];
482 switch ($operation) {
484 return ['access comments'];
487 return ['post comments', 'skip comment approval'];
490 return ['edit own comments'];
493 return ['administer comments'];
498 switch ($operation) {
500 return ['access user profiles'];
503 return ['administer users'];
507 if ($this->isConfigEntity($entity_type_id)) {
508 $entity_type = \Drupal::entityTypeManager()->getDefinition($entity_type_id);
509 if ($admin_permission = $entity_type->getAdminPermission()) {
510 return [$admin_permission];
518 * Loads an entity based on the location URL returned in the location header.
520 * @param string $location_url
521 * The URL returned in the Location header.
523 * @return \Drupal\Core\Entity\Entity|false
524 * The entity or FALSE if there is no matching entity.
526 protected function loadEntityFromLocationHeader($location_url) {
527 $url_parts = explode('/', $location_url);
528 $id = end($url_parts);
529 return $this->container->get('entity_type.manager')
530 ->getStorage($this->testEntityType)->load($id);
534 * Remove node fields that can only be written by an admin user.
536 * @param \Drupal\node\NodeInterface $node
537 * The node to remove fields where non-administrative users cannot write.
539 * @return \Drupal\node\NodeInterface
540 * The node with removed fields.
542 protected function removeNodeFieldsForNonAdminUsers(NodeInterface $node) {
543 $node->set('status', NULL);
544 $node->set('created', NULL);
545 $node->set('changed', NULL);
546 $node->set('promote', NULL);
547 $node->set('sticky', NULL);
548 $node->set('revision_timestamp', NULL);
549 $node->set('revision_log', NULL);
550 $node->set('uid', NULL);
556 * Check to see if the HTTP request response body is identical to the expected
560 * The first value to check.
562 * (optional) A message to display with the assertion. Do not translate
563 * messages: use \Drupal\Component\Utility\SafeMarkup::format() to embed
564 * variables in the message text, not t(). If left blank, a default message
567 * (optional) The group this message is in, which is displayed in a column
568 * in test output. Use 'Debug' to indicate this is debugging output. Do not
569 * translate this string. Defaults to 'Other'; most tests do not override
573 * TRUE if the assertion succeeded, FALSE otherwise.
575 protected function assertResponseBody($expected, $message = '', $group = 'REST Response') {
576 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);
580 * Checks if an entity type id is for a Config Entity.
582 * @param string $entity_type_id
583 * The entity type ID to check.
586 * TRUE if the entity is a Config Entity, FALSE otherwise.
588 protected function isConfigEntity($entity_type_id) {
589 return \Drupal::entityTypeManager()->getDefinition($entity_type_id) instanceof ConfigEntityType;
593 * Provides an array of suitable property values for a config entity type.
595 * Config entities have some common keys that need to be created. Required
596 * properties differ among config entity types, so we keep a minimum mapping
599 * @param string $entity_type_id
600 * The ID of the type of entity that should be created.
603 * An array of values keyed by property name.
605 protected function configEntityValues($entity_type_id) {
606 $entity_type = \Drupal::entityTypeManager()->getDefinition($entity_type_id);
607 $keys = $entity_type->getKeys();
609 // Fill out known key values that are shared across entity types.
610 foreach ($keys as $key) {
611 if ($key === 'id' || $key === 'label') {
612 $values[$key] = $this->randomMachineName();
615 // Add extra values for particular entity types.
616 switch ($entity_type_id) {
618 $values['plugin'] = 'system_powered_by_block';