CommentResourceTestBase.php 10.1 KB
Newer Older
1 2 3 4 5 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 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
<?php

namespace Drupal\Tests\rest\Functional\EntityResource\Comment;

use Drupal\comment\Entity\Comment;
use Drupal\comment\Entity\CommentType;
use Drupal\comment\Tests\CommentTestTrait;
use Drupal\entity_test\Entity\EntityTest;
use Drupal\Tests\rest\Functional\EntityResource\EntityResourceTestBase;
use Drupal\user\Entity\User;
use GuzzleHttp\RequestOptions;

abstract class CommentResourceTestBase extends EntityResourceTestBase {

  use CommentTestTrait;

  /**
   * {@inheritdoc}
   */
  public static $modules = ['comment', 'entity_test'];

  /**
   * {@inheritdoc}
   */
  protected static $entityTypeId = 'comment';

  /**
   * {@inheritdoc}
   */
  protected static $patchProtectedFieldNames = [
    'status',
    'pid',
    'entity_id',
    'uid',
    'name',
    'homepage',
    'created',
    'changed',
    'thread',
    'entity_type',
    'field_name',
  ];

  /**
   * @var \Drupal\comment\CommentInterface
   */
  protected $entity;

  /**
   * {@inheritdoc}
   */
  protected function setUpAuthorization($method) {
    switch ($method) {
      case 'GET':
        $this->grantPermissionsToTestedRole(['access comments', 'view test entity']);
        break;
      case 'POST':
        $this->grantPermissionsToTestedRole(['post comments']);
        break;
      case 'PATCH':
        // Anononymous users are not ever allowed to edit their own comments. To
        // be able to test PATCHing comments as the anonymous user, the more
        // permissive 'administer comments' permission must be granted.
        // @see \Drupal\comment\CommentAccessControlHandler::checkAccess
        if (static::$auth) {
          $this->grantPermissionsToTestedRole(['edit own comments']);
        }
        else {
          $this->grantPermissionsToTestedRole(['administer comments']);
        }
        break;
      case 'DELETE':
        $this->grantPermissionsToTestedRole(['administer comments']);
        break;
    }
  }

  /**
   * {@inheritdoc}
   */
  protected function createEntity() {
    // Create a "bar" bundle for the "entity_test" entity type and create.
    $bundle = 'bar';
    entity_test_create_bundle($bundle, NULL, 'entity_test');

    // Create a comment field on this bundle.
    $this->addDefaultCommentField('entity_test', 'bar', 'comment');

    // Create a "Camelids" test entity that the comment will be assigned to.
90
    $commented_entity = EntityTest::create([
91 92
      'name' => 'Camelids',
      'type' => 'bar',
93
    ]);
94 95 96 97 98 99 100 101 102 103 104 105 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 136 137 138 139 140 141 142 143 144 145 146
    $commented_entity->save();

    // Create a "Llama" comment.
    $comment = Comment::create([
      'comment_body' => [
        'value' => 'The name "llama" was adopted by European settlers from native Peruvians.',
        'format' => 'plain_text',
      ],
      'entity_id' => $commented_entity->id(),
      'entity_type' => 'entity_test',
      'field_name' => 'comment',
    ]);
    $comment->setSubject('Llama')
      ->setOwnerId(static::$auth ? $this->account->id() : 0)
      ->setPublished(TRUE)
      ->setCreatedTime(123456789)
      ->setChangedTime(123456789);
    $comment->save();

    return $comment;
  }

  /**
   * {@inheritdoc}
   */
  protected function getExpectedNormalizedEntity() {
    $author = User::load($this->entity->getOwnerId());
    return [
      'cid' => [
        ['value' => 1],
      ],
      'uuid' => [
        ['value' => $this->entity->uuid()],
      ],
      'langcode' => [
        [
          'value' => 'en',
        ],
      ],
      'comment_type' => [
        [
          'target_id' => 'comment',
          'target_type' => 'comment_type',
          'target_uuid' => CommentType::load('comment')->uuid(),
        ],
      ],
      'subject' => [
        [
          'value' => 'Llama',
        ],
      ],
      'status' => [
        [
147
          'value' => TRUE,
148 149 150 151
        ],
      ],
      'created' => [
        [
152
          'value' => 123456789,
153 154 155 156
        ],
      ],
      'changed' => [
        [
157
          'value' => $this->entity->getChangedTime(),
158 159 160 161 162 163 164 165 166
        ],
      ],
      'default_langcode' => [
        [
          'value' => TRUE,
        ],
      ],
      'uid' => [
        [
167
          'target_id' => (int) $author->id(),
168 169 170 171 172 173 174 175 176 177 178 179 180
          'target_type' => 'user',
          'target_uuid' => $author->uuid(),
          'url' => base_path() . 'user/' . $author->id(),
        ],
      ],
      'pid' => [],
      'entity_type' => [
        [
          'value' => 'entity_test',
        ],
      ],
      'entity_id' => [
        [
181
          'target_id' => 1,
182 183 184 185 186 187 188 189 190 191 192 193 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
          'target_type' => 'entity_test',
          'target_uuid' => EntityTest::load(1)->uuid(),
          'url' => base_path() . 'entity_test/1',
        ],
      ],
      'field_name' => [
        [
          'value' => 'comment',
        ],
      ],
      'name' => [],
      'homepage' => [],
      'thread' => [
        [
          'value' => '01/',
        ],
      ],
      'comment_body' => [
        [
          'value' => 'The name "llama" was adopted by European settlers from native Peruvians.',
          'format' => 'plain_text',
        ],
      ],
    ];
  }

