View source
<?php
namespace Drupal\Tests\api_test\Functional;
use Drupal\Component\Serialization\Json;
use GuzzleHttp\Exception\ClientException;
class ApiTest extends ApiTestBase {
private $token;
protected function setUp() {
parent::setUp();
$page_creator_client_options = [
'form_params' => [
'grant_type' => 'password',
'client_id' => 'api_test-oauth2-client',
'client_secret' => 'oursecret',
'username' => 'api-test-user',
'password' => 'admin',
],
];
$this->token = $this
->getToken($page_creator_client_options);
}
public function testAllowed() {
$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']);
$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']);
$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());
\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());
}
public function testNotAllowed() {
$response = $this
->request('/jsonapi/user_role/user_role', 'get', $this->token);
$body = $this
->decodeResponse($response);
$this
->assertArrayHasKey('errors', $body['meta']);
foreach ($body['meta']['errors'] as $error) {
$this
->assertEquals(403, $error['status']);
}
$client = $this->container
->get('http_client');
$url = $this
->buildUrl('/jsonapi/node/page/api_test-unpublished-page-content');
$this
->setExpectedException(ClientException::class, 'Client error: `GET ' . $url . '` resulted in a `403 Forbidden`');
$client
->get($url);
}
}