annotate core/modules/rest/tests/src/Functional/ResourceTestBase.php @ 12:7a779792577d

Update Drupal core to v8.4.5 (via Composer)
author Chris Cannam
date Fri, 23 Feb 2018 15:52:07 +0000
parents 4c8ae668cc8c
children 1fec387a4317
rev   line source
Chris@0 1 <?php
Chris@0 2
Chris@0 3 namespace Drupal\Tests\rest\Functional;
Chris@0 4
Chris@0 5 use Behat\Mink\Driver\BrowserKitDriver;
Chris@0 6 use Drupal\Core\Url;
Chris@0 7 use Drupal\rest\RestResourceConfigInterface;
Chris@0 8 use Drupal\Tests\BrowserTestBase;
Chris@0 9 use Drupal\user\Entity\Role;
Chris@0 10 use Drupal\user\RoleInterface;
Chris@0 11 use GuzzleHttp\RequestOptions;
Chris@0 12 use Psr\Http\Message\ResponseInterface;
Chris@0 13
Chris@0 14 /**
Chris@0 15 * Subclass this for every REST resource, every format and every auth provider.
Chris@0 16 *
Chris@0 17 * For more guidance see
Chris@0 18 * \Drupal\Tests\rest\Functional\EntityResource\EntityResourceTestBase
Chris@0 19 * which has recommendations for testing the
Chris@0 20 * \Drupal\rest\Plugin\rest\resource\EntityResource REST resource for every
Chris@0 21 * format and every auth provider. It's a special case (because that single REST
Chris@0 22 * resource generates supports not just one thing, but many things — multiple
Chris@0 23 * entity types), but the same principles apply.
Chris@0 24 */
Chris@0 25 abstract class ResourceTestBase extends BrowserTestBase {
Chris@0 26
Chris@0 27 /**
Chris@0 28 * The format to use in this test.
Chris@0 29 *
Chris@0 30 * A format is the combination of a certain normalizer and a certain
Chris@0 31 * serializer.
Chris@0 32 *
Chris@0 33 * @see https://www.drupal.org/developing/api/8/serialization
Chris@0 34 *
Chris@0 35 * (The default is 'json' because that doesn't depend on any module.)
Chris@0 36 *
Chris@0 37 * @var string
Chris@0 38 */
Chris@0 39 protected static $format = 'json';
Chris@0 40
Chris@0 41 /**
Chris@0 42 * The MIME type that corresponds to $format.
Chris@0 43 *
Chris@0 44 * (Sadly this cannot be computed automatically yet.)
Chris@0 45 *
Chris@0 46 * @var string
Chris@0 47 */
Chris@0 48 protected static $mimeType = 'application/json';
Chris@0 49
Chris@0 50 /**
Chris@0 51 * The authentication mechanism to use in this test.
Chris@0 52 *
Chris@0 53 * (The default is 'cookie' because that doesn't depend on any module.)
Chris@0 54 *
Chris@0 55 * @var string
Chris@0 56 */
Chris@0 57 protected static $auth = FALSE;
Chris@0 58
Chris@0 59 /**
Chris@0 60 * The REST Resource Config entity ID under test (i.e. a resource type).
Chris@0 61 *
Chris@0 62 * The REST Resource plugin ID can be calculated from this.
Chris@0 63 *
Chris@0 64 * @var string
Chris@0 65 *
Chris@0 66 * @see \Drupal\rest\Entity\RestResourceConfig::__construct()
Chris@0 67 */
Chris@0 68 protected static $resourceConfigId = NULL;
Chris@0 69
Chris@0 70 /**
Chris@0 71 * The account to use for authentication, if any.
Chris@0 72 *
Chris@0 73 * @var null|\Drupal\Core\Session\AccountInterface
Chris@0 74 */
Chris@0 75 protected $account = NULL;
Chris@0 76
Chris@0 77 /**
Chris@0 78 * The REST resource config entity storage.
Chris@0 79 *
Chris@0 80 * @var \Drupal\Core\Entity\EntityStorageInterface
Chris@0 81 */
Chris@0 82 protected $resourceConfigStorage;
Chris@0 83
Chris@0 84 /**
Chris@0 85 * The serializer service.
Chris@0 86 *
Chris@0 87 * @var \Symfony\Component\Serializer\Serializer
Chris@0 88 */
Chris@0 89 protected $serializer;
Chris@0 90
Chris@0 91 /**
Chris@0 92 * Modules to install.
Chris@0 93 *
Chris@0 94 * @var array
Chris@0 95 */
Chris@0 96 public static $modules = ['rest'];
Chris@0 97
Chris@0 98 /**
Chris@0 99 * {@inheritdoc}
Chris@0 100 */
Chris@0 101 public function setUp() {
Chris@0 102 parent::setUp();
Chris@0 103
Chris@0 104 $this->serializer = $this->container->get('serializer');
Chris@0 105
Chris@0 106 // Ensure the anonymous user role has no permissions at all.
Chris@0 107 $user_role = Role::load(RoleInterface::ANONYMOUS_ID);
Chris@0 108 foreach ($user_role->getPermissions() as $permission) {
Chris@0 109 $user_role->revokePermission($permission);
Chris@0 110 }
Chris@0 111 $user_role->save();
Chris@0 112 assert('[] === $user_role->getPermissions()', 'The anonymous user role has no permissions at all.');
Chris@0 113
Chris@0 114 if (static::$auth !== FALSE) {
Chris@0 115 // Ensure the authenticated user role has no permissions at all.
Chris@0 116 $user_role = Role::load(RoleInterface::AUTHENTICATED_ID);
Chris@0 117 foreach ($user_role->getPermissions() as $permission) {
Chris@0 118 $user_role->revokePermission($permission);
Chris@0 119 }
Chris@0 120 $user_role->save();
Chris@0 121 assert('[] === $user_role->getPermissions()', 'The authenticated user role has no permissions at all.');
Chris@0 122
Chris@0 123 // Create an account.
Chris@0 124 $this->account = $this->createUser();
Chris@0 125 }
Chris@0 126 else {
Chris@0 127 // Otherwise, also create an account, so that any test involving User
Chris@0 128 // entities will have the same user IDs regardless of authentication.
Chris@0 129 $this->createUser();
Chris@0 130 }
Chris@0 131
Chris@0 132 $this->resourceConfigStorage = $this->container->get('entity_type.manager')->getStorage('rest_resource_config');
Chris@0 133
Chris@0 134 // Ensure there's a clean slate: delete all REST resource config entities.
Chris@0 135 $this->resourceConfigStorage->delete($this->resourceConfigStorage->loadMultiple());
Chris@0 136 $this->refreshTestStateAfterRestConfigChange();
Chris@0 137 }
Chris@0 138
Chris@0 139 /**
Chris@0 140 * Provisions the REST resource under test.
Chris@0 141 *
Chris@0 142 * @param string[] $formats
Chris@0 143 * The allowed formats for this resource.
Chris@0 144 * @param string[] $authentication
Chris@0 145 * The allowed authentication providers for this resource.
Chris@0 146 */
Chris@0 147 protected function provisionResource($formats = [], $authentication = []) {
Chris@0 148 $this->resourceConfigStorage->create([
Chris@0 149 'id' => static::$resourceConfigId,
Chris@0 150 'granularity' => RestResourceConfigInterface::RESOURCE_GRANULARITY,
Chris@0 151 'configuration' => [
Chris@0 152 'methods' => ['GET', 'POST', 'PATCH', 'DELETE'],
Chris@0 153 'formats' => $formats,
Chris@0 154 'authentication' => $authentication,
Chris@0 155 ],
Chris@0 156 'status' => TRUE,
Chris@0 157 ])->save();
Chris@0 158 $this->refreshTestStateAfterRestConfigChange();
Chris@0 159 }
Chris@0 160
Chris@0 161 /**
Chris@0 162 * Refreshes the state of the tester to be in sync with the testee.
Chris@0 163 *
Chris@0 164 * Should be called after every change made to:
Chris@0 165 * - RestResourceConfig entities
Chris@0 166 * - the 'rest.settings' simple configuration
Chris@0 167 */
Chris@0 168 protected function refreshTestStateAfterRestConfigChange() {
Chris@0 169 // Ensure that the cache tags invalidator has its internal values reset.
Chris@0 170 // Otherwise the http_response cache tag invalidation won't work.
Chris@0 171 $this->refreshVariables();
Chris@0 172
Chris@0 173 // Tests using this base class may trigger route rebuilds due to changes to
Chris@0 174 // RestResourceConfig entities or 'rest.settings'. Ensure the test generates
Chris@0 175 // routes using an up-to-date router.
Chris@0 176 \Drupal::service('router.builder')->rebuildIfNeeded();
Chris@0 177 }
Chris@0 178
Chris@0 179 /**
Chris@0 180 * Return the expected error message.
Chris@0 181 *
Chris@0 182 * @param string $method
Chris@0 183 * The HTTP method (GET, POST, PATCH, DELETE).
Chris@0 184 *
Chris@0 185 * @return string
Chris@0 186 * The error string.
Chris@0 187 */
Chris@0 188 protected function getExpectedUnauthorizedAccessMessage($method) {
Chris@0 189 $resource_plugin_id = str_replace('.', ':', static::$resourceConfigId);
Chris@0 190 $permission = 'restful ' . strtolower($method) . ' ' . $resource_plugin_id;
Chris@0 191 return "The '$permission' permission is required.";
Chris@0 192 }
Chris@0 193
Chris@0 194 /**
Chris@0 195 * Sets up the necessary authorization.
Chris@0 196 *
Chris@0 197 * In case of a test verifying publicly accessible REST resources: grant
Chris@0 198 * permissions to the anonymous user role.
Chris@0 199 *
Chris@0 200 * In case of a test verifying behavior when using a particular authentication
Chris@0 201 * provider: create a user with a particular set of permissions.
Chris@0 202 *
Chris@0 203 * Because of the $method parameter, it's possible to first set up
Chris@0 204 * authentication for only GET, then add POST, et cetera. This then also
Chris@0 205 * allows for verifying a 403 in case of missing authorization.
Chris@0 206 *
Chris@0 207 * @param string $method
Chris@0 208 * The HTTP method for which to set up authentication.
Chris@0 209 *
Chris@0 210 * @see ::grantPermissionsToAnonymousRole()
Chris@0 211 * @see ::grantPermissionsToAuthenticatedRole()
Chris@0 212 */
Chris@0 213 abstract protected function setUpAuthorization($method);
Chris@0 214
Chris@0 215 /**
Chris@0 216 * Verifies the error response in case of missing authentication.
Chris@0 217 */
Chris@0 218 abstract protected function assertResponseWhenMissingAuthentication(ResponseInterface $response);
Chris@0 219
Chris@0 220 /**
Chris@0 221 * Asserts normalization-specific edge cases.
Chris@0 222 *
Chris@0 223 * (Should be called before sending a well-formed request.)
Chris@0 224 *
Chris@0 225 * @see \GuzzleHttp\ClientInterface::request()
Chris@0 226 *
Chris@0 227 * @param string $method
Chris@0 228 * HTTP method.
Chris@0 229 * @param \Drupal\Core\Url $url
Chris@0 230 * URL to request.
Chris@0 231 * @param array $request_options
Chris@0 232 * Request options to apply.
Chris@0 233 */
Chris@0 234 abstract protected function assertNormalizationEdgeCases($method, Url $url, array $request_options);
Chris@0 235
Chris@0 236 /**
Chris@0 237 * Asserts authentication provider-specific edge cases.
Chris@0 238 *
Chris@0 239 * (Should be called before sending a well-formed request.)
Chris@0 240 *
Chris@0 241 * @see \GuzzleHttp\ClientInterface::request()
Chris@0 242 *
Chris@0 243 * @param string $method
Chris@0 244 * HTTP method.
Chris@0 245 * @param \Drupal\Core\Url $url
Chris@0 246 * URL to request.
Chris@0 247 * @param array $request_options
Chris@0 248 * Request options to apply.
Chris@0 249 */
Chris@0 250 abstract protected function assertAuthenticationEdgeCases($method, Url $url, array $request_options);
Chris@0 251
Chris@0 252 /**
Chris@0 253 * Initializes authentication.
Chris@0 254 *
Chris@0 255 * E.g. for cookie authentication, we first need to get a cookie.
Chris@0 256 */
Chris@0 257 protected function initAuthentication() {}
Chris@0 258
Chris@0 259 /**
Chris@0 260 * Returns Guzzle request options for authentication.
Chris@0 261 *
Chris@0 262 * @param string $method
Chris@0 263 * The HTTP method for this authenticated request.
Chris@0 264 *
Chris@0 265 * @return array
Chris@0 266 * Guzzle request options to use for authentication.
Chris@0 267 *
Chris@0 268 * @see \GuzzleHttp\ClientInterface::request()
Chris@0 269 */
Chris@0 270 protected function getAuthenticationRequestOptions($method) {
Chris@0 271 return [];
Chris@0 272 }
Chris@0 273
Chris@0 274 /**
Chris@0 275 * Grants permissions to the anonymous role.
Chris@0 276 *
Chris@0 277 * @param string[] $permissions
Chris@0 278 * Permissions to grant.
Chris@0 279 */
Chris@0 280 protected function grantPermissionsToAnonymousRole(array $permissions) {
Chris@0 281 $this->grantPermissions(Role::load(RoleInterface::ANONYMOUS_ID), $permissions);
Chris@0 282 }
Chris@0 283
Chris@0 284 /**
Chris@0 285 * Grants permissions to the authenticated role.
Chris@0 286 *
Chris@0 287 * @param string[] $permissions
Chris@0 288 * Permissions to grant.
Chris@0 289 */
Chris@0 290 protected function grantPermissionsToAuthenticatedRole(array $permissions) {
Chris@0 291 $this->grantPermissions(Role::load(RoleInterface::AUTHENTICATED_ID), $permissions);
Chris@0 292 }
Chris@0 293
Chris@0 294 /**
Chris@0 295 * Grants permissions to the tested role: anonymous or authenticated.
Chris@0 296 *
Chris@0 297 * @param string[] $permissions
Chris@0 298 * Permissions to grant.
Chris@0 299 *
Chris@0 300 * @see ::grantPermissionsToAuthenticatedRole()
Chris@0 301 * @see ::grantPermissionsToAnonymousRole()
Chris@0 302 */
Chris@0 303 protected function grantPermissionsToTestedRole(array $permissions) {
Chris@0 304 if (static::$auth) {
Chris@0 305 $this->grantPermissionsToAuthenticatedRole($permissions);
Chris@0 306 }
Chris@0 307 else {
Chris@0 308 $this->grantPermissionsToAnonymousRole($permissions);
Chris@0 309 }
Chris@0 310 }
Chris@0 311
Chris@0 312 /**
Chris@0 313 * Performs a HTTP request. Wraps the Guzzle HTTP client.
Chris@0 314 *
Chris@0 315 * Why wrap the Guzzle HTTP client? Because we want to keep the actual test
Chris@0 316 * code as simple as possible, and hence not require them to specify the
Chris@0 317 * 'http_errors = FALSE' request option, nor do we want them to have to
Chris@0 318 * convert Drupal Url objects to strings.
Chris@0 319 *
Chris@0 320 * We also don't want to follow redirects automatically, to ensure these tests
Chris@0 321 * are able to detect when redirects are added or removed.
Chris@0 322 *
Chris@0 323 * @see \GuzzleHttp\ClientInterface::request()
Chris@0 324 *
Chris@0 325 * @param string $method
Chris@0 326 * HTTP method.
Chris@0 327 * @param \Drupal\Core\Url $url
Chris@0 328 * URL to request.
Chris@0 329 * @param array $request_options
Chris@0 330 * Request options to apply.
Chris@0 331 *
Chris@0 332 * @return \Psr\Http\Message\ResponseInterface
Chris@0 333 */
Chris@0 334 protected function request($method, Url $url, array $request_options) {
Chris@0 335 $request_options[RequestOptions::HTTP_ERRORS] = FALSE;
Chris@0 336 $request_options[RequestOptions::ALLOW_REDIRECTS] = FALSE;
Chris@0 337 $request_options = $this->decorateWithXdebugCookie($request_options);
Chris@0 338 $client = $this->getSession()->getDriver()->getClient()->getClient();
Chris@0 339 return $client->request($method, $url->setAbsolute(TRUE)->toString(), $request_options);
Chris@0 340 }
Chris@0 341
Chris@0 342 /**
Chris@0 343 * Asserts that a resource response has the given status code and body.
Chris@0 344 *
Chris@0 345 * @param int $expected_status_code
Chris@0 346 * The expected response status.
Chris@0 347 * @param string|false $expected_body
Chris@0 348 * The expected response body. FALSE in case this should not be asserted.
Chris@0 349 * @param \Psr\Http\Message\ResponseInterface $response
Chris@0 350 * The response to assert.
Chris@0 351 */
Chris@0 352 protected function assertResourceResponse($expected_status_code, $expected_body, ResponseInterface $response) {
Chris@0 353 $this->assertSame($expected_status_code, $response->getStatusCode());
Chris@0 354 $this->assertSame([static::$mimeType], $response->getHeader('Content-Type'));
Chris@0 355 if ($expected_body !== FALSE) {
Chris@0 356 $this->assertSame($expected_body, (string) $response->getBody());
Chris@0 357 }
Chris@0 358 }
Chris@0 359
Chris@0 360 /**
Chris@0 361 * Asserts that a resource error response has the given message.
Chris@0 362 *
Chris@0 363 * @param int $expected_status_code
Chris@0 364 * The expected response status.
Chris@0 365 * @param string $expected_message
Chris@0 366 * The expected error message.
Chris@0 367 * @param \Psr\Http\Message\ResponseInterface $response
Chris@0 368 * The error response to assert.
Chris@0 369 */
Chris@0 370 protected function assertResourceErrorResponse($expected_status_code, $expected_message, ResponseInterface $response) {
Chris@0 371 $expected_body = ($expected_message !== FALSE) ? $this->serializer->encode(['message' => $expected_message], static::$format) : FALSE;
Chris@0 372 $this->assertResourceResponse($expected_status_code, $expected_body, $response);
Chris@0 373 }
Chris@0 374
Chris@0 375 /**
Chris@0 376 * Adds the Xdebug cookie to the request options.
Chris@0 377 *
Chris@0 378 * @param array $request_options
Chris@0 379 * The request options.
Chris@0 380 *
Chris@0 381 * @return array
Chris@0 382 * Request options updated with the Xdebug cookie if present.
Chris@0 383 */
Chris@0 384 protected function decorateWithXdebugCookie(array $request_options) {
Chris@0 385 $session = $this->getSession();
Chris@0 386 $driver = $session->getDriver();
Chris@0 387 if ($driver instanceof BrowserKitDriver) {
Chris@0 388 $client = $driver->getClient();
Chris@0 389 foreach ($client->getCookieJar()->all() as $cookie) {
Chris@0 390 if (isset($request_options[RequestOptions::HEADERS]['Cookie'])) {
Chris@0 391 $request_options[RequestOptions::HEADERS]['Cookie'] .= '; ' . $cookie->getName() . '=' . $cookie->getValue();
Chris@0 392 }
Chris@0 393 else {
Chris@0 394 $request_options[RequestOptions::HEADERS]['Cookie'] = $cookie->getName() . '=' . $cookie->getValue();
Chris@0 395 }
Chris@0 396 }
Chris@0 397 }
Chris@0 398 return $request_options;
Chris@0 399 }
Chris@0 400
Chris@0 401 }