ResourceTestBase.php 12.8 KB
Newer Older
1
2
3
4
<?php

namespace Drupal\Tests\rest\Functional;

5
use Behat\Mink\Driver\BrowserKitDriver;
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
use Drupal\Core\Url;
use Drupal\rest\RestResourceConfigInterface;
use Drupal\Tests\BrowserTestBase;
use Drupal\user\Entity\Role;
use Drupal\user\RoleInterface;
use GuzzleHttp\RequestOptions;
use Psr\Http\Message\ResponseInterface;

/**
 * Subclass this for every REST resource, every format and every auth provider.
 *
 * For more guidance see
 * \Drupal\Tests\rest\Functional\EntityResource\EntityResourceTestBase
 * which has recommendations for testing the
 * \Drupal\rest\Plugin\rest\resource\EntityResource REST resource for every
 * format and every auth provider. It's a special case (because that single REST
 * resource generates supports not just one thing, but many things — multiple
 * entity types), but the same principles apply.
 */
abstract class ResourceTestBase extends BrowserTestBase {

  /**
   * The format to use in this test.
   *
   * A format is the combination of a certain normalizer and a certain
   * serializer.
   *
   * @see https://www.drupal.org/developing/api/8/serialization
   *
   * (The default is 'json' because that doesn't depend on any module.)
   *
   * @var string
   */
  protected static $format = 'json';

  /**
   * The MIME type that corresponds to $format.
   *
   * (Sadly this cannot be computed automatically yet.)
   *
   * @var string
   */
  protected static $mimeType = 'application/json';

  /**
   * The authentication mechanism to use in this test.
   *
   * (The default is 'cookie' because that doesn't depend on any module.)
   *
   * @var string
   */
  protected static $auth = FALSE;

59
60
61
62
63
64
  /**
   * The REST Resource Config entity ID under test (i.e. a resource type).
   *
   * The REST Resource plugin ID can be calculated from this.
   *
   * @var string
65
66
   *
   * @see \Drupal\rest\Entity\RestResourceConfig::__construct()
67
68
69
   */
  protected static $resourceConfigId = NULL;

70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
  /**
   * The account to use for authentication, if any.
   *
   * @var null|\Drupal\Core\Session\AccountInterface
   */
  protected $account = NULL;

  /**
   * The REST resource config entity storage.
   *
   * @var \Drupal\Core\Entity\EntityStorageInterface
   */
  protected $resourceConfigStorage;

  /**
   * The serializer service.
   *
   * @var \Symfony\Component\Serializer\Serializer
   */
  protected $serializer;

  /**
   * Modules to install.
   *
   * @var array
   */
  public static $modules = ['rest'];

  /**
   * {@inheritdoc}
   */
  public function setUp() {
    parent::setUp();

104
105
    $this->serializer = $this->container->get('serializer');

106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
    // Ensure the anonymous user role has no permissions at all.
    $user_role = Role::load(RoleInterface::ANONYMOUS_ID);
    foreach ($user_role->getPermissions() as $permission) {
      $user_role->revokePermission($permission);
    }
    $user_role->save();
    assert('[] === $user_role->getPermissions()', 'The anonymous user role has no permissions at all.');

    if (static::$auth !== FALSE) {
      // Ensure the authenticated user role has no permissions at all.
      $user_role = Role::load(RoleInterface::AUTHENTICATED_ID);
      foreach ($user_role->getPermissions() as $permission) {
        $user_role->revokePermission($permission);
      }
      $user_role->save();
      assert('[] === $user_role->getPermissions()', 'The authenticated user role has no permissions at all.');

      // Create an account.
      $this->account = $this->createUser();
    }
    else {
      // Otherwise, also create an account, so that any test involving User
      // entities will have the same user IDs regardless of authentication.
      $this->createUser();
    }

    $this->resourceConfigStorage = $this->container->get('entity_type.manager')->getStorage('rest_resource_config');

    // Ensure there's a clean slate: delete all REST resource config entities.
    $this->resourceConfigStorage->delete($this->resourceConfigStorage->loadMultiple());
136
    $this->refreshTestStateAfterRestConfigChange();
137
138
139
  }

