public function ApiTest::testAllowed in Lightning API 8.3
Same name and namespace in other branches
- 8.4 tests/src/Functional/ApiTest.php \Drupal\Tests\lightning_api\Functional\ApiTest::testAllowed()
Tests Getting data as anon and authenticated user.
File
- tests/
src/ Functional/ ApiTest.php, line 223
Class
- ApiTest
- Tests OAuth and JSON:API authentication and interactions with entities.
Namespace
Drupal\Tests\lightning_api\FunctionalCode
public function testAllowed() {
$this
->createContentType([
'type' => 'page',
]);
// Create some sample content for testing. One published and one unpublished
// basic page.
$published_node = $this
->drupalCreateNode();
$unpublished_node = $published_node
->createDuplicate()
->setUnpublished();
$unpublished_node
->save();
// Get data that is available anonymously.
$response = $this
->request('/jsonapi/node/page/' . $published_node
->uuid());
$this
->assertSame(200, $response
->getStatusCode());
$body = $this
->decodeResponse($response);
$this
->assertSame($published_node
->getTitle(), $body['data']['attributes']['title']);
// Get data that requires authentication.
$access_token = $this
->getCreator('page');
$response = $this
->request('/jsonapi/node/page/' . $unpublished_node
->uuid(), 'get', $access_token);
$this
->assertSame(200, $response
->getStatusCode());
$body = $this
->decodeResponse($response);
$this
->assertSame($unpublished_node
->getTitle(), $body['data']['attributes']['title']);
// Post new content that requires authentication.
$count = (int) \Drupal::entityQuery('node')
->count()
->execute();
$this
->request('/jsonapi/node/page', 'post', $access_token, [
'data' => [
'type' => 'node--page',
'attributes' => [
'title' => 'With my own two hands',
],
],
]);
$this
->assertSame(++$count, (int) \Drupal::entityQuery('node')
->count()
->execute());
}