Mercurial > hg > cmmr2012-drupal-site
comparison core/modules/jsonapi/tests/src/Functional/CommentTest.php @ 5:12f9dff5fda9 tip
Update to Drupal core 8.7.1
author | Chris Cannam |
---|---|
date | Thu, 09 May 2019 15:34:47 +0100 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
4:a9cd425dd02b | 5:12f9dff5fda9 |
---|---|
1 <?php | |
2 | |
3 namespace Drupal\Tests\jsonapi\Functional; | |
4 | |
5 use Drupal\comment\Entity\Comment; | |
6 use Drupal\comment\Entity\CommentType; | |
7 use Drupal\comment\Tests\CommentTestTrait; | |
8 use Drupal\Component\Serialization\Json; | |
9 use Drupal\Component\Utility\NestedArray; | |
10 use Drupal\Core\Cache\Cache; | |
11 use Drupal\Core\Entity\EntityInterface; | |
12 use Drupal\Core\Session\AccountInterface; | |
13 use Drupal\Core\Url; | |
14 use Drupal\entity_test\Entity\EntityTest; | |
15 use Drupal\Tests\jsonapi\Traits\CommonCollectionFilterAccessTestPatternsTrait; | |
16 use Drupal\user\Entity\User; | |
17 use GuzzleHttp\RequestOptions; | |
18 | |
19 /** | |
20 * JSON:API integration test for the "Comment" content entity type. | |
21 * | |
22 * @group jsonapi | |
23 */ | |
24 class CommentTest extends ResourceTestBase { | |
25 | |
26 use CommentTestTrait; | |
27 use CommonCollectionFilterAccessTestPatternsTrait; | |
28 | |
29 /** | |
30 * {@inheritdoc} | |
31 */ | |
32 public static $modules = ['comment', 'entity_test']; | |
33 | |
34 /** | |
35 * {@inheritdoc} | |
36 */ | |
37 protected static $entityTypeId = 'comment'; | |
38 | |
39 /** | |
40 * {@inheritdoc} | |
41 */ | |
42 protected static $resourceTypeName = 'comment--comment'; | |
43 | |
44 /** | |
45 * {@inheritdoc} | |
46 */ | |
47 protected static $patchProtectedFieldNames = [ | |
48 'status' => "The 'administer comments' permission is required.", | |
49 'name' => "The 'administer comments' permission is required.", | |
50 'homepage' => "The 'administer comments' permission is required.", | |
51 'created' => "The 'administer comments' permission is required.", | |
52 'changed' => NULL, | |
53 'thread' => NULL, | |
54 'entity_type' => NULL, | |
55 'field_name' => NULL, | |
56 // @todo Uncomment this after https://www.drupal.org/project/drupal/issues/1847608 lands. Until then, it's impossible to test this. | |
57 // 'pid' => NULL, | |
58 'uid' => "The 'administer comments' permission is required.", | |
59 'entity_id' => NULL, | |
60 ]; | |
61 | |
62 /** | |
63 * {@inheritdoc} | |
64 * | |
65 * @var \Drupal\comment\CommentInterface | |
66 */ | |
67 protected $entity; | |
68 | |
69 /** | |
70 * {@inheritdoc} | |
71 */ | |
72 protected function setUpAuthorization($method) { | |
73 switch ($method) { | |
74 case 'GET': | |
75 $this->grantPermissionsToTestedRole(['access comments', 'view test entity']); | |
76 break; | |
77 | |
78 case 'POST': | |
79 $this->grantPermissionsToTestedRole(['post comments']); | |
80 break; | |
81 | |
82 case 'PATCH': | |
83 $this->grantPermissionsToTestedRole(['edit own comments']); | |
84 break; | |
85 | |
86 case 'DELETE': | |
87 $this->grantPermissionsToTestedRole(['administer comments']); | |
88 break; | |
89 } | |
90 } | |
91 | |
92 /** | |
93 * {@inheritdoc} | |
94 */ | |
95 protected function createEntity() { | |
96 // Create a "bar" bundle for the "entity_test" entity type and create. | |
97 $bundle = 'bar'; | |
98 entity_test_create_bundle($bundle, NULL, 'entity_test'); | |
99 | |
100 // Create a comment field on this bundle. | |
101 $this->addDefaultCommentField('entity_test', 'bar', 'comment'); | |
102 | |
103 // Create a "Camelids" test entity that the comment will be assigned to. | |
104 $commented_entity = EntityTest::create([ | |
105 'name' => 'Camelids', | |
106 'type' => 'bar', | |
107 ]); | |
108 $commented_entity->save(); | |
109 | |
110 // Create a "Llama" comment. | |
111 $comment = Comment::create([ | |
112 'comment_body' => [ | |
113 'value' => 'The name "llama" was adopted by European settlers from native Peruvians.', | |
114 'format' => 'plain_text', | |
115 ], | |
116 'entity_id' => $commented_entity->id(), | |
117 'entity_type' => 'entity_test', | |
118 'field_name' => 'comment', | |
119 ]); | |
120 $comment->setSubject('Llama') | |
121 ->setOwnerId($this->account->id()) | |
122 ->setPublished() | |
123 ->setCreatedTime(123456789) | |
124 ->setChangedTime(123456789); | |
125 $comment->save(); | |
126 | |
127 return $comment; | |
128 } | |
129 | |
130 /** | |
131 * {@inheritdoc} | |
132 */ | |
133 protected function getExpectedDocument() { | |
134 $self_url = Url::fromUri('base:/jsonapi/comment/comment/' . $this->entity->uuid())->setAbsolute()->toString(TRUE)->getGeneratedUrl(); | |
135 $author = User::load($this->entity->getOwnerId()); | |
136 return [ | |
137 'jsonapi' => [ | |
138 'meta' => [ | |
139 'links' => [ | |
140 'self' => ['href' => 'http://jsonapi.org/format/1.0/'], | |
141 ], | |
142 ], | |
143 'version' => '1.0', | |
144 ], | |
145 'links' => [ | |
146 'self' => ['href' => $self_url], | |
147 ], | |
148 'data' => [ | |
149 'id' => $this->entity->uuid(), | |
150 'type' => 'comment--comment', | |
151 'links' => [ | |
152 'self' => ['href' => $self_url], | |
153 ], | |
154 'attributes' => [ | |
155 'created' => '1973-11-29T21:33:09+00:00', | |
156 'changed' => (new \DateTime())->setTimestamp($this->entity->getChangedTime())->setTimezone(new \DateTimeZone('UTC'))->format(\DateTime::RFC3339), | |
157 'comment_body' => [ | |
158 'value' => 'The name "llama" was adopted by European settlers from native Peruvians.', | |
159 'format' => 'plain_text', | |
160 'processed' => "<p>The name "llama" was adopted by European settlers from native Peruvians.</p>\n", | |
161 ], | |
162 'default_langcode' => TRUE, | |
163 'entity_type' => 'entity_test', | |
164 'field_name' => 'comment', | |
165 'homepage' => NULL, | |
166 'langcode' => 'en', | |
167 'name' => NULL, | |
168 'status' => TRUE, | |
169 'subject' => 'Llama', | |
170 'thread' => '01/', | |
171 'drupal_internal__cid' => 1, | |
172 ], | |
173 'relationships' => [ | |
174 'uid' => [ | |
175 'data' => [ | |
176 'id' => $author->uuid(), | |
177 'type' => 'user--user', | |
178 ], | |
179 'links' => [ | |
180 'related' => ['href' => $self_url . '/uid'], | |
181 'self' => ['href' => $self_url . '/relationships/uid'], | |
182 ], | |
183 ], | |
184 'comment_type' => [ | |
185 'data' => [ | |
186 'id' => CommentType::load('comment')->uuid(), | |
187 'type' => 'comment_type--comment_type', | |
188 ], | |
189 'links' => [ | |
190 'related' => ['href' => $self_url . '/comment_type'], | |
191 'self' => ['href' => $self_url . '/relationships/comment_type'], | |
192 ], | |
193 ], | |
194 'entity_id' => [ | |
195 'data' => [ | |
196 'id' => EntityTest::load(1)->uuid(), | |
197 'type' => 'entity_test--bar', | |
198 ], | |
199 'links' => [ | |
200 'related' => ['href' => $self_url . '/entity_id'], | |
201 'self' => ['href' => $self_url . '/relationships/entity_id'], | |
202 ], | |
203 ], | |
204 'pid' => [ | |
205 'data' => NULL, | |
206 'links' => [ | |
207 'related' => ['href' => $self_url . '/pid'], | |
208 'self' => ['href' => $self_url . '/relationships/pid'], | |
209 ], | |
210 ], | |
211 ], | |
212 ], | |
213 ]; | |
214 } | |
215 | |
216 /** | |
217 * {@inheritdoc} | |
218 */ | |
219 protected function getPostDocument() { | |
220 return [ | |
221 'data' => [ | |
222 'type' => 'comment--comment', | |
223 'attributes' => [ | |
224 'entity_type' => 'entity_test', | |
225 'field_name' => 'comment', | |
226 'subject' => 'Dramallama', | |
227 'comment_body' => [ | |
228 'value' => 'Llamas are awesome.', | |
229 'format' => 'plain_text', | |
230 ], | |
231 ], | |
232 'relationships' => [ | |
233 'entity_id' => [ | |
234 'data' => [ | |
235 'type' => 'entity_test--bar', | |
236 'id' => EntityTest::load(1)->uuid(), | |
237 ], | |
238 ], | |
239 ], | |
240 ], | |
241 ]; | |
242 } | |
243 | |
244 /** | |
245 * {@inheritdoc} | |
246 */ | |
247 protected function getExpectedCacheTags(array $sparse_fieldset = NULL) { | |
248 $tags = parent::getExpectedCacheTags($sparse_fieldset); | |
249 if ($sparse_fieldset === NULL || in_array('comment_body', $sparse_fieldset)) { | |
250 $tags = Cache::mergeTags($tags, ['config:filter.format.plain_text']); | |
251 } | |
252 return $tags; | |
253 } | |
254 | |
255 /** | |
256 * {@inheritdoc} | |
257 */ | |
258 protected function getExpectedCacheContexts(array $sparse_fieldset = NULL) { | |
259 $contexts = parent::getExpectedCacheContexts($sparse_fieldset); | |
260 if ($sparse_fieldset === NULL || in_array('comment_body', $sparse_fieldset)) { | |
261 $contexts = Cache::mergeContexts($contexts, ['languages:language_interface', 'theme']); | |
262 } | |
263 return $contexts; | |
264 } | |
265 | |
266 /** | |
267 * {@inheritdoc} | |
268 */ | |
269 protected function getExpectedUnauthorizedAccessMessage($method) { | |
270 switch ($method) { | |
271 case 'GET'; | |
272 return "The 'access comments' permission is required and the comment must be published."; | |
273 | |
274 case 'POST'; | |
275 return "The 'post comments' permission is required."; | |
276 | |
277 case 'PATCH': | |
278 return "The 'edit own comments' permission is required, the user must be the comment author, and the comment must be published."; | |
279 | |
280 default: | |
281 return parent::getExpectedUnauthorizedAccessMessage($method); | |
282 } | |
283 } | |
284 | |
285 /** | |
286 * Tests POSTing a comment without critical base fields. | |
287 * | |
288 * Note that testPostIndividual() is testing with the most minimal | |
289 * normalization possible: the one returned by ::getNormalizedPostEntity(). | |
290 * | |
291 * But Comment entities have some very special edge cases: | |
292 * - base fields that are not marked as required in | |
293 * \Drupal\comment\Entity\Comment::baseFieldDefinitions() yet in fact are | |
294 * required. | |
295 * - base fields that are marked as required, but yet can still result in | |
296 * validation errors other than "missing required field". | |
297 */ | |
298 public function testPostIndividualDxWithoutCriticalBaseFields() { | |
299 $this->setUpAuthorization('POST'); | |
300 $this->config('jsonapi.settings')->set('read_only', FALSE)->save(TRUE); | |
301 | |
302 $url = Url::fromRoute(sprintf('jsonapi.%s.collection.post', static::$resourceTypeName)); | |
303 $request_options = []; | |
304 $request_options[RequestOptions::HEADERS]['Accept'] = 'application/vnd.api+json'; | |
305 $request_options[RequestOptions::HEADERS]['Content-Type'] = 'application/vnd.api+json'; | |
306 $request_options = NestedArray::mergeDeep($request_options, $this->getAuthenticationRequestOptions()); | |
307 | |
308 $remove_field = function (array $normalization, $type, $attribute_name) { | |
309 unset($normalization['data'][$type][$attribute_name]); | |
310 return $normalization; | |
311 }; | |
312 | |
313 // DX: 422 when missing 'entity_type' field. | |
314 $request_options[RequestOptions::BODY] = Json::encode($remove_field($this->getPostDocument(), 'attributes', 'entity_type')); | |
315 $response = $this->request('POST', $url, $request_options); | |
316 $this->assertResourceErrorResponse(422, 'entity_type: This value should not be null.', NULL, $response, '/data/attributes/entity_type'); | |
317 | |
318 // DX: 422 when missing 'entity_id' field. | |
319 $request_options[RequestOptions::BODY] = Json::encode($remove_field($this->getPostDocument(), 'relationships', 'entity_id')); | |
320 // @todo Remove the try/catch in https://www.drupal.org/node/2820364. | |
321 try { | |
322 $response = $this->request('POST', $url, $request_options); | |
323 $this->assertResourceErrorResponse(422, 'entity_id: This value should not be null.', NULL, $response, '/data/attributes/entity_id'); | |
324 } | |
325 catch (\Exception $e) { | |
326 if (version_compare(phpversion(), '7.0') >= 0) { | |
327 $this->assertSame("Error: Call to a member function get() on null\nDrupal\\comment\\Plugin\\Validation\\Constraint\\CommentNameConstraintValidator->getAnonymousContactDetailsSetting()() (Line: 96)\n", $e->getMessage()); | |
328 } | |
329 else { | |
330 $this->assertSame(500, $response->getStatusCode()); | |
331 } | |
332 } | |
333 | |
334 // DX: 422 when missing 'field_name' field. | |
335 $request_options[RequestOptions::BODY] = Json::encode($remove_field($this->getPostDocument(), 'attributes', 'field_name')); | |
336 $response = $this->request('POST', $url, $request_options); | |
337 $this->assertResourceErrorResponse(422, 'field_name: This value should not be null.', NULL, $response, '/data/attributes/field_name'); | |
338 } | |
339 | |
340 /** | |
341 * Tests POSTing a comment with and without 'skip comment approval'. | |
342 */ | |
343 public function testPostIndividualSkipCommentApproval() { | |
344 $this->setUpAuthorization('POST'); | |
345 $this->config('jsonapi.settings')->set('read_only', FALSE)->save(TRUE); | |
346 | |
347 // Create request. | |
348 $request_options = []; | |
349 $request_options[RequestOptions::HEADERS]['Accept'] = 'application/vnd.api+json'; | |
350 $request_options[RequestOptions::HEADERS]['Content-Type'] = 'application/vnd.api+json'; | |
351 $request_options = NestedArray::mergeDeep($request_options, $this->getAuthenticationRequestOptions()); | |
352 $request_options[RequestOptions::BODY] = Json::encode($this->getPostDocument()); | |
353 | |
354 $url = Url::fromRoute('jsonapi.comment--comment.collection.post'); | |
355 | |
356 // Status should be FALSE when posting as anonymous. | |
357 $response = $this->request('POST', $url, $request_options); | |
358 $this->assertResourceResponse(201, FALSE, $response); | |
359 $this->assertFalse(Json::decode((string) $response->getBody())['data']['attributes']['status']); | |
360 $this->assertFalse($this->entityStorage->loadUnchanged(2)->isPublished()); | |
361 | |
362 // Grant anonymous permission to skip comment approval. | |
363 $this->grantPermissionsToTestedRole(['skip comment approval']); | |
364 | |
365 // Status must be TRUE when posting as anonymous and skip comment approval. | |
366 $response = $this->request('POST', $url, $request_options); | |
367 $this->assertResourceResponse(201, FALSE, $response); | |
368 $this->assertTrue(Json::decode((string) $response->getBody())['data']['attributes']['status']); | |
369 $this->assertTrue($this->entityStorage->loadUnchanged(3)->isPublished()); | |
370 } | |
371 | |
372 /** | |
373 * {@inheritdoc} | |
374 */ | |
375 protected function getExpectedUnauthorizedAccessCacheability() { | |
376 // @see \Drupal\comment\CommentAccessControlHandler::checkAccess() | |
377 return parent::getExpectedUnauthorizedAccessCacheability() | |
378 ->addCacheTags(['comment:1']); | |
379 } | |
380 | |
381 /** | |
382 * {@inheritdoc} | |
383 */ | |
384 protected static function entityAccess(EntityInterface $entity, $operation, AccountInterface $account) { | |
385 // Also reset the 'entity_test' entity access control handler because | |
386 // comment access also depends on access to the commented entity type. | |
387 \Drupal::entityTypeManager()->getAccessControlHandler('entity_test')->resetCache(); | |
388 return parent::entityAccess($entity, $operation, $account); | |
389 } | |
390 | |
391 /** | |
392 * {@inheritdoc} | |
393 */ | |
394 public function testRelated() { | |
395 $this->markTestSkipped('Remove this in https://www.drupal.org/project/jsonapi/issues/2940339'); | |
396 } | |
397 | |
398 /** | |
399 * {@inheritdoc} | |
400 */ | |
401 protected static function getIncludePermissions() { | |
402 return [ | |
403 'type' => ['administer comment types'], | |
404 'uid' => ['access user profiles'], | |
405 ]; | |
406 } | |
407 | |
408 /** | |
409 * {@inheritdoc} | |
410 */ | |
411 public function testCollectionFilterAccess() { | |
412 // Verify the expected behavior in the common case. | |
413 $this->doTestCollectionFilterAccessForPublishableEntities('subject', 'access comments', 'administer comments'); | |
414 | |
415 $collection_url = Url::fromRoute('jsonapi.entity_test--bar.collection'); | |
416 $request_options = []; | |
417 $request_options[RequestOptions::HEADERS]['Accept'] = 'application/vnd.api+json'; | |
418 $request_options = NestedArray::mergeDeep($request_options, $this->getAuthenticationRequestOptions()); | |
419 | |
420 // Go back to a simpler scenario: revoke the admin permission, publish the | |
421 // comment and uninstall the query access test module. | |
422 $this->revokePermissionsFromTestedRole(['administer comments']); | |
423 $this->entity->setPublished()->save(); | |
424 $this->assertTrue($this->container->get('module_installer')->uninstall(['jsonapi_test_field_filter_access'], TRUE), 'Uninstalled modules.'); | |
425 // ?filter[spotlight.LABEL]: 1 result. Just as already tested above in | |
426 // ::doTestCollectionFilterAccessForPublishableEntities(). | |
427 $collection_filter_url = $collection_url->setOption('query', ["filter[spotlight.subject]" => $this->entity->label()]); | |
428 $response = $this->request('GET', $collection_filter_url, $request_options); | |
429 $doc = Json::decode((string) $response->getBody()); | |
430 $this->assertCount(1, $doc['data']); | |
431 // Mark the commented entity as inaccessible. | |
432 \Drupal::state()->set('jsonapi__entity_test_filter_access_blacklist', [$this->entity->getCommentedEntityId()]); | |
433 Cache::invalidateTags(['state:jsonapi__entity_test_filter_access_blacklist']); | |
434 // ?filter[spotlight.LABEL]: 0 results. | |
435 $response = $this->request('GET', $collection_filter_url, $request_options); | |
436 $doc = Json::decode((string) $response->getBody()); | |
437 $this->assertCount(0, $doc['data']); | |
438 } | |
439 | |
440 /** | |
441 * {@inheritdoc} | |
442 */ | |
443 protected static function getExpectedCollectionCacheability(AccountInterface $account, array $collection, array $sparse_fieldset = NULL, $filtered = FALSE) { | |
444 $cacheability = parent::getExpectedCollectionCacheability($account, $collection, $sparse_fieldset, $filtered); | |
445 if ($filtered) { | |
446 $cacheability->addCacheTags(['state:jsonapi__entity_test_filter_access_blacklist']); | |
447 } | |
448 return $cacheability; | |
449 } | |
450 | |
451 /** | |
452 * {@inheritdoc} | |
453 */ | |
454 public function testPatchIndividual() { | |
455 // Ensure ::getModifiedEntityForPatchTesting() can pick an alternative value | |
456 // for the 'entity_id' field. | |
457 EntityTest::create([ | |
458 'name' => $this->randomString(), | |
459 'type' => 'bar', | |
460 ])->save(); | |
461 | |
462 return parent::testPatchIndividual(); | |
463 } | |
464 | |
465 } |