  /**
140
   * Provisions the REST resource under test.
141
142
143
144
145
146
   *
   * @param string[] $formats
   *   The allowed formats for this resource.
   * @param string[] $authentication
   *   The allowed authentication providers for this resource.
   */
147
  protected function provisionResource($formats = [], $authentication = []) {
148
    $this->resourceConfigStorage->create([
149
      'id' => static::$resourceConfigId,
150
151
152
153
154
      'granularity' => RestResourceConfigInterface::RESOURCE_GRANULARITY,
      'configuration' => [
        'methods' => ['GET', 'POST', 'PATCH', 'DELETE'],
        'formats' => $formats,
        'authentication' => $authentication,
155
156
      ],
      'status' => TRUE,
157
    ])->save();
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
    $this->refreshTestStateAfterRestConfigChange();
  }

  /**
   * Refreshes the state of the tester to be in sync with the testee.
   *
   * Should be called after every change made to:
   * - RestResourceConfig entities
   * - the 'rest.settings' simple configuration
   */
  protected function refreshTestStateAfterRestConfigChange() {
    // Ensure that the cache tags invalidator has its internal values reset.
    // Otherwise the http_response cache tag invalidation won't work.
    $this->refreshVariables();

    // Tests using this base class may trigger route rebuilds due to changes to
    // RestResourceConfig entities or 'rest.settings'. Ensure the test generates
    // routes using an up-to-date router.
    \Drupal::service('router.builder')->rebuildIfNeeded();
177
178
  }

179
180
181
182
183
184
185
  /**
   * Return the expected error message.
   *
   * @param string $method
   *   The HTTP method (GET, POST, PATCH, DELETE).
   *
   * @return string
186
   *   The error string.
187
188
189
190
191
192
193
   */
  protected function getExpectedUnauthorizedAccessMessage($method) {
    $resource_plugin_id = str_replace('.', ':', static::$resourceConfigId);
    $permission = 'restful ' . strtolower($method) . ' ' . $resource_plugin_id;
    return "The '$permission' permission is required.";
  }

194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
  /**
   * Sets up the necessary authorization.
   *
   * In case of a test verifying publicly accessible REST resources: grant
   * permissions to the anonymous user role.
   *
   * In case of a test verifying behavior when using a particular authentication
   * provider: create a user with a particular set of permissions.
   *
   * Because of the $method parameter, it's possible to first set up
   * authentication for only GET, then add POST, et cetera. This then also
   * allows for verifying a 403 in case of missing authorization.
   *
   * @param string $method
   *   The HTTP method for which to set up authentication.
   *
   * @see ::grantPermissionsToAnonymousRole()
   * @see ::grantPermissionsToAuthenticatedRole()
   */
  abstract protected function setUpAuthorization($method);

  /**
   * Verifies the error response in case of missing authentication.
   */
  abstract protected function assertResponseWhenMissingAuthentication(ResponseInterface $response);

  /**
   * Asserts normalization-specific edge cases.
   *
   * (Should be called before sending a well-formed request.)
   *
   * @see \GuzzleHttp\ClientInterface::request()
   *
   * @param string $method
   *   HTTP method.
   * @param \Drupal\Core\Url $url
   *   URL to request.
   * @param array $request_options
   *   Request options to apply.
   */
  abstract protected function assertNormalizationEdgeCases($method, Url $url, array $request_options);

  /**
   * Asserts authentication provider-specific edge cases.
   *
   * (Should be called before sending a well-formed request.)
   *
   * @see \GuzzleHttp\ClientInterface::request()
   *
   * @param string $method
   *   HTTP method.
   * @param \Drupal\Core\Url $url
   *   URL to request.
   * @param array $request_options
   *   Request options to apply.
   */
  abstract protected function assertAuthenticationEdgeCases($method, Url $url, array $request_options);

  /**
   * Initializes authentication.
   *
   * E.g. for cookie authentication, we first need to get a cookie.
   */
  protected function initAuthentication() {}

  /**
   * Returns Guzzle request options for authentication.
   *
   * @param string $method
   *   The HTTP method for this authenticated request.
   *
   * @return array
   *   Guzzle request options to use for authentication.
   *
   * @see \GuzzleHttp\ClientInterface::request()
   */
  protected function getAuthenticationRequestOptions($method) {
    return [];
  }

  /**
   * Grants permissions to the anonymous role.
   *
   * @param string[] $permissions
   *   Permissions to grant.
   */
  protected function grantPermissionsToAnonymousRole(array $permissions) {
    $this->grantPermissions(Role::load(RoleInterface::ANONYMOUS_ID), $permissions);
  }

