Updated Drupal to 8.6. This goes with the following updates because it's possible...
[yaffs-website] / web / core / modules / rest / src / Tests / RESTTestBase.php
1 <?php
2
3 namespace Drupal\rest\Tests;
4
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;
12
13 /**
14  * Test helper class that provides a REST client method to send HTTP requests.
15  *
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.
17  */
18 abstract class RESTTestBase extends WebTestBase {
19
20   /**
21    * The REST resource config storage.
22    *
23    * @var \Drupal\Core\Entity\EntityStorageInterface
24    */
25   protected $resourceConfigStorage;
26
27   /**
28    * The default serialization format to use for testing REST operations.
29    *
30    * @var string
31    */
32   protected $defaultFormat;
33
34   /**
35    * The default MIME type to use for testing REST operations.
36    *
37    * @var string
38    */
39   protected $defaultMimeType;
40
41   /**
42    * The entity type to use for testing.
43    *
44    * @var string
45    */
46   protected $testEntityType = 'entity_test';
47
48   /**
49    * The default authentication provider to use for testing REST operations.
50    *
51    * @var array
52    */
53   protected $defaultAuth;
54
55
56   /**
57    * The raw response body from http request operations.
58    *
59    * @var array
60    */
61   protected $responseBody;
62
63   /**
64    * Modules to install.
65    *
66    * @var array
67    */
68   public static $modules = ['rest', 'entity_test'];
69
70   /**
71    * The last response.
72    *
73    * @var \Psr\Http\Message\ResponseInterface
74    */
75   protected $response;
76
77   protected function setUp() {
78     parent::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']);
86     }
87
88     $this->cookieFile = $this->publicFilesDirectory . '/cookie.jar';
89   }
90
91   /**
92    * Calculates cookies used by guzzle later.
93    *
94    * @return \GuzzleHttp\Cookie\CookieJarInterface
95    *   The used CURL options in guzzle.
96    */
97   protected function cookies() {
98     $cookies = [];
99
100     foreach ($this->cookies as $key => $cookie) {
101       $cookies[$key][] = $cookie['value'];
102     }
103
104     $request = \Drupal::request();
105     $cookies = NestedArray::mergeDeep($cookies, $this->extractCookiesFromRequest($request));
106
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
111         // be removed.
112         if ($cookie_value !== 'deleted') {
113           $cookie_jar->setCookie(new SetCookie(['Name' => $key, 'Value' => $cookie_value, 'Domain' => $request->getHost()]));
114         }
115       }
116     }
117
118     return $cookie_jar;
119   }
120
121   /**
122    * Helper function to issue a HTTP request with simpletest's cURL.
123    *
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).
137    *
138    * @return string
139    *   The content returned from the request.
140    */
141   protected function httpRequest($url, $method, $body = NULL, $mime_type = NULL, $csrf_token = NULL) {
142     if (!isset($mime_type)) {
143       $mime_type = $this->defaultMimeType;
144     }
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');
148     }
149
150     $client = \Drupal::httpClient();
151     $url = $this->buildUrl($url);
152
153     $options = [
154       'http_errors' => FALSE,
155       'cookies' => $this->cookies(),
156       'curl' => [
157         CURLOPT_HEADERFUNCTION => [&$this, 'curlHeaderCallback'],
158       ],
159     ];
160     switch ($method) {
161       case 'GET':
162         $options += [
163           'headers' => [
164             'Accept' => $mime_type,
165           ],
166         ];
167         $response = $client->get($url, $options);
168         break;
169
170       case 'HEAD':
171         $response = $client->head($url, $options);
172         break;
173
174       case 'POST':
175         $options += [
176           'headers' => $csrf_token !== FALSE ? [
177             'Content-Type' => $mime_type,
178             'X-CSRF-Token' => ($csrf_token === NULL ? $requested_token : $csrf_token),
179           ] : [
180             'Content-Type' => $mime_type,
181           ],
182           'body' => $body,
183         ];
184         $response = $client->post($url, $options);
185         break;
186
187       case 'PUT':
188         $options += [
189           'headers' => $csrf_token !== FALSE ? [
190             'Content-Type' => $mime_type,
191             'X-CSRF-Token' => ($csrf_token === NULL ? $requested_token : $csrf_token),
192           ] : [
193             'Content-Type' => $mime_type,
194           ],
195           'body' => $body,
196         ];
197         $response = $client->put($url, $options);
198         break;
199
200       case 'PATCH':
201         $options += [
202           'headers' => $csrf_token !== FALSE ? [
203             'Content-Type' => $mime_type,
204             'X-CSRF-Token' => ($csrf_token === NULL ? $requested_token : $csrf_token),
205           ] : [
206             'Content-Type' => $mime_type,
207           ],
208           'body' => $body,
209         ];
210         $response = $client->patch($url, $options);
211         break;
212
213       case 'DELETE':
214         $options += [
215           'headers' => $csrf_token !== FALSE ? [
216             'Content-Type' => $mime_type,
217             'X-CSRF-Token' => ($csrf_token === NULL ? $requested_token : $csrf_token),
218           ] : [],
219         ];
220         $response = $client->delete($url, $options);
221         break;
222     }
223
224     $this->response = $response;
225     $this->responseBody = (string) $response->getBody();
226     $this->setRawContent($this->responseBody);
227
228     // Ensure that any changes to variables in the other thread are picked up.
229     $this->refreshVariables();
230
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);
237
238     return $this->responseBody;
239   }
240
241   /**
242    * {@inheritdoc}
243    */
244   protected function assertResponse($code, $message = '', $group = 'Browser') {
245     if (!isset($this->response)) {
246       return parent::assertResponse($code, $message, $group);
247     }
248     return $this->assertEqual($code, $this->response->getStatusCode(), $message ? $message : "HTTP response expected $code, actual {$this->response->getStatusCode()}", $group);
249   }
250
251   /**
252    * {@inheritdoc}
253    */
254   protected function drupalGetHeaders($all_requests = FALSE) {
255     if (!isset($this->response)) {
256       return parent::drupalGetHeaders($all_requests);
257     }
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())));
262   }
263
264   /**
265    * {@inheritdoc}
266    */
267   protected function drupalGetHeader($name, $all_requests = FALSE) {
268     if (!isset($this->response)) {
269       return parent::drupalGetHeader($name, $all_requests);
270     }
271     if ($header = $this->response->getHeader($name)) {
272       return implode(', ', $header);
273     }
274   }
275
276   /**
277    * Creates entity objects based on their types.
278    *
279    * @param string $entity_type
280    *   The type of the entity that should be created.
281    *
282    * @return \Drupal\Core\Entity\EntityInterface
283    *   The new entity object.
284    */
285   protected function entityCreate($entity_type) {
286     return $this->container->get('entity_type.manager')
287       ->getStorage($entity_type)
288       ->create($this->entityValues($entity_type));
289   }
290
291   /**
292    * Provides an array of suitable property values for an entity type.
293    *
294    * Required properties differ from entity type to entity type, so we keep a
295    * minimum mapping here.
296    *
297    * @param string $entity_type_id
298    *   The ID of the type of entity that should be created.
299    *
300    * @return array
301    *   An array of values keyed by property name.
302    */
303   protected function entityValues($entity_type_id) {
304     switch ($entity_type_id) {
305       case 'entity_test':
306         return [
307           'name' => $this->randomMachineName(),
308           'user_id' => 1,
309           'field_test_text' => [
310             0 => [
311               'value' => $this->randomString(),
312               'format' => 'plain_text',
313             ],
314           ],
315         ];
316       case 'config_test':
317         return [
318           'id' => $this->randomMachineName(),
319           'label' => 'Test label',
320         ];
321       case 'node':
322         return ['title' => $this->randomString(), 'type' => 'resttest'];
323       case 'node_type':
324         return [
325           'type' => 'article',
326           'name' => $this->randomMachineName(),
327         ];
328       case 'user':
329         return ['name' => $this->randomMachineName()];
330
331       case 'comment':
332         return [
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',
339         ];
340       case 'taxonomy_vocabulary':
341         return [
342           'vid' => 'tags',
343           'name' => $this->randomMachineName(),
344         ];
345       case 'block':
346         // Block placements depend on themes, ensure Bartik is installed.
347         $this->container->get('theme_installer')->install(['bartik']);
348         return [
349           'id' => strtolower($this->randomMachineName(8)),
350           'plugin' => 'system_powered_by_block',
351           'theme' => 'bartik',
352           'region' => 'header',
353         ];
354       default:
355         if ($this->isConfigEntity($entity_type_id)) {
356           return $this->configEntityValues($entity_type_id);
357         }
358         return [];
359     }
360   }
361
362   /**
363    * Enables the REST service interface for a specific entity type.
364    *
365    * @param string|false $resource_type
366    *   The resource type that should get REST API enabled or FALSE to disable all
367    *   resource types.
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.
372    * @param array $auth
373    *   (Optional) The list of valid authentication methods.
374    */
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);
379       // get entity by id
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' => [],
387         ]);
388       }
389       $configuration = $resource_config->get('configuration');
390
391       if (is_array($format)) {
392         for ($i = 0; $i < count($format); $i++) {
393           $configuration[$method]['supported_formats'][] = $format[$i];
394         }
395       }
396       else {
397         if ($format == NULL) {
398           $format = $this->defaultFormat;
399         }
400         $configuration[$method]['supported_formats'][] = $format;
401       }
402
403       if (!is_array($auth) || empty($auth)) {
404         $auth = $this->defaultAuth;
405       }
406       foreach ($auth as $auth_provider) {
407         $configuration[$method]['supported_auth'][] = $auth_provider;
408       }
409
410       $resource_config->set('configuration', $configuration);
411       $resource_config->save();
412     }
413     else {
414       foreach ($this->resourceConfigStorage->loadMultiple() as $resource_config) {
415         $resource_config->delete();
416       }
417     }
418     $this->rebuildCache();
419   }
420
421   /**
422    * Rebuilds routing caches.
423    */
424   protected function rebuildCache() {
425     $this->container->get('router.builder')->rebuildIfNeeded();
426   }
427
428   /**
429    * {@inheritdoc}
430    *
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.
434    */
435   protected function curlExec($curl_options, $redirect = FALSE) {
436     unset($this->response);
437
438     if (!isset($curl_options[CURLOPT_CUSTOMREQUEST])) {
439       if (!empty($curl_options[CURLOPT_HTTPGET])) {
440         $curl_options[CURLOPT_CUSTOMREQUEST] = 'GET';
441       }
442       if (!empty($curl_options[CURLOPT_POST])) {
443         $curl_options[CURLOPT_CUSTOMREQUEST] = 'POST';
444       }
445     }
446     return parent::curlExec($curl_options, $redirect);
447   }
448
449   /**
450    * Provides the necessary user permissions for entity operations.
451    *
452    * @param string $entity_type_id
453    *   The entity type.
454    * @param string $operation
455    *   The operation, one of 'view', 'create', 'update' or 'delete'.
456    *
457    * @return array
458    *   The set of user permission strings.
459    */
460   protected function entityPermissions($entity_type_id, $operation) {
461     switch ($entity_type_id) {
462       case 'entity_test':
463         switch ($operation) {
464           case 'view':
465             return ['view test entity'];
466           case 'create':
467           case 'update':
468           case 'delete':
469             return ['administer entity_test content'];
470         }
471       case 'node':
472         switch ($operation) {
473           case 'view':
474             return ['access content'];
475           case 'create':
476             return ['create resttest content'];
477           case 'update':
478             return ['edit any resttest content'];
479           case 'delete':
480             return ['delete any resttest content'];
481         }
482
483       case 'comment':
484         switch ($operation) {
485           case 'view':
486             return ['access comments'];
487
488           case 'create':
489             return ['post comments', 'skip comment approval'];
490
491           case 'update':
492             return ['edit own comments'];
493
494           case 'delete':
495             return ['administer comments'];
496         }
497         break;
498
499       case 'user':
500         switch ($operation) {
501           case 'view':
502             return ['access user profiles'];
503
504           default:
505             return ['administer users'];
506         }
507
508       default:
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];
513           }
514         }
515     }
516     return [];
517   }
518
519   /**
520    * Loads an entity based on the location URL returned in the location header.
521    *
522    * @param string $location_url
523    *   The URL returned in the Location header.
524    *
525    * @return \Drupal\Core\Entity\Entity|false
526    *   The entity or FALSE if there is no matching entity.
527    */
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);
533   }
534
535   /**
536    * Remove node fields that can only be written by an admin user.
537    *
538    * @param \Drupal\node\NodeInterface $node
539    *   The node to remove fields where non-administrative users cannot write.
540    *
541    * @return \Drupal\node\NodeInterface
542    *   The node with removed fields.
543    */
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);
553
554     return $node;
555   }
556
557   /**
558    * Check to see if the HTTP request response body is identical to the expected
559    * value.
560    *
561    * @param $expected
562    *   The first value to check.
563    * @param $message
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
567    *   will be displayed.
568    * @param $group
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
572    *   this default.
573    *
574    * @return bool
575    *   TRUE if the assertion succeeded, FALSE otherwise.
576    */
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);
579   }
580
581   /**
582    * Checks if an entity type id is for a Config Entity.
583    *
584    * @param string $entity_type_id
585    *   The entity type ID to check.
586    *
587    * @return bool
588    *   TRUE if the entity is a Config Entity, FALSE otherwise.
589    */
590   protected function isConfigEntity($entity_type_id) {
591     return \Drupal::entityTypeManager()->getDefinition($entity_type_id) instanceof ConfigEntityType;
592   }
593
594   /**
595    * Provides an array of suitable property values for a config entity type.
596    *
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
599    * here.
600    *
601    * @param string $entity_type_id
602    *   The ID of the type of entity that should be created.
603    *
604    * @return array
605    *   An array of values keyed by property name.
606    */
607   protected function configEntityValues($entity_type_id) {
608     $entity_type = \Drupal::entityTypeManager()->getDefinition($entity_type_id);
609     $keys = $entity_type->getKeys();
610     $values = [];
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();
615       }
616     }
617     // Add extra values for particular entity types.
618     switch ($entity_type_id) {
619       case 'block':
620         $values['plugin'] = 'system_powered_by_block';
621         break;
622     }
623     return $values;
624   }
625
626 }