You are here

RestfulDiscoveryTestCase.test in RESTful 7.2

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

Contains RestfulDiscoveryTestCase

File

tests/RestfulDiscoveryTestCase.test
View source
<?php

/**
 * @file
 * Contains RestfulDiscoveryTestCase
 */
use Drupal\restful\Http\Request;
use Drupal\restful\Http\RequestInterface;

/**
 * Class RestfulDiscoveryTestCase.
 */
class RestfulDiscoveryTestCase extends RestfulCurlBaseTestCase {

  /**
   * {@inheritdoc}
   */
  public static function getInfo() {
    return array(
      'name' => 'Discovery',
      'description' => 'Test the discovery features.',
      'group' => 'RESTful',
    );
  }

  /**
   * {@inheritdoc}
   */
  public function setUp() {
    parent::setUp('restful_test');
  }

  /**
   * Test the discovery page.
   */
  public function testDiscoveryPage() {
    $request = $this
      ->httpRequest('api');
    $body = drupal_json_decode($request['body']);
    $this
      ->assertTrue(!empty($body['self']), 'The discovery plugin exposed the plugins.');

    // Disable the plugin and test a 404.
    variable_set('restful_enable_discovery_resource', FALSE);
    $request = $this
      ->httpRequest('api');
    $body = drupal_json_decode($request['body']);
    $this
      ->assertEqual($body['status'], 404, 'The discovery plugin is disabled.');
    variable_set('restful_enable_discovery_resource', TRUE);
  }

  /**
   * Test the headers populated in an OPTIONS request.
   */
  public function testOptionsMethod() {

    // 1. Assert Access-Control-Allow-Methods.
    $response = $this
      ->httpRequest('api/v1.4/test_articles', RequestInterface::METHOD_OPTIONS);
    $this
      ->assertTrue(strpos($response['headers'], sprintf('access-control-allow-methods: %s', implode(', ', array(
      RequestInterface::METHOD_HEAD,
      RequestInterface::METHOD_OPTIONS,
    )))) !== FALSE, 'Access-Control-Allow-Methods header is populated correctly.');

    // Make sure it returns the appropriate headers for every path.
    $response = $this
      ->httpRequest('api/v1.4/test_articles/1', RequestInterface::METHOD_OPTIONS);
    $this
      ->assertTrue(strpos($response['headers'], sprintf('access-control-allow-methods: %s', implode(', ', array(
      RequestInterface::METHOD_PATCH,
      RequestInterface::METHOD_DELETE,
      RequestInterface::METHOD_OPTIONS,
    )))) !== FALSE, 'Access-Control-Allow-Methods header is populated correctly for different paths.');

    // 2. Assert Accept.
    // List the content types the route accepts.
    $this
      ->assertTrue(strpos($response['headers'], 'accept: application/xml; charset=utf-8') !== FALSE, 'Accept header is populated correctly for configured formatter.');
    $response = $this
      ->httpRequest('api/v1.2/test_articles', RequestInterface::METHOD_OPTIONS);
    $this
      ->assertTrue(strpos($response['headers'], 'application/hal+json') !== FALSE, 'Accept header is populated correctly for non configured formatters.');
    $this
      ->assertTrue(strpos($response['headers'], 'application/json') !== FALSE, 'Accept header is populated correctly for non configured formatters.');
    $this
      ->assertTrue(strpos($response['headers'], 'application/vnd.api+json') !== FALSE, 'Accept header is populated correctly for non configured formatters.');
    $this
      ->assertTrue(strpos($response['headers'], 'application/drupal.single+json') !== FALSE, 'Accept header is populated correctly for non configured formatters.');
    $this
      ->assertTrue(strpos($response['headers'], 'application/xml') !== FALSE, 'Accept header is populated correctly for non configured formatters.');

    // 3. Assert Access-Control-Allow-Origin.
    $response = $this
      ->httpRequest('api/v1.4/test_articles', RequestInterface::METHOD_HEAD);
    $this
      ->assertTrue(strpos($response['headers'], 'access-control-allow-origin: *') !== FALSE, 'Accept header is populated correctly for non configured formatters.');

    // 4. Assert Access.
    $response = $this
      ->httpRequest('api/v1.4/test_articles/1', RequestInterface::METHOD_HEAD);
    $this
      ->assertTrue($response['code'], 400, 'Access is denied for unsupported HTTP methods.');
  }

