public function ApiTest::testAllowed in Lightning API 8
Same name and namespace in other branches
- 8.2 modules/api_test/tests/src/Functional/ApiTest.php \Drupal\Tests\api_test\Functional\ApiTest::testAllowed()
Tests Getting data as anon and authenticated user.
File
- modules/
api_test/ tests/ src/ Functional/ ApiTest.php, line 47
Class
- ApiTest
- Tests that OAuth and json:api are working together to authenticate, authorize and allow/forbid interaction with entities as designed.
Namespace
Drupal\Tests\api_test\FunctionalCode
public function testAllowed() {
// Get data that is available anonymously.
$response = $this
->request('/jsonapi/node/page/api_test-published-page-content');
$this
->assertEquals(200, $response
->getStatusCode());
$body = $this
->decodeResponse($response);
$this
->assertEquals('Published Page', $body['data']['attributes']['title']);
// Get data that requires authentication.
$response = $this
->request('/jsonapi/node/page/api_test-unpublished-page-content', 'get', $this->token);
$this
->assertEquals(200, $response
->getStatusCode());
$body = $this
->decodeResponse($response);
$this
->assertEquals('Unpublished Page', $body['data']['attributes']['title']);
// Post new content that requires authentication.
$count = (int) \Drupal::entityQuery('node')
->count()
->execute();
$data = [
'data' => [
'type' => 'node--page',
'attributes' => [
'title' => 'With my own two hands',
],
],
];
$this
->request('/jsonapi/node/page', 'post', $this->token, $data);
$this
->assertSame(++$count, (int) \Drupal::entityQuery('node')
->count()
->execute());
// The user, client, and content should be removed on uninstall. The account
// created by generateKeys() will still be around, but that exists only in
// the test database, so we don't need to worry about it.
\Drupal::service('module_installer')
->uninstall([
'api_test',
]);
$this
->assertSame(1, (int) \Drupal::entityQuery('user')
->condition('uid', 1, '>')
->count()
->execute());
$this
->assertSame(0, (int) \Drupal::entityQuery('consumer')
->count()
->execute());
$this
->assertSame(0, (int) \Drupal::entityQuery('node')
->count()
->execute());
}