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' => [
311 'value' => $this->randomString(),
312 'format' => 'plain_text',
318 'id' => $this->randomMachineName(),
319 'label' => 'Test label',
322 return ['title' => $this->randomString(), 'type' => 'resttest'];
326 'name' => $this->randomMachineName(),
329 return ['name' => $this->randomMachineName()];
333 'subject' => $this->randomMachineName(),
334 'entity_type' => 'node',
335 'comment_type' => 'comment',
336 'comment_body' => $this->randomString(),
337 'entity_id' => 'invalid',
338 'field_name' => 'comment',
340 case 'taxonomy_vocabulary':
343 'name' => $this->randomMachineName(),
346 // Block placements depend on themes, ensure Bartik is installed.
347 $this->container->get('theme_installer')->install(['bartik']);
349 'id' => strtolower($this->randomMachineName(8)),
350 'plugin' => 'system_powered_by_block',
352 'region' => 'header',
355 if ($this->isConfigEntity($entity_type_id)) {
356 return $this->configEntityValues($entity_type_id);
363 * Enables the REST service interface for a specific entity type.
365 * @param string|false $resource_type
366 * The resource type that should get REST API enabled or FALSE to disable all
368 * @param string $method
369 * The HTTP method to enable, e.g. GET, POST etc.
370 * @param string|array $format
371 * (Optional) The serialization format, e.g. hal_json, or a list of formats.
373 * (Optional) The list of valid authentication methods.
375 protected function enableService($resource_type, $method = 'GET', $format = NULL, array $auth = []) {
376 if ($resource_type) {
377 // Enable REST API for this entity type.
378 $resource_config_id = str_replace(':', '.', $resource_type);
380 /** @var \Drupal\rest\RestResourceConfigInterface $resource_config */
381 $resource_config = $this->resourceConfigStorage->load($resource_config_id);
382 if (!$resource_config) {
383 $resource_config = $this->resourceConfigStorage->create([
384 'id' => $resource_config_id,
385 'granularity' => RestResourceConfigInterface::METHOD_GRANULARITY,
386 'configuration' => [],
389 $configuration = $resource_config->get('configuration');
391 if (is_array($format)) {
392 for ($i = 0; $i < count($format); $i++) {
393 $configuration[$method]['supported_formats'][] = $format[$i];
397 if ($format == NULL) {
398 $format = $this->defaultFormat;
400 $configuration[$method]['supported_formats'][] = $format;
403 if (!is_array($auth) || empty($auth)) {
404 $auth = $this->defaultAuth;
406 foreach ($auth as $auth_provider) {
407 $configuration[$method]['supported_auth'][] = $auth_provider;
410 $resource_config->set('configuration', $configuration);
411 $resource_config->save();
414 foreach ($this->resourceConfigStorage->loadMultiple() as $resource_config) {
415 $resource_config->delete();
418 $this->rebuildCache();
422 * Rebuilds routing caches.
424 protected function rebuildCache() {
425 $this->container->get('router.builder')->rebuildIfNeeded();
431 * This method is overridden to deal with a cURL quirk: the usage of
432 * CURLOPT_CUSTOMREQUEST cannot be unset on the cURL handle, so we need to
433 * override it every time it is omitted.
435 protected function curlExec($curl_options, $redirect = FALSE) {
436 unset($this->response);
438 if (!isset($curl_options[CURLOPT_CUSTOMREQUEST])) {
439 if (!empty($curl_options[CURLOPT_HTTPGET])) {
440 $curl_options[CURLOPT_CUSTOMREQUEST] = 'GET';
442 if (!empty($curl_options[CURLOPT_POST])) {
443 $curl_options[CURLOPT_CUSTOMREQUEST] = 'POST';
446 return parent::curlExec($curl_options, $redirect);
450 * Provides the necessary user permissions for entity operations.
452 * @param string $entity_type_id
454 * @param string $operation
455 * The operation, one of 'view', 'create', 'update' or 'delete'.
458 * The set of user permission strings.
460 protected function entityPermissions($entity_type_id, $operation) {
461 switch ($entity_type_id) {
463 switch ($operation) {
465 return ['view test entity'];
469 return ['administer entity_test content'];
472 switch ($operation) {
474 return ['access content'];
476 return ['create resttest content'];
478 return ['edit any resttest content'];
480 return ['delete any resttest content'];
484 switch ($operation) {
486 return ['access comments'];
489 return ['post comments', 'skip comment approval'];
492 return ['edit own comments'];
495 return ['administer comments'];
500 switch ($operation) {
502 return ['access user profiles'];
505 return ['administer users'];
509 if ($this->isConfigEntity($entity_type_id)) {
510 $entity_type = \Drupal::entityTypeManager()->getDefinition($entity_type_id);
511 if ($admin_permission = $entity_type->getAdminPermission()) {
512 return [$admin_permission];
520 * Loads an entity based on the location URL returned in the location header.
522 * @param string $location_url
523 * The URL returned in the Location header.
525 * @return \Drupal\Core\Entity\Entity|false
526 * The entity or FALSE if there is no matching entity.
528 protected function loadEntityFromLocationHeader($location_url) {
529 $url_parts = explode('/', $location_url);
530 $id = end($url_parts);
531 return $this->container->get('entity_type.manager')
532 ->getStorage($this->testEntityType)->load($id);
536 * Remove node fields that can only be written by an admin user.
538 * @param \Drupal\node\NodeInterface $node
539 * The node to remove fields where non-administrative users cannot write.
541 * @return \Drupal\node\NodeInterface
542 * The node with removed fields.
544 protected function removeNodeFieldsForNonAdminUsers(NodeInterface $node) {
545 $node->set('status', NULL);
546 $node->set('created', NULL);
547 $node->set('changed', NULL);
548 $node->set('promote', NULL);
549 $node->set('sticky', NULL);
550 $node->set('revision_timestamp', NULL);
551 $node->set('revision_log', NULL);
552 $node->set('uid', NULL);
558 * Check to see if the HTTP request response body is identical to the expected
562 * The first value to check.
564 * (optional) A message to display with the assertion. Do not translate
565 * messages: use \Drupal\Component\Render\FormattableMarkup to embed
566 * variables in the message text, not t(). If left blank, a default message
569 * (optional) The group this message is in, which is displayed in a column
570 * in test output. Use 'Debug' to indicate this is debugging output. Do not
571 * translate this string. Defaults to 'Other'; most tests do not override
575 * TRUE if the assertion succeeded, FALSE otherwise.
577 protected function assertResponseBody($expected, $message = '', $group = 'REST Response') {
578 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);
582 * Checks if an entity type id is for a Config Entity.
584 * @param string $entity_type_id
585 * The entity type ID to check.
588 * TRUE if the entity is a Config Entity, FALSE otherwise.
590 protected function isConfigEntity($entity_type_id) {
591 return \Drupal::entityTypeManager()->getDefinition($entity_type_id) instanceof ConfigEntityType;
595 * Provides an array of suitable property values for a config entity type.
597 * Config entities have some common keys that need to be created. Required
598 * properties differ among config entity types, so we keep a minimum mapping
601 * @param string $entity_type_id
602 * The ID of the type of entity that should be created.
605 * An array of values keyed by property name.
607 protected function configEntityValues($entity_type_id) {
608 $entity_type = \Drupal::entityTypeManager()->getDefinition($entity_type_id);
609 $keys = $entity_type->getKeys();
611 // Fill out known key values that are shared across entity types.
612 foreach ($keys as $key) {
613 if ($key === 'id' || $key === 'label') {
614 $values[$key] = $this->randomMachineName();
617 // Add extra values for particular entity types.
618 switch ($entity_type_id) {
620 $values['plugin'] = 'system_powered_by_block';