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 protected static $resourceConfigId = NULL;
69 * The account to use for authentication, if any.
71 * @var null|\Drupal\Core\Session\AccountInterface
73 protected $account = NULL;
76 * The REST resource config entity storage.
78 * @var \Drupal\Core\Entity\EntityStorageInterface
80 protected $resourceConfigStorage;
83 * The serializer service.
85 * @var \Symfony\Component\Serializer\Serializer
87 protected $serializer;
94 public static $modules = ['rest'];
99 public function setUp() {
102 // Ensure the anonymous user role has no permissions at all.
103 $user_role = Role::load(RoleInterface::ANONYMOUS_ID);
104 foreach ($user_role->getPermissions() as $permission) {
105 $user_role->revokePermission($permission);
108 assert('[] === $user_role->getPermissions()', 'The anonymous user role has no permissions at all.');
110 if (static::$auth !== FALSE) {
111 // Ensure the authenticated user role has no permissions at all.
112 $user_role = Role::load(RoleInterface::AUTHENTICATED_ID);
113 foreach ($user_role->getPermissions() as $permission) {
114 $user_role->revokePermission($permission);
117 assert('[] === $user_role->getPermissions()', 'The authenticated user role has no permissions at all.');
119 // Create an account.
120 $this->account = $this->createUser();
123 // Otherwise, also create an account, so that any test involving User
124 // entities will have the same user IDs regardless of authentication.
128 $this->resourceConfigStorage = $this->container->get('entity_type.manager')->getStorage('rest_resource_config');
130 // Ensure there's a clean slate: delete all REST resource config entities.
131 $this->resourceConfigStorage->delete($this->resourceConfigStorage->loadMultiple());
132 $this->refreshTestStateAfterRestConfigChange();
136 * Provisions the REST resource under test.
138 * @param string[] $formats
139 * The allowed formats for this resource.
140 * @param string[] $authentication
141 * The allowed authentication providers for this resource.
143 protected function provisionResource($formats = [], $authentication = []) {
144 $this->resourceConfigStorage->create([
145 'id' => static::$resourceConfigId,
146 'granularity' => RestResourceConfigInterface::RESOURCE_GRANULARITY,
148 'methods' => ['GET', 'POST', 'PATCH', 'DELETE'],
149 'formats' => $formats,
150 'authentication' => $authentication,
154 $this->refreshTestStateAfterRestConfigChange();
158 * Refreshes the state of the tester to be in sync with the testee.
160 * Should be called after every change made to:
161 * - RestResourceConfig entities
162 * - the 'rest.settings' simple configuration
164 protected function refreshTestStateAfterRestConfigChange() {
165 // Ensure that the cache tags invalidator has its internal values reset.
166 // Otherwise the http_response cache tag invalidation won't work.
167 $this->refreshVariables();
169 // Tests using this base class may trigger route rebuilds due to changes to
170 // RestResourceConfig entities or 'rest.settings'. Ensure the test generates
171 // routes using an up-to-date router.
172 \Drupal::service('router.builder')->rebuildIfNeeded();
176 * Sets up the necessary authorization.
178 * In case of a test verifying publicly accessible REST resources: grant
179 * permissions to the anonymous user role.
181 * In case of a test verifying behavior when using a particular authentication
182 * provider: create a user with a particular set of permissions.
184 * Because of the $method parameter, it's possible to first set up
185 * authentication for only GET, then add POST, et cetera. This then also
186 * allows for verifying a 403 in case of missing authorization.
188 * @param string $method
189 * The HTTP method for which to set up authentication.
191 * @see ::grantPermissionsToAnonymousRole()
192 * @see ::grantPermissionsToAuthenticatedRole()
194 abstract protected function setUpAuthorization($method);
197 * Verifies the error response in case of missing authentication.
199 abstract protected function assertResponseWhenMissingAuthentication(ResponseInterface $response);
202 * Asserts normalization-specific edge cases.
204 * (Should be called before sending a well-formed request.)
206 * @see \GuzzleHttp\ClientInterface::request()
208 * @param string $method
210 * @param \Drupal\Core\Url $url
212 * @param array $request_options
213 * Request options to apply.
215 abstract protected function assertNormalizationEdgeCases($method, Url $url, array $request_options);
218 * Asserts authentication provider-specific edge cases.
220 * (Should be called before sending a well-formed request.)
222 * @see \GuzzleHttp\ClientInterface::request()
224 * @param string $method
226 * @param \Drupal\Core\Url $url
228 * @param array $request_options
229 * Request options to apply.
231 abstract protected function assertAuthenticationEdgeCases($method, Url $url, array $request_options);
234 * Return the expected error message.
236 * @param string $method
237 * The HTTP method (GET, POST, PATCH, DELETE).
242 abstract protected function getExpectedUnauthorizedAccessMessage($method);
245 * Return the default expected error message if the
246 * bc_entity_resource_permissions is true.
248 * @param string $method
249 * The HTTP method (GET, POST, PATCH, DELETE).
254 abstract protected function getExpectedBcUnauthorizedAccessMessage($method);
257 * Initializes authentication.
259 * E.g. for cookie authentication, we first need to get a cookie.
261 protected function initAuthentication() {}
264 * Returns Guzzle request options for authentication.
266 * @param string $method
267 * The HTTP method for this authenticated request.
270 * Guzzle request options to use for authentication.
272 * @see \GuzzleHttp\ClientInterface::request()
274 protected function getAuthenticationRequestOptions($method) {
279 * Grants permissions to the anonymous role.
281 * @param string[] $permissions
282 * Permissions to grant.
284 protected function grantPermissionsToAnonymousRole(array $permissions) {
285 $this->grantPermissions(Role::load(RoleInterface::ANONYMOUS_ID), $permissions);
289 * Grants permissions to the authenticated role.
291 * @param string[] $permissions
292 * Permissions to grant.
294 protected function grantPermissionsToAuthenticatedRole(array $permissions) {
295 $this->grantPermissions(Role::load(RoleInterface::AUTHENTICATED_ID), $permissions);
299 * Grants permissions to the tested role: anonymous or authenticated.
301 * @param string[] $permissions
302 * Permissions to grant.
304 * @see ::grantPermissionsToAuthenticatedRole()
305 * @see ::grantPermissionsToAnonymousRole()
307 protected function grantPermissionsToTestedRole(array $permissions) {
309 $this->grantPermissionsToAuthenticatedRole($permissions);
312 $this->grantPermissionsToAnonymousRole($permissions);
317 * Performs a HTTP request. Wraps the Guzzle HTTP client.
319 * Why wrap the Guzzle HTTP client? Because we want to keep the actual test
320 * code as simple as possible, and hence not require them to specify the
321 * 'http_errors = FALSE' request option, nor do we want them to have to
322 * convert Drupal Url objects to strings.
324 * @see \GuzzleHttp\ClientInterface::request()
326 * @param string $method
328 * @param \Drupal\Core\Url $url
330 * @param array $request_options
331 * Request options to apply.
333 * @return \Psr\Http\Message\ResponseInterface
335 protected function request($method, Url $url, array $request_options) {
336 $request_options[RequestOptions::HTTP_ERRORS] = FALSE;
337 $request_options = $this->decorateWithXdebugCookie($request_options);
338 $client = $this->getSession()->getDriver()->getClient()->getClient();
339 return $client->request($method, $url->setAbsolute(TRUE)->toString(), $request_options);
343 * Asserts that a resource response has the given status code and body.
345 * @param int $expected_status_code
346 * The expected response status.
347 * @param string|false $expected_body
348 * The expected response body. FALSE in case this should not be asserted.
349 * @param \Psr\Http\Message\ResponseInterface $response
350 * The response to assert.
352 protected function assertResourceResponse($expected_status_code, $expected_body, ResponseInterface $response) {
353 $this->assertSame($expected_status_code, $response->getStatusCode());
354 if ($expected_status_code < 400) {
355 $this->assertSame([static::$mimeType], $response->getHeader('Content-Type'));
358 $this->assertSame([static::$mimeType], $response->getHeader('Content-Type'));
360 if ($expected_body !== FALSE) {
361 $this->assertSame($expected_body, (string) $response->getBody());
366 * Asserts that a resource error response has the given message.
368 * @param int $expected_status_code
369 * The expected response status.
370 * @param string $expected_message
371 * The expected error message.
372 * @param \Psr\Http\Message\ResponseInterface $response
373 * The error response to assert.
375 protected function assertResourceErrorResponse($expected_status_code, $expected_message, ResponseInterface $response) {
376 $expected_body = ($expected_message !== FALSE) ? $this->serializer->encode(['message' => $expected_message], static::$format) : FALSE;
377 $this->assertResourceResponse($expected_status_code, $expected_body, $response);
381 * Adds the Xdebug cookie to the request options.
383 * @param array $request_options
384 * The request options.
387 * Request options updated with the Xdebug cookie if present.
389 protected function decorateWithXdebugCookie(array $request_options) {
390 $session = $this->getSession();
391 $driver = $session->getDriver();
392 if ($driver instanceof BrowserKitDriver) {
393 $client = $driver->getClient();
394 foreach ($client->getCookieJar()->all() as $cookie) {
395 if (isset($request_options[RequestOptions::HEADERS]['Cookie'])) {
396 $request_options[RequestOptions::HEADERS]['Cookie'] .= '; ' . $cookie->getName() . '=' . $cookie->getValue();
399 $request_options[RequestOptions::HEADERS]['Cookie'] = $cookie->getName() . '=' . $cookie->getValue();
403 return $request_options;