  /**
   * {@inheritdoc}
   */
  protected function getNormalizedPostEntity() {
    return [
      'comment_type' => [
        [
          'target_id' => 'comment',
        ],
      ],
      'entity_type' => [
        [
          'value' => 'entity_test',
        ],
      ],
      'entity_id' => [
        [
          'target_id' => EntityTest::load(1)->id(),
        ],
      ],
      'field_name' => [
        [
          'value' => 'comment',
        ],
      ],
      'subject' => [
        [
          'value' => 'Dramallama',
        ],
      ],
      'comment_body' => [
        [
          'value' => 'Llamas are awesome.',
          'format' => 'plain_text',
        ],
      ],
    ];
  }

  /**
   * {@inheritdoc}
   */
  protected function getNormalizedPatchEntity() {
    return array_diff_key($this->getNormalizedPostEntity(), ['entity_type' => TRUE, 'entity_id' => TRUE, 'field_name' => TRUE]);
  }

  /**
   * Tests POSTing a comment without critical base fields.
   *
   * testPost() is testing with the most minimal normalization possible: the one
   * returned by ::getNormalizedPostEntity().
   *
   * But Comment entities have some very special edge cases:
   * - base fields that are not marked as required in
   *   \Drupal\comment\Entity\Comment::baseFieldDefinitions() yet in fact are
   *   required.
   * - base fields that are marked as required, but yet can still result in
   *   validation errors other than "missing required field".
   */
  public function testPostDxWithoutCriticalBaseFields() {
    $this->initAuthentication();
    $this->provisionEntityResource();
    $this->setUpAuthorization('POST');

    $url = $this->getPostUrl()->setOption('query', ['_format' => static::$format]);
    $request_options = [];
    $request_options[RequestOptions::HEADERS]['Accept'] = static::$mimeType;
    $request_options[RequestOptions::HEADERS]['Content-Type'] = static::$mimeType;
    $request_options = array_merge_recursive($request_options, $this->getAuthenticationRequestOptions('POST'));

    // DX: 422 when missing 'entity_type' field.
    $request_options[RequestOptions::BODY] = $this->serializer->encode(array_diff_key($this->getNormalizedPostEntity(), ['entity_type' => TRUE]), static::$format);
    $response = $this->request('POST', $url, $request_options);
281 282
    // @todo Uncomment, remove next 3 lines in https://www.drupal.org/node/2820364.
    $this->assertSame(500, $response->getStatusCode());
283
    $this->assertSame(['text/plain; charset=UTF-8'], $response->getHeader('Content-Type'));
284
    $this->assertStringStartsWith('The website encountered an unexpected error. Please try again later.</br></br><em class="placeholder">Symfony\Component\HttpKernel\Exception\HttpException</em>: Internal Server Error in <em class="placeholder">Drupal\rest\Plugin\rest\resource\EntityResource-&gt;post()</em>', (string) $response->getBody());
285 286 287 288 289 290 291 292 293
    //$this->assertResourceErrorResponse(422, "Unprocessable Entity: validation failed.\nentity_type: This value should not be null.\n", $response);

    // DX: 422 when missing 'entity_id' field.
    $request_options[RequestOptions::BODY] = $this->serializer->encode(array_diff_key($this->getNormalizedPostEntity(), ['entity_id' => TRUE]), static::$format);
    // @todo Remove the try/catch in favor of the two commented lines in
    // https://www.drupal.org/node/2820364.
    try {
      $response = $this->request('POST', $url, $request_options);
      // This happens on DrupalCI.
294
      //$this->assertSame(500, $response->getStatusCode());
295 296 297
    }
    catch (\Exception $e) {
      // This happens on Wim's local machine.
298
      //$this->assertSame("Error: Call to a member function get() on null\nDrupal\\comment\\Plugin\\Validation\\Constraint\\CommentNameConstraintValidator->getAnonymousContactDetailsSetting()() (Line: 96)\n", $e->getMessage());
299 300 301 302 303 304 305
    }
    //$response = $this->request('POST', $url, $request_options);
    //$this->assertResourceErrorResponse(422, "Unprocessable Entity: validation failed.\nentity_type: This value should not be null.\n", $response);

    // DX: 422 when missing 'entity_type' field.
    $request_options[RequestOptions::BODY] = $this->serializer->encode(array_diff_key($this->getNormalizedPostEntity(), ['field_name' => TRUE]), static::$format);
    $response = $this->request('POST', $url, $request_options);
306
    // @todo Uncomment, remove next 2 lines in https://www.drupal.org/node/2820364.
307
    $this->assertSame(500, $response->getStatusCode());
308
    $this->assertSame(['text/plain; charset=UTF-8'], $response->getHeader('Content-Type'));
309 310 311
    //$this->assertResourceErrorResponse(422, "Unprocessable Entity: validation failed.\nfield_name: This value should not be null.\n", $response);
  }

312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
  /**
   * {@inheritdoc}
   */
  protected function getExpectedUnauthorizedAccessMessage($method) {
    if ($this->config('rest.settings')->get('bc_entity_resource_permissions')) {
      return parent::getExpectedUnauthorizedAccessMessage($method);
    }

    switch ($method) {
      case 'GET';
        return "The 'access comments' permission is required and the comment must be published.";
      case 'POST';
        return "The 'post comments' permission is required.";
      default:
        return parent::getExpectedUnauthorizedAccessMessage($method);
    }
  }

330
}