You are here

RestfulHalJsonTestCase.test in RESTful 7.2

Same filename and directory in other branches
  1. 7 tests/RestfulHalJsonTestCase.test

Contains RestfulHalJsonTestCase

File

tests/RestfulHalJsonTestCase.test
View source
<?php

/**
 * @file
 * Contains RestfulHalJsonTestCase
 */
use Drupal\restful\Http\RequestInterface;
use Drupal\restful\Http\Request;
use Drupal\restful\Http\HttpHeaderBag;
class RestfulHalJsonTestCase extends RestfulCurlBaseTestCase {
  public static function getInfo() {
    return array(
      'name' => 'View HAL+JSON',
      'description' => 'Test the viewing of an entity in HAL+JSON format.',
      'group' => 'RESTful',
    );
  }
  public function setUp() {
    parent::setUp('restful_example', 'restful_test', 'entityreference');
    restful_test_add_fields();
  }

  /**
   * Test embedded resources.
   */
  public function testHalEmbeddedResources() {
    $user1 = $this
      ->drupalCreateUser();

    /* @var \Entity $entity1 */
    $entity1 = entity_create('entity_test', array(
      'name' => 'main',
      'uid' => $user1->uid,
    ));
    $entity1
      ->save();

    /* @var \Entity $entity2 */
    $entity2 = entity_create('entity_test', array(
      'name' => 'main',
      'uid' => $user1->uid,
    ));
    $entity2
      ->save();
    $entity3 = entity_create('entity_test', array(
      'name' => 'main',
      'uid' => $user1->uid,
    ));

    /* @var \EntityDrupalWrapper $wrapper */
    $wrapper = entity_metadata_wrapper('entity_test', $entity3);
    $text1 = $this
      ->randomName();
    $text2 = $this
      ->randomName();
    $wrapper->text_single
      ->set($text1);
    $wrapper->text_multiple
      ->set(array(
      $text1,
      $text2,
    ));
    $wrapper->entity_reference_single
      ->set($entity1);
    $wrapper->entity_reference_multiple[] = $entity1;
    $wrapper->entity_reference_multiple[] = $entity2;
    $wrapper
      ->save();
    $handler = restful()
      ->getResourceManager()
      ->getPlugin('main:1.1');
    $headers = new HttpHeaderBag(array(
      'X-API-Version' => 'v1.1',
      'Accept' => 'application/hal+json',
    ));
    $handler
      ->setRequest(Request::create('api/main/' . $wrapper
      ->getIdentifier(), array(), RequestInterface::METHOD_GET, $headers));
    $handler
      ->setPath($wrapper
      ->getIdentifier());
    $response = $handler
      ->process();
    $formatter_manager = restful()
      ->getFormatterManager();
    $formatter_manager
      ->setResource($handler);
    $formatter_result = $formatter_manager
      ->format($response);
    $results = drupal_json_decode($formatter_result);
    $this
      ->assertEqual(2, count($results['_embedded']));
    $this
      ->assertEqual($wrapper->entity_reference_multiple
      ->count(), count($results['_embedded']['hal:entity_reference_multiple_resource']));
    $this
      ->assertEqual($entity1->pid, count($results['_embedded']['hal:entity_reference_single_resource']['id']));
  }

}

Classes