  /**
   * Grants permissions to the authenticated role.
   *
   * @param string[] $permissions
   *   Permissions to grant.
   */
  protected function grantPermissionsToAuthenticatedRole(array $permissions) {
    $this->grantPermissions(Role::load(RoleInterface::AUTHENTICATED_ID), $permissions);
  }

  /**
   * Grants permissions to the tested role: anonymous or authenticated.
   *
   * @param string[] $permissions
   *   Permissions to grant.
   *
   * @see ::grantPermissionsToAuthenticatedRole()
   * @see ::grantPermissionsToAnonymousRole()
   */
  protected function grantPermissionsToTestedRole(array $permissions) {
    if (static::$auth) {
      $this->grantPermissionsToAuthenticatedRole($permissions);
    }
    else {
      $this->grantPermissionsToAnonymousRole($permissions);
    }
  }

  /**
   * Performs a HTTP request. Wraps the Guzzle HTTP client.
   *
   * Why wrap the Guzzle HTTP client? Because we want to keep the actual test
   * code as simple as possible, and hence not require them to specify the
   * 'http_errors = FALSE' request option, nor do we want them to have to
   * convert Drupal Url objects to strings.
   *
320
321
322
   * We also don't want to follow redirects automatically, to ensure these tests
   * are able to detect when redirects are added or removed.
   *
323
324
325
326
327
328
329
330
331
332
333
334
335
   * @see \GuzzleHttp\ClientInterface::request()
   *
   * @param string $method
   *   HTTP method.
   * @param \Drupal\Core\Url $url
   *   URL to request.
   * @param array $request_options
   *   Request options to apply.
   *
   * @return \Psr\Http\Message\ResponseInterface
   */
  protected function request($method, Url $url, array $request_options) {
    $request_options[RequestOptions::HTTP_ERRORS] = FALSE;
336
    $request_options[RequestOptions::ALLOW_REDIRECTS] = FALSE;
337
    $request_options = $this->decorateWithXdebugCookie($request_options);
338
339
    $client = $this->getSession()->getDriver()->getClient()->getClient();
    return $client->request($method, $url->setAbsolute(TRUE)->toString(), $request_options);
340
341
342
343
344
345
346
347
348
349
350
351
352
353
  }

  /**
   * Asserts that a resource response has the given status code and body.
   *
   * @param int $expected_status_code
   *   The expected response status.
   * @param string|false $expected_body
   *   The expected response body. FALSE in case this should not be asserted.
   * @param \Psr\Http\Message\ResponseInterface $response
   *   The response to assert.
   */
  protected function assertResourceResponse($expected_status_code, $expected_body, ResponseInterface $response) {
    $this->assertSame($expected_status_code, $response->getStatusCode());
354
    $this->assertSame([static::$mimeType], $response->getHeader('Content-Type'));
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
    if ($expected_body !== FALSE) {
      $this->assertSame($expected_body, (string) $response->getBody());
    }
  }

  /**
   * Asserts that a resource error response has the given message.
   *
   * @param int $expected_status_code
   *   The expected response status.
   * @param string $expected_message
   *   The expected error message.
   * @param \Psr\Http\Message\ResponseInterface $response
   *   The error response to assert.
   */
  protected function assertResourceErrorResponse($expected_status_code, $expected_message, ResponseInterface $response) {
371
    $expected_body = ($expected_message !== FALSE) ? $this->serializer->encode(['message' => $expected_message], static::$format) : FALSE;
372
373
374
    $this->assertResourceResponse($expected_status_code, $expected_body, $response);
  }

375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
  /**
   * Adds the Xdebug cookie to the request options.
   *
   * @param array $request_options
   *   The request options.
   *
   * @return array
   *   Request options updated with the Xdebug cookie if present.
   */
  protected function decorateWithXdebugCookie(array $request_options) {
    $session = $this->getSession();
    $driver = $session->getDriver();
    if ($driver instanceof BrowserKitDriver) {
      $client = $driver->getClient();
      foreach ($client->getCookieJar()->all() as $cookie) {
        if (isset($request_options[RequestOptions::HEADERS]['Cookie'])) {
          $request_options[RequestOptions::HEADERS]['Cookie'] .= '; ' . $cookie->getName() . '=' . $cookie->getValue();
        }
        else {
          $request_options[RequestOptions::HEADERS]['Cookie'] = $cookie->getName() . '=' . $cookie->getValue();
        }
      }
    }
    return $request_options;
  }

401
}