public function JsonExtrasApiFunctionalTest::testWrite in JSON:API Extras 8
Same name and namespace in other branches
- 8.2 tests/src/Functional/JsonExtrasApiFunctionalTest.php \Drupal\Tests\jsonapi_extras\Functional\JsonExtrasApiFunctionalTest::testWrite()
Test POST/PATCH.
File
- tests/
src/ Functional/ JsonExtrasApiFunctionalTest.php, line 226
Class
- JsonExtrasApiFunctionalTest
- The test class for the main functionality.
Namespace
Drupal\Tests\jsonapi_extras\FunctionalCode
public function testWrite() {
$this
->createDefaultContent(0, 3, FALSE, FALSE, static::IS_NOT_MULTILINGUAL);
// 1. Successful post.
$collection_url = Url::fromRoute('jsonapi.articles.collection');
$body = [
'data' => [
'type' => 'articles',
'attributes' => [
'langcode' => 'en',
'title' => 'My custom title',
'default_langcode' => '1',
'body' => 'Custom value',
'timestamp' => '2017-12-23T08:45:17+0100',
],
'relationships' => [
'contentType' => [
'data' => [
'type' => 'contentTypes',
'id' => NodeType::load('article')
->uuid(),
],
],
'owner' => [
'data' => [
'type' => 'user--user',
'id' => User::load(1)
->uuid(),
],
],
'tags' => [
'data' => [
[
'type' => 'taxonomy_term--tags',
'id' => $this->tags[0]
->uuid(),
],
[
'type' => 'taxonomy_term--tags',
'id' => $this->tags[1]
->uuid(),
],
],
],
],
],
];
$response = $this
->request('POST', $collection_url, [
'body' => Json::encode($body),
'auth' => [
$this->user
->getUsername(),
$this->user->pass_raw,
],
'headers' => [
'Content-Type' => 'application/vnd.api+json',
],
]);
$created_response = Json::decode((string) $response
->getBody());
$this
->assertEquals(201, $response
->getStatusCode());
$this
->assertArrayHasKey('internalId', $created_response['data']['attributes']);
$this
->assertCount(2, $created_response['data']['relationships']['tags']['data']);
$this
->assertSame($created_response['data']['links']['self'], $response
->getHeader('Location')[0]);
$date = new \DateTime($body['data']['attributes']['timestamp']);
$created_node = Node::load($created_response['data']['attributes']['internalId']);
$this
->assertSame((int) $date
->format('U'), (int) $created_node
->get('field_timestamp')->value);
// 2. Successful relationships PATCH.
$uuid = $created_response['data']['id'];
$relationships_url = Url::fromUserInput('/api/articles/' . $uuid . '/relationships/tags');
$body = [
'data' => [
[
'type' => 'taxonomy_term--tags',
'id' => $this->tags[2]
->uuid(),
],
],
];
$response = $this
->request('POST', $relationships_url, [
'body' => Json::encode($body),
'auth' => [
$this->user
->getUsername(),
$this->user->pass_raw,
],
'headers' => [
'Content-Type' => 'application/vnd.api+json',
],
]);
$created_response = Json::decode((string) $response
->getBody());
$this
->assertCount(3, $created_response['data']);
}