public function StyleSerializerTest::testSerializerResponses

Checks the behavior of the Serializer callback paths and row plugins.

File

drupal/core/modules/rest/lib/Drupal/rest/Tests/Views/StyleSerializerTest.php, line 68
Contains \Drupal\rest\Tests\Views\StyleSerializerTest.

Class

StyleSerializerTest
Tests the serializer style plugin.

Namespace

Drupal\rest\Tests\Views

Code

public function testSerializerResponses() {

  // Test the serialize callback.
  $view = views_get_view('test_serializer_display_field');
  $view
    ->initDisplay();
  $this
    ->executeView($view);
  $actual_json = $this
    ->drupalGet('test/serialize/field', array(), array(
    'Accept: application/json',
  ));
  $this
    ->assertResponse(200);

  // Test the http Content-type.
  $headers = $this
    ->drupalGetHeaders();
  $this
    ->assertEqual($headers['content-type'], 'application/json', 'The header Content-type is correct.');
  $expected = array();
  foreach ($view->result as $row) {
    $expected_row = array();
    foreach ($view->field as $id => $field) {
      $expected_row[$id] = $field
        ->render($row);
    }
    $expected[] = $expected_row;
  }
  $this
    ->assertIdentical($actual_json, json_encode($expected), 'The expected JSON output was found.');

  // Test that the rendered output and the preview output are the same.
  $view
    ->destroy();
  $view
    ->setDisplay('rest_export_1');

  // Mock the request content type by setting it on the display handler.
  $view->display_handler
    ->setContentType('json');
  $output = $view
    ->preview();
  $this
    ->assertIdentical($actual_json, drupal_render($output), 'The expected JSON preview output was found.');

  // Test a 403 callback.
  $this
    ->drupalGet('test/serialize/denied');
  $this
    ->assertResponse(403);

  // Test the entity rows.
  $view = views_get_view('test_serializer_display_entity');
  $view
    ->initDisplay();
  $this
    ->executeView($view);

  // Get the serializer service.
  $serializer = drupal_container()
    ->get('serializer');
  $entities = array();
  foreach ($view->result as $row) {
    $entities[] = $row->_entity;
  }
  $expected = $serializer
    ->serialize($entities, 'json');
  $actual_json = $this
    ->drupalGet('test/serialize/entity', array(), array(
    'Accept: application/json',
  ));
  $this
    ->assertResponse(200);
  $this
    ->assertIdentical($actual_json, $expected, 'The expected JSON output was found.');
  $expected = $serializer
    ->serialize($entities, 'hal_json');
  $actual_json = $this
    ->drupalGet('test/serialize/entity', array(), array(
    'Accept: application/hal+json',
  ));
  $this
    ->assertIdentical($actual_json, $expected, 'The expected HAL output was found.');
}