  /**
   * Field discovery.
   */
  public function testFieldDiscovery() {

    // Add common fields, vocabulary and terms.
    restful_test_add_fields();

    // Create an entity.
    $entity = entity_create('entity_test', array(
      'name' => 'main',
      'label' => $this
        ->randomName(),
    ));
    $pid = $entity
      ->save();
    $handler = restful()
      ->getResourceManager()
      ->getPlugin('main:1.1');
    $handler
      ->setRequest(Request::create('api/v1.1/main/' . $pid, array(), RequestInterface::METHOD_OPTIONS));
    $handler
      ->setPath($pid);
    $formatter = restful()
      ->getFormatterManager()
      ->negotiateFormatter(NULL);
    $formatter
      ->setResource($handler);
    $result = $formatter
      ->prepare($handler
      ->process());
    $expected = array(
      'id' => array(
        'data' => array(
          'cardinality' => 1,
          'read_only' => TRUE,
          'type' => 'integer',
          'required' => TRUE,
        ),
        'info' => array(
          'description' => t('Base ID for the entity.'),
          'label' => t('ID'),
        ),
      ),
      'label' => array(
        'data' => array(
          'cardinality' => 1,
          'read_only' => FALSE,
          'type' => 'string',
          'required' => FALSE,
          'size' => 255,
        ),
        'form_element' => array(
          'allowed_values' => NULL,
          'type' => 'textfield',
          'default_value' => '',
          'placeholder' => '',
          'size' => 255,
          'description' => 'The label of the resource.',
          'title' => 'label',
        ),
        'info' => array(
          'description' => t('The label of the resource.'),
          'label' => t('Label'),
        ),
      ),
      'text_multiple' => array(
        'data' => array(
          'cardinality' => FIELD_CARDINALITY_UNLIMITED,
          'read_only' => FALSE,
          'type' => 'string',
          'size' => 255,
          'required' => FALSE,
        ),
        'form_element' => array(
          'allowed_values' => NULL,
          'default_value' => '',
          'placeholder' => t('This is helpful.'),
          'size' => 255,
          'type' => 'textfield',
          'description' => 'This field holds different text inputs.',
          'title' => 'text_multiple',
        ),
        'info' => array(
          'description' => t('This field holds different text inputs.'),
          'label' => t('Text multiple'),
        ),
      ),
    );
    foreach ($expected as $public_field => $discovery_info) {
      foreach (array(
        'data',
        'form_element',
        'info',
      ) as $section_name) {
        if (empty($result['data'][0][$public_field][$section_name]) && empty($expected[$public_field][$section_name])) {
          continue;
        }
        $this
          ->assertEqual($result['data'][0][$public_field][$section_name], $expected[$public_field][$section_name], format_string('The "@section" information is properly described for @field.', array(
          '@field' => $public_field,
          '@section' => $section_name,
        )));
      }
    }
  }

  /**
   * Field discovery allowed values.
   */
  public function testFieldDiscoveryAllowedValues() {

    // Add entity reference fields.
    restful_test_add_fields('node', 'article');
    $handler = restful()
      ->getResourceManager()
      ->getPlugin('test_articles:1.2');

    // Create 3 nodes.
    $expected_result = array();
    foreach (array(
      1,
      2,
      3,
    ) as $id) {
      $title = 'article/' . $id;
      $settings = array(
        'title' => $title,
        'type' => 'article',
      );
      $node = $this
        ->drupalCreateNode($settings);
      $expected_result[$node->nid] = $title;
    }

    // Set widget to select list.
    $instance = field_info_instance('node', 'entity_reference_single', 'article');
    $instance['widget']['type'] = 'options_select';
    field_update_instance($instance);
    $handler
      ->setRequest(Request::create('api/v1.2/test_articles', array(), RequestInterface::METHOD_OPTIONS));
    $handler
      ->setPath('');
    $formatter = restful()
      ->getFormatterManager()
      ->negotiateFormatter(NULL);
    $formatter
      ->setResource($handler);
    $result = $formatter
      ->prepare($handler
      ->process());
    $this
      ->assertEqual($result['data'][0]['entity_reference_single']['form_element']['allowed_values'], $expected_result);

    // Set widget to autocomplete.
    $instance['widget']['type'] = 'entityreference_autocomplete';
    field_update_instance($instance);

    // Invalidate public fields cache.
    $handler = restful()
      ->getResourceManager()
      ->getPluginCopy('test_articles:1.2');
    $handler
      ->setRequest(Request::create('api/v1.2/test_articles', array(), RequestInterface::METHOD_OPTIONS));
    $handler
      ->setPath('');
    $formatter = restful()
      ->getFormatterManager()
      ->negotiateFormatter(NULL);
    $formatter
      ->setResource($handler);
    $result = $formatter
      ->prepare($handler
      ->process());
    $this
      ->assertNull($result['data'][0]['entity_reference_single']['form_element']['allowed_values']);
  }

}

Classes

Namesort descending Description
RestfulDiscoveryTestCase Class RestfulDiscoveryTestCase.