3 namespace Drupal\Tests\rest\Functional;
5 use Behat\Mink\Driver\BrowserKitDriver;
7 use Drupal\rest\RestResourceConfigInterface;
8 use Drupal\Tests\BrowserTestBase;
9 use Drupal\user\Entity\Role;
10 use Drupal\user\RoleInterface;
11 use GuzzleHttp\RequestOptions;
12 use Psr\Http\Message\ResponseInterface;
15 * Subclass this for every REST resource, every format and every auth provider.
17 * For more guidance see
18 * \Drupal\Tests\rest\Functional\EntityResource\EntityResourceTestBase
19 * which has recommendations for testing the
20 * \Drupal\rest\Plugin\rest\resource\EntityResource REST resource for every
21 * format and every auth provider. It's a special case (because that single REST
22 * resource generates supports not just one thing, but many things — multiple
23 * entity types), but the same principles apply.
25 abstract class ResourceTestBase extends BrowserTestBase {
28 * The format to use in this test.
30 * A format is the combination of a certain normalizer and a certain
33 * @see https://www.drupal.org/developing/api/8/serialization
35 * (The default is 'json' because that doesn't depend on any module.)
39 protected static $format = 'json';
42 * The MIME type that corresponds to $format.
44 * (Sadly this cannot be computed automatically yet.)
48 protected static $mimeType = 'application/json';
51 * The authentication mechanism to use in this test.
53 * (The default is 'cookie' because that doesn't depend on any module.)
57 protected static $auth = FALSE;
60 * The REST Resource Config entity ID under test (i.e. a resource type).
62 * The REST Resource plugin ID can be calculated from this.
66 * @see \Drupal\rest\Entity\RestResourceConfig::__construct()
68 protected static $resourceConfigId = NULL;
71 * The account to use for authentication, if any.
73 * @var null|\Drupal\Core\Session\AccountInterface
75 protected $account = NULL;
78 * The REST resource config entity storage.
80 * @var \Drupal\Core\Entity\EntityStorageInterface
82 protected $resourceConfigStorage;
85 * The serializer service.
87 * @var \Symfony\Component\Serializer\Serializer
89 protected $serializer;
96 public static $modules = ['rest'];
101 public function setUp() {
104 $this->serializer = $this->container->get('serializer');
106 // Ensure the anonymous user role has no permissions at all.
107 $user_role = Role::load(RoleInterface::ANONYMOUS_ID);
108 foreach ($user_role->getPermissions() as $permission) {
109 $user_role->revokePermission($permission);
112 assert([] === $user_role->getPermissions(), 'The anonymous user role has no permissions at all.');
114 if (static::$auth !== FALSE) {
115 // Ensure the authenticated user role has no permissions at all.
116 $user_role = Role::load(RoleInterface::AUTHENTICATED_ID);
117 foreach ($user_role->getPermissions() as $permission) {
118 $user_role->revokePermission($permission);
121 assert([] === $user_role->getPermissions(), 'The authenticated user role has no permissions at all.');
123 // Create an account.
124 $this->account = $this->createUser();
127 // Otherwise, also create an account, so that any test involving User
128 // entities will have the same user IDs regardless of authentication.
132 $this->resourceConfigStorage = $this->container->get('entity_type.manager')->getStorage('rest_resource_config');
134 // Ensure there's a clean slate: delete all REST resource config entities.
135 $this->resourceConfigStorage->delete($this->resourceConfigStorage->loadMultiple());
136 $this->refreshTestStateAfterRestConfigChange();
140 * Provisions the REST resource under test.
142 * @param string[] $formats
143 * The allowed formats for this resource.
144 * @param string[] $authentication
145 * The allowed authentication providers for this resource.
147 protected function provisionResource($formats = [], $authentication = []) {
148 $this->resourceConfigStorage->create([
149 'id' => static::$resourceConfigId,
150 'granularity' => RestResourceConfigInterface::RESOURCE_GRANULARITY,
152 'methods' => ['GET', 'POST', 'PATCH', 'DELETE'],
153 'formats' => $formats,
154 'authentication' => $authentication,
158 $this->refreshTestStateAfterRestConfigChange();
162 * Refreshes the state of the tester to be in sync with the testee.
164 * Should be called after every change made to:
165 * - RestResourceConfig entities
166 * - the 'rest.settings' simple configuration
168 protected function refreshTestStateAfterRestConfigChange() {
169 // Ensure that the cache tags invalidator has its internal values reset.
170 // Otherwise the http_response cache tag invalidation won't work.
171 $this->refreshVariables();
173 // Tests using this base class may trigger route rebuilds due to changes to
174 // RestResourceConfig entities or 'rest.settings'. Ensure the test generates
175 // routes using an up-to-date router.
176 \Drupal::service('router.builder')->rebuildIfNeeded();
180 * Return the expected error message.
182 * @param string $method
183 * The HTTP method (GET, POST, PATCH, DELETE).
188 protected function getExpectedUnauthorizedAccessMessage($method) {
189 $resource_plugin_id = str_replace('.', ':', static::$resourceConfigId);
190 $permission = 'restful ' . strtolower($method) . ' ' . $resource_plugin_id;
191 return "The '$permission' permission is required.";
195 * Sets up the necessary authorization.
197 * In case of a test verifying publicly accessible REST resources: grant
198 * permissions to the anonymous user role.
200 * In case of a test verifying behavior when using a particular authentication
201 * provider: create a user with a particular set of permissions.
203 * Because of the $method parameter, it's possible to first set up
204 * authentication for only GET, then add POST, et cetera. This then also
205 * allows for verifying a 403 in case of missing authorization.
207 * @param string $method
208 * The HTTP method for which to set up authentication.
210 * @see ::grantPermissionsToAnonymousRole()
211 * @see ::grantPermissionsToAuthenticatedRole()
213 abstract protected function setUpAuthorization($method);
216 * Verifies the error response in case of missing authentication.
218 * @param string $method
220 * @param \Psr\Http\Message\ResponseInterface $response
221 * The response to assert.
223 abstract protected function assertResponseWhenMissingAuthentication($method, ResponseInterface $response);
226 * Asserts normalization-specific edge cases.
228 * (Should be called before sending a well-formed request.)
230 * @see \GuzzleHttp\ClientInterface::request()
232 * @param string $method
234 * @param \Drupal\Core\Url $url
236 * @param array $request_options
237 * Request options to apply.
239 abstract protected function assertNormalizationEdgeCases($method, Url $url, array $request_options);
242 * Asserts authentication provider-specific edge cases.
244 * (Should be called before sending a well-formed request.)
246 * @see \GuzzleHttp\ClientInterface::request()
248 * @param string $method
250 * @param \Drupal\Core\Url $url
252 * @param array $request_options
253 * Request options to apply.
255 abstract protected function assertAuthenticationEdgeCases($method, Url $url, array $request_options);
258 * Returns the expected cacheability of an unauthorized access response.
260 * @return \Drupal\Core\Cache\RefinableCacheableDependencyInterface
261 * The expected cacheability.
263 abstract protected function getExpectedUnauthorizedAccessCacheability();
266 * Initializes authentication.
268 * E.g. for cookie authentication, we first need to get a cookie.
270 protected function initAuthentication() {}
273 * Returns Guzzle request options for authentication.
275 * @param string $method
276 * The HTTP method for this authenticated request.
279 * Guzzle request options to use for authentication.
281 * @see \GuzzleHttp\ClientInterface::request()
283 protected function getAuthenticationRequestOptions($method) {
288 * Grants permissions to the anonymous role.
290 * @param string[] $permissions
291 * Permissions to grant.
293 protected function grantPermissionsToAnonymousRole(array $permissions) {
294 $this->grantPermissions(Role::load(RoleInterface::ANONYMOUS_ID), $permissions);
298 * Grants permissions to the authenticated role.
300 * @param string[] $permissions
301 * Permissions to grant.
303 protected function grantPermissionsToAuthenticatedRole(array $permissions) {
304 $this->grantPermissions(Role::load(RoleInterface::AUTHENTICATED_ID), $permissions);
308 * Grants permissions to the tested role: anonymous or authenticated.
310 * @param string[] $permissions
311 * Permissions to grant.
313 * @see ::grantPermissionsToAuthenticatedRole()
314 * @see ::grantPermissionsToAnonymousRole()
316 protected function grantPermissionsToTestedRole(array $permissions) {
318 $this->grantPermissionsToAuthenticatedRole($permissions);
321 $this->grantPermissionsToAnonymousRole($permissions);
326 * Performs a HTTP request. Wraps the Guzzle HTTP client.
328 * Why wrap the Guzzle HTTP client? Because we want to keep the actual test
329 * code as simple as possible, and hence not require them to specify the
330 * 'http_errors = FALSE' request option, nor do we want them to have to
331 * convert Drupal Url objects to strings.
333 * We also don't want to follow redirects automatically, to ensure these tests
334 * are able to detect when redirects are added or removed.
336 * @see \GuzzleHttp\ClientInterface::request()
338 * @param string $method
340 * @param \Drupal\Core\Url $url
342 * @param array $request_options
343 * Request options to apply.
345 * @return \Psr\Http\Message\ResponseInterface
347 protected function request($method, Url $url, array $request_options) {
348 $request_options[RequestOptions::HTTP_ERRORS] = FALSE;
349 $request_options[RequestOptions::ALLOW_REDIRECTS] = FALSE;
350 $request_options = $this->decorateWithXdebugCookie($request_options);
351 $client = $this->getSession()->getDriver()->getClient()->getClient();
352 return $client->request($method, $url->setAbsolute(TRUE)->toString(), $request_options);
356 * Asserts that a resource response has the given status code and body.
358 * @param int $expected_status_code
359 * The expected response status.
360 * @param string|false $expected_body
361 * The expected response body. FALSE in case this should not be asserted.
362 * @param \Psr\Http\Message\ResponseInterface $response
363 * The response to assert.
364 * @param string[]|false $expected_cache_tags
365 * (optional) The expected cache tags in the X-Drupal-Cache-Tags response
366 * header, or FALSE if that header should be absent. Defaults to FALSE.
367 * @param string[]|false $expected_cache_contexts
368 * (optional) The expected cache contexts in the X-Drupal-Cache-Contexts
369 * response header, or FALSE if that header should be absent. Defaults to
371 * @param string|false $expected_page_cache_header_value
372 * (optional) The expected X-Drupal-Cache response header value, or FALSE if
373 * that header should be absent. Possible strings: 'MISS', 'HIT'. Defaults
375 * @param string|false $expected_dynamic_page_cache_header_value
376 * (optional) The expected X-Drupal-Dynamic-Cache response header value, or
377 * FALSE if that header should be absent. Possible strings: 'MISS', 'HIT'.
380 protected function assertResourceResponse($expected_status_code, $expected_body, ResponseInterface $response, $expected_cache_tags = FALSE, $expected_cache_contexts = FALSE, $expected_page_cache_header_value = FALSE, $expected_dynamic_page_cache_header_value = FALSE) {
381 $this->assertSame($expected_status_code, $response->getStatusCode());
382 if ($expected_status_code === 204) {
383 // DELETE responses should not include a Content-Type header. But Apache
384 // sets it to 'text/html' by default. We also cannot detect the presence
385 // of Apache either here in the CLI. For now having this documented here
387 // $this->assertSame(FALSE, $response->hasHeader('Content-Type'));
388 $this->assertSame('', (string) $response->getBody());
391 $this->assertSame([static::$mimeType], $response->getHeader('Content-Type'));
392 if ($expected_body !== FALSE) {
393 $this->assertSame($expected_body, (string) $response->getBody());
397 // Expected cache tags: X-Drupal-Cache-Tags header.
398 $this->assertSame($expected_cache_tags !== FALSE, $response->hasHeader('X-Drupal-Cache-Tags'));
399 if (is_array($expected_cache_tags)) {
400 $this->assertSame($expected_cache_tags, explode(' ', $response->getHeader('X-Drupal-Cache-Tags')[0]));
403 // Expected cache contexts: X-Drupal-Cache-Contexts header.
404 $this->assertSame($expected_cache_contexts !== FALSE, $response->hasHeader('X-Drupal-Cache-Contexts'));
405 if (is_array($expected_cache_contexts)) {
406 $this->assertSame($expected_cache_contexts, explode(' ', $response->getHeader('X-Drupal-Cache-Contexts')[0]));
409 // Expected Page Cache header value: X-Drupal-Cache header.
410 if ($expected_page_cache_header_value !== FALSE) {
411 $this->assertTrue($response->hasHeader('X-Drupal-Cache'));
412 $this->assertSame($expected_page_cache_header_value, $response->getHeader('X-Drupal-Cache')[0]);
415 $this->assertFalse($response->hasHeader('X-Drupal-Cache'));
418 // Expected Dynamic Page Cache header value: X-Drupal-Dynamic-Cache header.
419 if ($expected_dynamic_page_cache_header_value !== FALSE) {
420 $this->assertTrue($response->hasHeader('X-Drupal-Dynamic-Cache'));
421 $this->assertSame($expected_dynamic_page_cache_header_value, $response->getHeader('X-Drupal-Dynamic-Cache')[0]);
424 $this->assertFalse($response->hasHeader('X-Drupal-Dynamic-Cache'));
429 * Asserts that a resource error response has the given message.
431 * @param int $expected_status_code
432 * The expected response status.
433 * @param string $expected_message
434 * The expected error message.
435 * @param \Psr\Http\Message\ResponseInterface $response
436 * The error response to assert.
437 * @param string[]|false $expected_cache_tags
438 * (optional) The expected cache tags in the X-Drupal-Cache-Tags response
439 * header, or FALSE if that header should be absent. Defaults to FALSE.
440 * @param string[]|false $expected_cache_contexts
441 * (optional) The expected cache contexts in the X-Drupal-Cache-Contexts
442 * response header, or FALSE if that header should be absent. Defaults to
444 * @param string|false $expected_page_cache_header_value
445 * (optional) The expected X-Drupal-Cache response header value, or FALSE if
446 * that header should be absent. Possible strings: 'MISS', 'HIT'. Defaults
448 * @param string|false $expected_dynamic_page_cache_header_value
449 * (optional) The expected X-Drupal-Dynamic-Cache response header value, or
450 * FALSE if that header should be absent. Possible strings: 'MISS', 'HIT'.
453 protected function assertResourceErrorResponse($expected_status_code, $expected_message, ResponseInterface $response, $expected_cache_tags = FALSE, $expected_cache_contexts = FALSE, $expected_page_cache_header_value = FALSE, $expected_dynamic_page_cache_header_value = FALSE) {
454 $expected_body = ($expected_message !== FALSE) ? $this->serializer->encode(['message' => $expected_message], static::$format) : FALSE;
455 $this->assertResourceResponse($expected_status_code, $expected_body, $response, $expected_cache_tags, $expected_cache_contexts, $expected_page_cache_header_value, $expected_dynamic_page_cache_header_value);
459 * Adds the Xdebug cookie to the request options.
461 * @param array $request_options
462 * The request options.
465 * Request options updated with the Xdebug cookie if present.
467 protected function decorateWithXdebugCookie(array $request_options) {
468 $session = $this->getSession();
469 $driver = $session->getDriver();
470 if ($driver instanceof BrowserKitDriver) {
471 $client = $driver->getClient();
472 foreach ($client->getCookieJar()->all() as $cookie) {
473 if (isset($request_options[RequestOptions::HEADERS]['Cookie'])) {
474 $request_options[RequestOptions::HEADERS]['Cookie'] .= '; ' . $cookie->getName() . '=' . $cookie->getValue();
477 $request_options[RequestOptions::HEADERS]['Cookie'] = $cookie->getName() . '=' . $cookie->getValue();
481 return $request_options;