View source
<?php
namespace Drupal\Tests\api_test\Functional;
use Drupal\taxonomy\Entity\Vocabulary;
use Drupal\user\Entity\User;
use Drupal\consumers\Entity\Consumer;
class EntityCrudTest extends ApiTestBase {
private $token;
protected function setUp() {
parent::setUp();
$account = User::create([
'name' => 'api-admin-user',
'mail' => 'api-admin-user@example.com',
'pass' => 'admin',
]);
$account
->addRole('administrator');
$account
->activate()
->save();
$client = Consumer::create([
'label' => 'API Test Admin Client',
'secret' => 'oursecret',
'confidential' => 1,
'user_id' => $account
->id(),
'roles' => 'administrator',
]);
$client
->save();
$admin_client_options = [
'form_params' => [
'grant_type' => 'password',
'client_id' => $client
->uuid(),
'client_secret' => 'oursecret',
'username' => $account
->getAccountName(),
'password' => 'admin',
],
];
$this->token = $this
->getToken($admin_client_options);
}
public function testEntities() {
$vocabulary = Vocabulary::create([
'name' => "I'm a vocab",
'vid' => 'im_a_vocab',
'status' => TRUE,
]);
$vocabulary
->save();
$endpoint = '/jsonapi/taxonomy_vocabulary/taxonomy_vocabulary/' . $vocabulary
->uuid();
$response = $this
->request($endpoint, 'get', $this->token);
$body = $this
->decodeResponse($response);
$this
->assertEquals($vocabulary
->label(), $body['data']['attributes']['name']);
$vocabulary
->set('name', 'Still a vocab, just a different title');
$vocabulary
->save();
$response = $this
->request($endpoint, 'get', $this->token);
$body = $this
->decodeResponse($response);
$this
->assertEquals($vocabulary
->label(), $body['data']['attributes']['name']);
drupal_flush_all_caches();
$response = $this
->request('/jsonapi/taxonomy_term/im_a_vocab');
$this
->assertEquals(200, $response
->getStatusCode());
$name = 'zebra';
$term_uuid = $this->container
->get('uuid')
->generate();
$endpoint = '/jsonapi/taxonomy_term/im_a_vocab/' . $term_uuid;
$data = [
'data' => [
'type' => 'taxonomy_term--im_a_vocab',
'id' => $term_uuid,
'attributes' => [
'name' => $name,
'uuid' => $term_uuid,
],
'relationships' => [
'vid' => [
'data' => [
'type' => 'taxonomy_vocabulary--taxonomy_vocabulary',
'id' => $vocabulary
->uuid(),
],
],
],
],
];
$this
->request('/jsonapi/taxonomy_term/im_a_vocab', 'post', $this->token, $data);
$response = $this
->request($endpoint, 'get', $this->token);
$body = $this
->decodeResponse($response);
$this
->assertEquals($name, $body['data']['attributes']['name']);
$new_name = 'squid';
$data = [
'data' => [
'type' => 'taxonomy_term--im_a_vocab',
'id' => $term_uuid,
'attributes' => [
'name' => $new_name,
],
],
];
$this
->request($endpoint, 'patch', $this->token, $data);
$response = $this
->request($endpoint, 'get', $this->token);
$body = $this
->decodeResponse($response);
$this
->assertSame($new_name, $body['data']['attributes']['name']);
}
}