You are here

class RestfulListTestCase in RESTful 7.2

Same name and namespace in other branches
  1. 7 tests/RestfulListTestCase.test \RestfulListTestCase

Class RestfulListTestCase.

Hierarchy

Expanded class hierarchy of RestfulListTestCase

File

tests/RestfulListTestCase.test, line 16
Contains RestfulListTestCase.

View source
class RestfulListTestCase extends RestfulCurlBaseTestCase {

  /**
   * {@inheritdoc}
   */
  public static function getInfo() {
    return array(
      'name' => 'List entities',
      'description' => 'Test the listing of entities.',
      'group' => 'RESTful',
    );
  }

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

  /**
   * Test the sorting of entities.
   */
  public function testSort() {

    // Allow the anonymous users access to the author field.
    user_role_change_permissions(DRUPAL_ANONYMOUS_RID, array(
      'access user profiles' => TRUE,
    ));
    $user1 = $this
      ->drupalCreateUser();
    $user2 = $this
      ->drupalCreateUser();
    $settings = array(
      'type' => 'article',
    );
    $info = array(
      'abc' => $user1->uid,
      'xyz' => $user1->uid,
      'efg' => $user2->uid,
    );
    $nodes = array();
    foreach ($info as $title => $uid) {
      $settings['title'] = $title;
      $settings['uid'] = $uid;
      $node = $this
        ->drupalCreateNode($settings);
      $nodes[$title] = $node->nid;
    }

    // Add unpublished node, to confirm it is not listed.
    $settings['status'] = NODE_NOT_PUBLISHED;
    $this
      ->drupalCreateNode($settings);
    $resource_manager = restful()
      ->getResourceManager();
    $handler = $resource_manager
      ->getPlugin('articles:1.0');
    $query['fields'] = 'id,label';
    $handler
      ->setRequest(Request::create('', $query, RequestInterface::METHOD_GET));
    $handler
      ->setPath('');

    // No sorting (default sorting).
    $result = drupal_json_decode(restful()
      ->getFormatterManager()
      ->format($handler
      ->process(), 'json'));
    $result = $result['data'];
    $expected_result = array(
      array(
        'id' => $nodes['abc'],
        'label' => 'abc',
      ),
      array(
        'id' => $nodes['xyz'],
        'label' => 'xyz',
      ),
      array(
        'id' => $nodes['efg'],
        'label' => 'efg',
      ),
    );
    $this
      ->assertEqual($result, $expected_result, 'No sorting (default sorting).');

    // Sort by ID descending.
    $query['sort'] = '-id';
    $handler
      ->setRequest(Request::create('', $query, RequestInterface::METHOD_GET));
    $result = drupal_json_decode(restful()
      ->getFormatterManager()
      ->format($handler
      ->process(), 'json'));
    $result = $result['data'];
    $expected_result = array(
      array(
        'id' => $nodes['efg'],
        'label' => 'efg',
      ),
      array(
        'id' => $nodes['xyz'],
        'label' => 'xyz',
      ),
      array(
        'id' => $nodes['abc'],
        'label' => 'abc',
      ),
    );
    $this
      ->assertEqual($result, $expected_result, 'Sort by ID descending.');

    // Sort by label ascending.
    $query['sort'] = 'label';
    $handler
      ->setRequest(Request::create('', $query, RequestInterface::METHOD_GET));
    $result = drupal_json_decode(restful()
      ->getFormatterManager()
      ->format($handler
      ->process(), 'json'));
    $result = $result['data'];
    $expected_result = array(
      array(
        'id' => $nodes['abc'],
        'label' => 'abc',
      ),
      array(
        'id' => $nodes['efg'],
        'label' => 'efg',
      ),
      array(
        'id' => $nodes['xyz'],
        'label' => 'xyz',
      ),
    );
    $this
      ->assertEqual($result, $expected_result, 'Sort by label ascending.');

    // Sort by label and by ID. For that we add another node titled "abc".
    $settings = array(
      'type' => 'article',
      'title' => 'abc',
    );
    $node = $this
      ->drupalCreateNode($settings);
    $query['sort'] = 'label,id';
    $handler
      ->setRequest(Request::create('', $query, RequestInterface::METHOD_GET));
    $result = drupal_json_decode(restful()
      ->getFormatterManager()
      ->format($handler
      ->process(), 'json'));
    $result = $result['data'];
    $expected_result = array(
      array(
        'id' => $nodes['abc'],
        'label' => 'abc',
      ),
      array(
        'id' => $node->nid,
        'label' => 'abc',
      ),
      array(
        'id' => $nodes['efg'],
        'label' => 'efg',
      ),
      array(
        'id' => $nodes['xyz'],
        'label' => 'xyz',
      ),
    );
    $this
      ->assertEqual($result, $expected_result, 'Sort by ID and by label.');

    // Test default sorting from plugin definition; by label, then by reverse
    // id.
    $handler = $resource_manager
      ->getPlugin('test_articles:1.1');
    unset($query['sort']);
    $handler
      ->setRequest(Request::create('', $query, RequestInterface::METHOD_GET));
    $result = drupal_json_decode(restful()
      ->getFormatterManager()
      ->format($handler
      ->process(), 'json'));
    $result = $result['data'];
    $expected_result = array(
      array(
        'id' => $node->nid,
        'label' => 'abc',
        'self' => $handler
          ->versionedUrl($node->nid),
      ),
      array(
        'id' => $nodes['abc'],
        'label' => 'abc',
        'self' => $handler
          ->versionedUrl($nodes['abc']),
      ),
      array(
        'id' => $nodes['efg'],
        'label' => 'efg',
        'self' => $handler
          ->versionedUrl($nodes['efg']),
      ),
      array(
        'id' => $nodes['xyz'],
        'label' => 'xyz',
        'self' => $handler
          ->versionedUrl($nodes['xyz']),
      ),
    );
    $this
      ->assertEqual($result, $expected_result, 'Default sort by ID and by label.');

    // Test that the default sort can be overridden.
    $query['sort'] = 'id';
    $handler
      ->setRequest(Request::create('', $query, RequestInterface::METHOD_GET));
    $handler
      ->setPath('');
    $result = drupal_json_decode(restful()
      ->getFormatterManager()
      ->format($handler
      ->process(), 'json'));
    $result = $result['data'];
    $expected_result = array(
      array(
        'id' => $nodes['abc'],
        'label' => 'abc',
        'self' => $handler
          ->versionedUrl($nodes['abc']),
      ),
      array(
        'id' => $nodes['xyz'],
        'label' => 'xyz',
        'self' => $handler
          ->versionedUrl($nodes['xyz']),
      ),
      array(
        'id' => $nodes['efg'],
        'label' => 'efg',
        'self' => $handler
          ->versionedUrl($nodes['efg']),
      ),
      array(
        'id' => $node->nid,
        'label' => 'abc',
        'self' => $handler
          ->versionedUrl($node->nid),
      ),
    );
    $this
      ->assertEqual($result, $expected_result, 'Sort by ID, overriding default sort.');

    // Illegal sort property.
    $query['sort'] = 'wrong_key';
    $handler
      ->setRequest(Request::create('', $query, RequestInterface::METHOD_GET));
    $handler
      ->setPath('');
    try {
      restful()
        ->getFormatterManager()
        ->format($handler
        ->process(), 'json');
      $this
        ->fail('Illegal sort property used.');
    } catch (BadRequestException $e) {
      $this
        ->pass('Exception thrown on illegal sort property.');
    }

    // Illegal sort property, descending.
    $query['sort'] = '-wrong_key';
    $handler
      ->setRequest(Request::create('', $query, RequestInterface::METHOD_GET));
    $handler
      ->setPath('');
    try {
      restful()
        ->getFormatterManager()
        ->format($handler
        ->process(), 'json');
      $this
        ->fail('Illegal sort property, descending, used.');
    } catch (BadRequestException $e) {
      $this
        ->pass('Exception thrown on illegal sort property, descending.');
    }

    // Test valid sort with sort params disabled.
    $resource_manager
      ->clearPluginCache($handler
      ->getPluginId());
    $plugin_definition = $handler
      ->getPluginDefinition();
    $plugin_definition['dataProvider']['urlParams'] = array(
      'filter' => TRUE,
      'sort' => FALSE,
      'range' => TRUE,
    );
    $handler
      ->setPluginDefinition($plugin_definition);

    // Re-instantiate the data provider.
    $handler
      ->setDataProvider(NULL);
    $query['sort'] = 'label,id';
    $handler
      ->setRequest(Request::create('', $query, RequestInterface::METHOD_GET));
    $handler
      ->setPath('');
    try {
      restful()
        ->getFormatterManager()
        ->format($handler
        ->process(), 'json');
      $this
        ->fail('Exception not raised for disabled sort parameter.');
    } catch (UnprocessableEntityException $e) {
      $this
        ->pass('Exception raised for disabled sort parameter.');
    }

    // Test the range overrides.
    unset($query['sort']);
    $query['range'] = 2;
    $handler
      ->setRequest(Request::create('', $query, RequestInterface::METHOD_GET));
    $handler
      ->setPath('');
    $result = drupal_json_decode(restful()
      ->getFormatterManager()
      ->format($handler
      ->process(), 'json'));
    $result = $result['data'];
    $this
      ->assertEqual(count($result), $query['range'], 'Range parameter overridden correctly');

    // Test the max cap in the the annotation configuration.
    $resource_manager
      ->clearPluginCache($handler
      ->getPluginId());
    $plugin_definition = $handler
      ->getPluginDefinition();
    $plugin_definition['range'] = 1;
    $handler
      ->setPluginDefinition($plugin_definition);
    $query['range'] = 2;
    $result = drupal_json_decode(restful()
      ->getFormatterManager()
      ->format($handler
      ->doGet('', $query), 'json'));
    $this
      ->assertEqual(count($result['data']), $query['range'], 'Range is limited to the configured maximum.');

    // Test invalid range.
    $query['range'] = $this
      ->randomName();
    $handler
      ->setRequest(Request::create('', $query, RequestInterface::METHOD_GET));
    $handler
      ->setPath('');
    try {
      restful()
        ->getFormatterManager()
        ->format($handler
        ->process(), 'json');
      $this
        ->fail('Exception not raised on invalid range parameter.');
    } catch (BadRequestException $e) {
      $this
        ->pass('Exception raised on invalid range parameter.');
    }

    // Test valid range with range params disabled.
    $resource_manager
      ->clearPluginCache($handler
      ->getPluginId());
    $plugin_definition = $handler
      ->getPluginDefinition();
    $plugin_definition['dataProvider']['urlParams'] = array(
      'filter' => TRUE,
      'sort' => TRUE,
      'range' => FALSE,
    );

    // Unset the previously added range.
    unset($plugin_definition['range']);
    $handler
      ->setPluginDefinition($plugin_definition);

    // Re-instantiate the data provider.
    $handler
      ->setDataProvider(NULL);
    $query['range'] = 2;
    $handler
      ->setRequest(Request::create('', $query, RequestInterface::METHOD_GET));
    $handler
      ->setPath('');
    try {
      restful()
        ->getFormatterManager()
        ->format($handler
        ->process(), 'json');
      $this
        ->fail('Exception not raised for disabled range parameter.');
    } catch (UnprocessableEntityException $e) {
      $this
        ->pass('Exception raised for disabled range parameter.');
    }

    // Sort by an entity metadata wrapper property that is different from the
    // DB column name.
    $handler = $resource_manager
      ->getPlugin('articles:1.5');
    $query = array(
      'sort' => '-user',
    );
    $handler
      ->setRequest(Request::create('', $query, RequestInterface::METHOD_GET));
    $handler
      ->setPath('');
    $result = drupal_json_decode(restful()
      ->getFormatterManager()
      ->format($handler
      ->process(), 'json'));
    $result = $result['data'];
    $this
      ->assertEqual($result[0]['user']['id'], 3, 'List sorted by the "author" entity metadata wrapper property, which maps to the "uid" DB column name.');
    $query = array(
      'sort' => 'static',
    );
    $handler
      ->setRequest(Request::create('', $query, RequestInterface::METHOD_GET));
    $handler
      ->setPath('');
    try {
      restful()
        ->getFormatterManager()
        ->format($handler
        ->process(), 'json');
      $this
        ->fail('Exception not thrown for invalid sort.');
    } catch (BadRequestException $e) {
      $this
        ->pass('Exception thrown for invalid sort.');
    }
  }

  /**
   * Test filtering.
   */
  public function testFilter() {
    $resource_manager = restful()
      ->getResourceManager();
    $user1 = $this
      ->drupalCreateUser();
    $user2 = $this
      ->drupalCreateUser();
    $this
      ->addIntegerFields();
    $info = array(
      array(
        'title' => 'abc',
        'integer_single' => 1,
        'integer_multiple' => array(
          1,
          2,
          3,
        ),
        'uid' => $user1->uid,
      ),
      array(
        'title' => 'another abc',
        'integer_single' => 5,
        'integer_multiple' => array(
          3,
          4,
          5,
        ),
        'uid' => $user1->uid,
      ),
      array(
        'title' => 'last',
        'integer_single' => NULL,
        'integer_multiple' => array(),
        'uid' => $user2->uid,
      ),
    );
    $nodes = array();
    foreach ($info as $row) {
      $title = $row['title'];
      $settings = array(
        'type' => 'article',
        'title' => $title,
      );
      $settings['integer_single'][LANGUAGE_NONE][0]['value'] = $row['integer_single'];
      foreach ($row['integer_multiple'] as $key => $value) {
        $settings['integer_multiple'][LANGUAGE_NONE][$key]['value'] = $value;
      }
      $settings['uid'] = $row['uid'];
      $node = $this
        ->drupalCreateNode($settings);
      $nodes[$title] = $node->nid;
    }
    $handler = $resource_manager
      ->getPlugin('test_articles:1.2');
    $fields = array(
      'id',
      'label',
      'integer_single',
      'intger_multiple',
    );
    $query['fields'] = implode(',', $fields);

    // Single value property.
    $query['filter'] = array(
      'label' => 'abc',
    );
    $handler
      ->setRequest(Request::create('', $query, RequestInterface::METHOD_GET));
    $handler
      ->setPath('');
    $result = drupal_json_decode(restful()
      ->getFormatterManager()
      ->format($handler
      ->process(), 'json'));
    $result = $result['data'];
    $this
      ->assertEqual($result[0]['id'], $nodes['abc'], 'Filter list by single value property.');

    // Assert count is correct.
    $formatter_handler = restful()
      ->getFormatterManager()
      ->getPlugin('hal_json');
    $instance_configuration = $formatter_handler
      ->getConfiguration();
    $formatter_handler
      ->setConfiguration(array_merge($instance_configuration ?: array(), array(
      'resource' => $handler,
    )));
    $output = $formatter_handler
      ->prepare($result);
    $this
      ->assertEqual($output['count'], 1, '"count" property is correct.');

    // Single value field.
    $resource_manager
      ->clearPluginCache($handler
      ->getPluginId());
    $handler = $resource_manager
      ->getPlugin('test_articles:1.2');
    $query['filter'] = array(
      'integer_single' => '1',
    );
    $handler
      ->setRequest(Request::create('', $query, RequestInterface::METHOD_GET));
    $handler
      ->setPath('');
    $result = drupal_json_decode(restful()
      ->getFormatterManager()
      ->format($handler
      ->process(), 'json'));
    $result = $result['data'];
    $this
      ->assertEqual($result[0]['id'], $nodes['abc'], 'Filter list by Single value field.');

    // LIKE operator.
    $input['filter'] = array(
      'label' => array(
        'value' => '%nothe%',
        'operator' => 'LIKE',
      ),
    );
    $result = drupal_json_decode(restful()
      ->getFormatterManager()
      ->format($handler
      ->doGet('', $input), 'json'));
    $result = $result['data'];
    $this
      ->assertEqual($result[0]['id'], $nodes['another abc'], 'Filter list using LIKE operator.');

    // STARTS_WITH operator.
    $input['filter'] = array(
      'label' => array(
        'value' => 'las',
        'operator' => 'STARTS_WITH',
      ),
    );
    $result = drupal_json_decode(restful()
      ->getFormatterManager()
      ->format($handler
      ->doGet('', $input), 'json'));
    $result = $result['data'];
    $this
      ->assertEqual($result[0]['id'], $nodes['last'], 'Filter list using STARTS_WITH operator.');

    // CONTAINS operator.
    $input['filter'] = array(
      'label' => array(
        'value' => 'bc',
        'operator' => 'CONTAINS',
      ),
    );
    $result = drupal_json_decode(restful()
      ->getFormatterManager()
      ->format($handler
      ->doGet('', $input), 'json'));
    $result = $result['data'];

    // Sort the results before checking it.
    usort($result, function ($a, $b) {
      return strcmp($a['label'], $b['label']);
    });
    $this
      ->assertEqual($result[0]['id'], $nodes['abc'], 'Filter list using CONTAINS operator.');
    $this
      ->assertEqual($result[1]['id'], $nodes['another abc'], 'Filter list using CONTAINS operator.');

    // Multiple value field.
    $query['filter'] = array(
      'integer_multiple' => array(
        'value' => array(
          4,
          5,
        ),
        'operator' => 'BETWEEN',
      ),
    );
    $handler
      ->setRequest(Request::create('', $query, RequestInterface::METHOD_GET));
    $handler
      ->setPath('');
    $result = drupal_json_decode(restful()
      ->getFormatterManager()
      ->format($handler
      ->process(), 'json'));
    $result = $result['data'];
    $this
      ->assertEqual($result[0]['id'], $nodes['another abc'], 'Filter list by multiple value field.');

    // Invalid key.
    $query['filter'] = array(
      'invalid_key' => '3',
    );
    $handler
      ->setRequest(Request::create('', $query, RequestInterface::METHOD_GET));
    $handler
      ->setPath('');
    try {
      restful()
        ->getFormatterManager()
        ->format($handler
        ->process(), 'json');
      $this
        ->fail('No exception was thrown on invalid key for filter.');
    } catch (BadRequestException $e) {
      $this
        ->pass('Correct exception was thrown on invalid key for filter.');
    } catch (\Exception $e) {
      $this
        ->fail('Incorrect exception was thrown on invalid key for filter.');
    }

    // Assert filtering doesn't apply for non-list request
    // (e.g. /api/v1.0/articles/1?filter[label]=foo), as this might be called
    // from a formatter plugin, after RESTful's error handling has finished.
    $query_string = array(
      'filter' => array(
        'invalid-key' => 'foo',
      ),
    );
    $result = $this
      ->httpRequest('api/v1.0/articles/1', RequestInterface::METHOD_GET, $query_string);
    $this
      ->assertEqual($result['code'], '200', 'Invalid filter key was ignored on non-list query.');

    // Test multiple filters on the same field.
    $query = array(
      'filter' => array(
        'integer_single' => array(
          'value' => array(
            1,
            4,
          ),
          'operator' => array(
            '>',
            '<>',
          ),
        ),
      ),
    );
    $handler
      ->setRequest(Request::create('', $query, RequestInterface::METHOD_GET));
    $handler
      ->setPath('');
    $result = drupal_json_decode(restful()
      ->getFormatterManager()
      ->format($handler
      ->process(), 'json'));
    $result = $result['data'];
    $this
      ->assertEqual($nodes['another abc'], $result[0]['id']);
    $query = array(
      'filter' => array(
        'integer_single' => array(
          'value' => array(
            1,
            5,
          ),
          'operator' => array(
            '>',
            '<>',
          ),
        ),
      ),
    );
    $handler
      ->setRequest(Request::create('', $query, RequestInterface::METHOD_GET));
    $handler
      ->setPath('');
    $result = drupal_json_decode(restful()
      ->getFormatterManager()
      ->format($handler
      ->process(), 'json'));
    $result = $result['data'];
    $this
      ->assertEqual($result, array());
    $query = array(
      'filter' => array(
        'integer_multiple' => array(
          'value' => array(
            3,
            4,
          ),
        ),
      ),
    );
    $handler
      ->setRequest(Request::create('', $query, RequestInterface::METHOD_GET));
    $handler
      ->setPath('');
    $result = drupal_json_decode(restful()
      ->getFormatterManager()
      ->format($handler
      ->process(), 'json'));
    $result = $result['data'];
    $this
      ->assertEqual($nodes['another abc'], $result[0]['id']);

    // Test valid filter with filter params disabled.
    $resource_manager
      ->clearPluginCache($handler
      ->getPluginId());
    $plugin_definition = $handler
      ->getPluginDefinition();
    $plugin_definition['dataProvider']['urlParams'] = array(
      'filter' => FALSE,
      'sort' => TRUE,
      'range' => TRUE,
    );
    $handler
      ->setPluginDefinition($plugin_definition);
    $handler
      ->setDataProvider(NULL);
    $query['filter'] = array(
      'label' => 'abc',
    );
    $handler
      ->setRequest(Request::create('', $query, RequestInterface::METHOD_GET));
    $handler
      ->setPath('');
    try {
      restful()
        ->getFormatterManager()
        ->format($handler
        ->process(), 'json');
      $this
        ->fail('Exception not raised for disabled filter parameter.');
    } catch (UnprocessableEntityException $e) {
      $this
        ->pass('Exception raised for disabled filter parameter.');
    }

    // Filter by an entity metadata wrapper property that is different from the
    // DB column name.
    $handler = $resource_manager
      ->getPlugin('articles:1.5');
    $query = array(
      'filter' => array(
        'user' => array(
          'value' => $user1->uid,
        ),
      ),
    );
    $handler
      ->setRequest(Request::create('', $query, RequestInterface::METHOD_GET));
    $handler
      ->setPath('');
    $result = drupal_json_decode(restful()
      ->getFormatterManager()
      ->format($handler
      ->process(), 'json'));
    $result = $result['data'];
    $this
      ->assertEqual(count($result), 2, 'List filtered by the "author" entity metadata wrapper property, which maps to the "uid" DB column name.');
    $query = array(
      'filter' => array(
        'static' => array(
          'value' => 0,
        ),
      ),
    );
    $handler
      ->setRequest(Request::create('', $query, RequestInterface::METHOD_GET));
    $handler
      ->setPath('');
    try {
      restful()
        ->getFormatterManager()
        ->format($handler
        ->process(), 'json');
      $this
        ->fail('Illegal filter property used.');
    } catch (BadRequestException $e) {
      $this
        ->pass('Exception thrown on illegal filter property.');
    }
  }

  /**
   * Test pagination.
   */
  public function testPagination() {
    $resource_manager = restful()
      ->getResourceManager();
    foreach (range(1, 9) as $key) {
      $settings = array(
        'type' => 'article',
        'title' => $key,
      );
      $this
        ->drupalCreateNode($settings);
    }
    $handler = $resource_manager
      ->getPlugin('articles:1.0');
    $formatter_handler = restful()
      ->getFormatterManager()
      ->negotiateFormatter('');
    $instance_configuration = $formatter_handler
      ->getConfiguration();
    $formatter_handler
      ->setConfiguration(array_merge($instance_configuration ?: array(), array(
      'resource' => $handler,
    )));

    // Set a smaller range for the pagination.
    $data_provider = $handler
      ->getDataProvider();
    $data_provider
      ->setRange(3);

    // Check pagination of first page.
    $handler
      ->setRequest(Request::create('', array(
      'page' => 1,
    ), RequestInterface::METHOD_GET));
    $handler
      ->setPath('');
    $result = drupal_json_decode($formatter_handler
      ->format($handler
      ->process()));
    $this
      ->assertEqual(count($result['data']), 3);
    $this
      ->assertTrue($result['next'], '"Next" link exists on the first page.');
    $this
      ->assertTrue(empty($result['previous']), '"Previous" link does not exist on the first page.');

    // Check pagination of middle pages.
    $handler
      ->setRequest(Request::create('', array(
      'page' => 2,
    ), RequestInterface::METHOD_GET));
    $result = drupal_json_decode($formatter_handler
      ->format($handler
      ->process()));
    $this
      ->assertTrue($result['next'], '"Next" link exists on the middle page.');
    $this
      ->assertEqual($result['next']['href'], $handler
      ->versionedUrl('', array(
      'query' => array(
        'page' => array(
          'number' => 3,
        ),
      ),
    )));
    $this
      ->assertTrue($result['previous'], '"Previous" link exists on the middle page.');
    $this
      ->assertEqual($result['previous']['href'], $handler
      ->versionedUrl('', array(
      'query' => array(
        'page' => array(
          'number' => 1,
        ),
      ),
    )));

    // Check pagination of last page.
    $handler
      ->setRequest(Request::create('', array(
      'page' => 3,
    ), RequestInterface::METHOD_GET));
    $result = drupal_json_decode($formatter_handler
      ->format($handler
      ->process()));
    $this
      ->assertTrue(empty($result['next']), '"Next" link does not exist on the last page.');
    $this
      ->assertTrue($result['previous'], '"Previous" link exists on the last page.');

    // Check other query strings are retained in the _links.
    $handler
      ->setRequest(Request::create('', array(
      'page' => 3,
      'sort' => '-id',
    ), RequestInterface::METHOD_GET));
    $result = drupal_json_decode($formatter_handler
      ->format($handler
      ->process()));
    $this
      ->assertTrue(strpos($result['previous']['href'], 'sort=-id'), 'Query strings are retained in the _links.');

    // Check pagination with non-numeric value.
    $handler
      ->setRequest(Request::create('', array(
      'page' => 'string',
    ), RequestInterface::METHOD_GET));
    try {
      restful()
        ->getFormatterManager()
        ->format($handler
        ->process(), 'json');
      $this
        ->fail('No exception thrown for pagination with non-numeric value.');
    } catch (BadRequestException $e) {
      $this
        ->pass('Correct exception thrown for pagination with non-numeric value.');
    } catch (\Exception $e) {
      $this
        ->fail('Incorrect exception thrown for pagination with non-numeric value.');
    }

    // Check pagination with 0 value.
    $handler
      ->setRequest(Request::create('', array(
      'page' => 0,
    ), RequestInterface::METHOD_GET));
    try {
      restful()
        ->getFormatterManager()
        ->format($handler
        ->process(), 'json');
      $this
        ->fail('No exception thrown for pagination with 0 value.');
    } catch (BadRequestException $e) {
      $this
        ->pass('Correct exception thrown for pagination with 0 value.');
    } catch (\Exception $e) {
      $this
        ->fail('Incorrect exception thrown for pagination with 0 value.');
    }

    // Check pagination with high number, where there are not items, yielded no
    // results, but is a valid call.
    $handler
      ->setRequest(Request::create('', array(
      'page' => 100,
    ), RequestInterface::METHOD_GET));
    $result = drupal_json_decode($formatter_handler
      ->format($handler
      ->process()));
    $this
      ->assertEqual($result['data'], array(), 'pagination with high number, where there are not items yielded no results.');

    // Check total number of results.
    $handler
      ->setRequest(Request::create('', array(
      'page' => 3,
    ), RequestInterface::METHOD_GET));
    $result = drupal_json_decode($formatter_handler
      ->format($handler
      ->process()));
    $this
      ->assertEqual($result['count'], 9, 'Total count exists and is correct.');
  }

  /**
   * Helper function; Add single and multiple integer fields.
   */
  private function addIntegerFields() {

    // Integer - single.
    $field = array(
      'field_name' => 'integer_single',
      'type' => 'number_integer',
      'entity_types' => array(
        'node',
      ),
      'cardinality' => 1,
    );
    field_create_field($field);
    $instance = array(
      'field_name' => 'integer_single',
      'bundle' => 'article',
      'entity_type' => 'node',
      'label' => t('Integer single'),
    );
    field_create_instance($instance);

    // Integer - multiple.
    $field = array(
      'field_name' => 'integer_multiple',
      'type' => 'number_integer',
      'entity_types' => array(
        'node',
      ),
      'cardinality' => FIELD_CARDINALITY_UNLIMITED,
    );
    field_create_field($field);
    $instance = array(
      'field_name' => 'integer_multiple',
      'bundle' => 'article',
      'entity_type' => 'node',
      'label' => t('Integer multiple'),
    );
    field_create_instance($instance);
  }

  /**
   * Test error handling when no access is granted to an entity in a list.
   */
  public function testAccessHandling() {
    $resource_manager = restful()
      ->getResourceManager();
    $settings = array(
      'type' => 'article',
    );
    $node1 = $this
      ->drupalCreateNode($settings);
    $node2 = $this
      ->drupalCreateNode($settings);
    $node3 = $this
      ->drupalCreateNode($settings);
    $user1 = $this
      ->drupalCreateUser();

    // Deny access via hook_node_access() to a specific node.
    restful_test_deny_access_node($node2->nid);
    variable_set('restful_show_access_denied', TRUE);
    $handler = $resource_manager
      ->getPlugin('articles:1.0');
    $handler
      ->setAccount($user1);
    $handler
      ->setRequest(Request::create('api/articles/v1.0'));
    $handler
      ->setPath('');
    $result = drupal_json_decode(restful()
      ->getFormatterManager()
      ->format($handler
      ->process(), 'json'));
    $this
      ->assertEqual(count($result['data']), 2, 'List returned and ignored un-accessible entity.');
    $this
      ->assertEqual(count($result['denied']), 1, 'A denied entity was detected.');

    // Get a list with specific IDs.
    $ids = array(
      $node1->nid,
      $node2->nid,
      $node3->nid,
    );
    $handler
      ->setRequest(Request::create('api/articles/v1.0' . implode(',', $ids)));
    $handler
      ->setPath(implode(',', $ids));
    $result = drupal_json_decode(restful()
      ->getFormatterManager()
      ->format($handler
      ->process(), 'json'));
    $this
      ->assertEqual(count($result['data']), 2, 'List of specific items returned and ignored un-accessible entity.');
    $this
      ->assertEqual(count($result['denied']), 1, 'A denied entity was detected.');
  }

  /**
   * Test node count and pager when there are unpublished nodes.
   */
  public function testCountWithUnpublished() {
    foreach (range(1, 9) as $key) {
      $settings = array(
        'type' => 'article',
        'title' => $key,
        'status' => NODE_PUBLISHED,
      );
      $this
        ->drupalCreateNode($settings);
    }
    foreach (range(1, 3) as $key) {
      $settings = array(
        'type' => 'article',
        'title' => $key,
        'status' => NODE_NOT_PUBLISHED,
      );
      $this
        ->drupalCreateNode($settings);
    }
    $handler = restful()
      ->getResourceManager()
      ->getPlugin('articles:1.0');
    $formatter = restful()
      ->getFormatterManager()
      ->getPlugin('json');
    $formatter
      ->setResource($handler);

    // Set a range for pagination to check only .
    $handler
      ->getDataProvider()
      ->setRange(9);

    // Check pagination of first page.
    $result = $handler
      ->doGet('', array(
      'page' => 1,
    ));
    $output = drupal_json_decode($formatter
      ->format($result));
    $this
      ->assertEqual(count($result), 9, 'Number of results displayed');
    $this
      ->assertEqual(count($result), $handler
      ->getDataProvider()
      ->count(), 'Count of results takes into account unpublished nodes');
    $this
      ->assertTrue(empty($output['next']), '"Next" link does not exist on the first page.');
    $this
      ->assertTrue(empty($output['previous']), '"Previous" link does not exist on the first page.');
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DrupalTestCase::$assertions protected property Assertions thrown in that test case.
DrupalTestCase::$databasePrefix protected property The database prefix of this test run.
DrupalTestCase::$originalFileDirectory protected property The original file directory, before it was changed for testing purposes.
DrupalTestCase::$results public property Current results of this test case.
DrupalTestCase::$setup protected property Flag to indicate whether the test has been set up.
DrupalTestCase::$setupDatabasePrefix protected property
DrupalTestCase::$setupEnvironment protected property
DrupalTestCase::$skipClasses protected property This class is skipped when looking for the source of an assertion.
DrupalTestCase::$testId protected property The test run ID.
DrupalTestCase::$timeLimit protected property Time limit for the test.
DrupalTestCase::$useSetupInstallationCache public property Whether to cache the installation part of the setUp() method.
DrupalTestCase::$useSetupModulesCache public property Whether to cache the modules installation part of the setUp() method.
DrupalTestCase::$verboseDirectoryUrl protected property URL to the verbose output file directory.
DrupalTestCase::assert protected function Internal helper: stores the assert.
DrupalTestCase::assertEqual protected function Check to see if two values are equal.
DrupalTestCase::assertFalse protected function Check to see if a value is false (an empty string, 0, NULL, or FALSE).
DrupalTestCase::assertIdentical protected function Check to see if two values are identical.
DrupalTestCase::assertNotEqual protected function Check to see if two values are not equal.
DrupalTestCase::assertNotIdentical protected function Check to see if two values are not identical.
DrupalTestCase::assertNotNull protected function Check to see if a value is not NULL.
DrupalTestCase::assertNull protected function Check to see if a value is NULL.
DrupalTestCase::assertTrue protected function Check to see if a value is not false (not an empty string, 0, NULL, or FALSE).
DrupalTestCase::deleteAssert public static function Delete an assertion record by message ID.
DrupalTestCase::error protected function Fire an error assertion. 1
DrupalTestCase::errorHandler public function Handle errors during test runs. 1
DrupalTestCase::exceptionHandler protected function Handle exceptions.
DrupalTestCase::fail protected function Fire an assertion that is always negative.
DrupalTestCase::generatePermutations public static function Converts a list of possible parameters into a stack of permutations.
DrupalTestCase::getAssertionCall protected function Cycles through backtrace until the first non-assertion method is found.
DrupalTestCase::getDatabaseConnection public static function Returns the database connection to the site running Simpletest.
DrupalTestCase::insertAssert public static function Store an assertion from outside the testing context.
DrupalTestCase::pass protected function Fire an assertion that is always positive.
DrupalTestCase::randomName public static function Generates a random string containing letters and numbers.
DrupalTestCase::randomString public static function Generates a random string of ASCII characters of codes 32 to 126.
DrupalTestCase::run public function Run all tests in this class.
DrupalTestCase::verbose protected function Logs a verbose message in a text file.
DrupalWebTestCase::$additionalCurlOptions protected property Additional cURL options.
DrupalWebTestCase::$content protected property The content of the page currently loaded in the internal browser.
DrupalWebTestCase::$cookieFile protected property The current cookie file used by cURL.
DrupalWebTestCase::$cookies protected property The cookies of the page currently loaded in the internal browser.
DrupalWebTestCase::$curlHandle protected property The handle of the current cURL connection.
DrupalWebTestCase::$drupalSettings protected property The value of the Drupal.settings JavaScript variable for the page currently loaded in the internal browser.
DrupalWebTestCase::$elements protected property The parsed version of the page.
DrupalWebTestCase::$generatedTestFiles protected property Whether the files were copied to the test files directory.
DrupalWebTestCase::$headers protected property The headers of the page currently loaded in the internal browser.
DrupalWebTestCase::$httpauth_credentials protected property HTTP authentication credentials (<username>:<password>).
DrupalWebTestCase::$httpauth_method protected property HTTP authentication method
DrupalWebTestCase::$loggedInUser protected property The current user logged in using the internal browser.
DrupalWebTestCase::$originalShutdownCallbacks protected property The original shutdown handlers array, before it was cleaned for testing purposes.
DrupalWebTestCase::$originalUser protected property The original user, before it was changed to a clean uid = 1 for testing purposes.
DrupalWebTestCase::$plainTextContent protected property The content of the page currently loaded in the internal browser (plain text version).
DrupalWebTestCase::$profile protected property The profile to install as a basis for testing. 20
DrupalWebTestCase::$redirect_count protected property The number of redirects followed during the handling of a request.
DrupalWebTestCase::$session_id protected property The current session ID, if available.
DrupalWebTestCase::$session_name protected property The current session name, if available.
DrupalWebTestCase::$url protected property The URL currently loaded in the internal browser.
DrupalWebTestCase::assertField protected function Asserts that a field exists with the given name or ID.
DrupalWebTestCase::assertFieldById protected function Asserts that a field exists in the current page with the given ID and value.
DrupalWebTestCase::assertFieldByName protected function Asserts that a field exists in the current page with the given name and value.
DrupalWebTestCase::assertFieldByXPath protected function Asserts that a field exists in the current page by the given XPath.
DrupalWebTestCase::assertFieldChecked protected function Asserts that a checkbox field in the current page is checked.
DrupalWebTestCase::assertLink protected function Pass if a link with the specified label is found, and optional with the specified index.
DrupalWebTestCase::assertLinkByHref protected function Pass if a link containing a given href (part) is found.
DrupalWebTestCase::assertMail protected function Asserts that the most recently sent e-mail message has the given value.
DrupalWebTestCase::assertMailPattern protected function Asserts that the most recently sent e-mail message has the pattern in it.
DrupalWebTestCase::assertMailString protected function Asserts that the most recently sent e-mail message has the string in it.
DrupalWebTestCase::assertNoDuplicateIds protected function Asserts that each HTML ID is used for just a single element.
DrupalWebTestCase::assertNoField protected function Asserts that a field does not exist with the given name or ID.
DrupalWebTestCase::assertNoFieldById protected function Asserts that a field does not exist with the given ID and value.
DrupalWebTestCase::assertNoFieldByName protected function Asserts that a field does not exist with the given name and value.
DrupalWebTestCase::assertNoFieldByXPath protected function Asserts that a field doesn't exist or its value doesn't match, by XPath.
DrupalWebTestCase::assertNoFieldChecked protected function Asserts that a checkbox field in the current page is not checked.
DrupalWebTestCase::assertNoLink protected function Pass if a link with the specified label is not found.
DrupalWebTestCase::assertNoLinkByHref protected function Pass if a link containing a given href (part) is not found.
DrupalWebTestCase::assertNoOptionSelected protected function Asserts that a select option in the current page is not checked.
DrupalWebTestCase::assertNoPattern protected function Will trigger a pass if the perl regex pattern is not present in raw content.
DrupalWebTestCase::assertNoRaw protected function Pass if the raw text is NOT found on the loaded page, fail otherwise. Raw text refers to the raw HTML that the page generated.
DrupalWebTestCase::assertNoResponse protected function Asserts the page did not return the specified response code.
DrupalWebTestCase::assertNoText protected function Pass if the text is NOT found on the text version of the page. The text version is the equivalent of what a user would see when viewing through a web browser. In other words the HTML has been filtered out of the contents.
DrupalWebTestCase::assertNoTitle protected function Pass if the page title is not the given string.
DrupalWebTestCase::assertNoUniqueText protected function Pass if the text is found MORE THAN ONCE on the text version of the page.
DrupalWebTestCase::assertOptionSelected protected function Asserts that a select option in the current page is checked.
DrupalWebTestCase::assertPattern protected function Will trigger a pass if the Perl regex pattern is found in the raw content.
DrupalWebTestCase::assertRaw protected function Pass if the raw text IS found on the loaded page, fail otherwise. Raw text refers to the raw HTML that the page generated.
DrupalWebTestCase::assertResponse protected function Asserts the page responds with the specified response code.
DrupalWebTestCase::assertText protected function Pass if the text IS found on the text version of the page. The text version is the equivalent of what a user would see when viewing through a web browser. In other words the HTML has been filtered out of the contents.
DrupalWebTestCase::assertTextHelper protected function Helper for assertText and assertNoText.
DrupalWebTestCase::assertThemeOutput protected function Asserts themed output.
DrupalWebTestCase::assertTitle protected function Pass if the page title is the given string.
DrupalWebTestCase::assertUniqueText protected function Pass if the text is found ONLY ONCE on the text version of the page.
DrupalWebTestCase::assertUniqueTextHelper protected function Helper for assertUniqueText and assertNoUniqueText.
DrupalWebTestCase::assertUrl protected function Pass if the internal browser's URL matches the given path.
DrupalWebTestCase::buildXPathQuery protected function Builds an XPath query.
DrupalWebTestCase::changeDatabasePrefix protected function Changes the database connection to the prefixed one.
DrupalWebTestCase::checkForMetaRefresh protected function Check for meta refresh tag and if found call drupalGet() recursively. This function looks for the http-equiv attribute to be set to "Refresh" and is case-sensitive.
DrupalWebTestCase::checkPermissions protected function Check to make sure that the array of permissions are valid.
DrupalWebTestCase::clickLink protected function Follows a link by name.
DrupalWebTestCase::constructFieldXpath protected function Helper function: construct an XPath for the given set of attributes and value.
DrupalWebTestCase::copySetupCache protected function Copy the setup cache from/to another table and files directory.
DrupalWebTestCase::cronRun protected function Runs cron in the Drupal installed by Simpletest.
DrupalWebTestCase::curlClose protected function Close the cURL handler and unset the handler.
DrupalWebTestCase::curlExec protected function Initializes and executes a cURL request.
DrupalWebTestCase::curlHeaderCallback protected function Reads headers and registers errors received from the tested site.
DrupalWebTestCase::curlInitialize protected function Initializes the cURL connection.
DrupalWebTestCase::drupalCompareFiles protected function Compare two files based on size and file name.
DrupalWebTestCase::drupalCreateContentType protected function Creates a custom content type based on default settings.
DrupalWebTestCase::drupalCreateNode protected function Creates a node based on default settings.
DrupalWebTestCase::drupalCreateRole protected function Creates a role with specified permissions.
DrupalWebTestCase::drupalCreateUser protected function Create a user with a given set of permissions.
DrupalWebTestCase::drupalGet protected function Retrieves a Drupal path or an absolute path.
DrupalWebTestCase::drupalGetAJAX protected function Retrieve a Drupal path or an absolute path and JSON decode the result.
DrupalWebTestCase::drupalGetContent protected function Gets the current raw HTML of requested page.
DrupalWebTestCase::drupalGetHeader protected function Gets the value of an HTTP response header. If multiple requests were required to retrieve the page, only the headers from the last request will be checked by default. However, if TRUE is passed as the second argument, all requests will be processed…
DrupalWebTestCase::drupalGetHeaders protected function Gets the HTTP response headers of the requested page. Normally we are only interested in the headers returned by the last request. However, if a page is redirected or HTTP authentication is in use, multiple requests will be required to retrieve the…
DrupalWebTestCase::drupalGetMails protected function Gets an array containing all e-mails sent during this test case.
DrupalWebTestCase::drupalGetNodeByTitle function Get a node from the database based on its title.
DrupalWebTestCase::drupalGetSettings protected function Gets the value of the Drupal.settings JavaScript variable for the currently loaded page.
DrupalWebTestCase::drupalGetTestFiles protected function Get a list files that can be used in tests.
DrupalWebTestCase::drupalGetToken protected function Generate a token for the currently logged in user.
DrupalWebTestCase::drupalHead protected function Retrieves only the headers for a Drupal path or an absolute path.
DrupalWebTestCase::drupalLogin protected function Log in a user with the internal browser.
DrupalWebTestCase::drupalLogout protected function
DrupalWebTestCase::drupalPost protected function Execute a POST request on a Drupal page. It will be done as usual POST request with SimpleBrowser.
DrupalWebTestCase::drupalPostAJAX protected function Execute an Ajax submission.
DrupalWebTestCase::drupalSetContent protected function Sets the raw HTML content. This can be useful when a page has been fetched outside of the internal browser and assertions need to be made on the returned page.
DrupalWebTestCase::drupalSetSettings protected function Sets the value of the Drupal.settings JavaScript variable for the currently loaded page.
DrupalWebTestCase::getAbsoluteUrl protected function Takes a path and returns an absolute path.
DrupalWebTestCase::getAllOptions protected function Get all option elements, including nested options, in a select.
DrupalWebTestCase::getSelectedItem protected function Get the selected value from a select field.
DrupalWebTestCase::getSetupCacheKey protected function Returns the cache key used for the setup caching.
DrupalWebTestCase::getUrl protected function Get the current URL from the cURL handler.
DrupalWebTestCase::handleForm protected function Handle form input related to drupalPost(). Ensure that the specified fields exist and attempt to create POST data in the correct manner for the particular field type.
DrupalWebTestCase::loadSetupCache protected function Copies the cached tables and files for a cached installation setup.
DrupalWebTestCase::parse protected function Parse content returned from curlExec using DOM and SimpleXML.
DrupalWebTestCase::preloadRegistry protected function Preload the registry from the testing site.
DrupalWebTestCase::prepareDatabasePrefix protected function Generates a database prefix for running tests.
DrupalWebTestCase::prepareEnvironment protected function Prepares the current environment for running the test.
DrupalWebTestCase::recursiveDirectoryCopy protected function Recursively copy one directory to another.
DrupalWebTestCase::refreshVariables protected function Refresh the in-memory set of variables. Useful after a page request is made that changes a variable in a different thread. 1
DrupalWebTestCase::resetAll protected function Reset all data structures after having enabled new modules.
DrupalWebTestCase::storeSetupCache protected function Store the installation setup to a cache.
DrupalWebTestCase::tearDown protected function Delete created files and temporary files directory, delete the tables created by setUp(), and reset the database prefix. 6
DrupalWebTestCase::verboseEmail protected function Outputs to verbose the most recent $count emails sent.
DrupalWebTestCase::xpath protected function Perform an xpath search on the contents of the internal browser. The search is relative to the root element (HTML tag normally) of the page.
DrupalWebTestCase::__construct function Constructor for DrupalWebTestCase. Overrides DrupalTestCase::__construct 1
RestfulCurlBaseTestCase::httpRequest protected function Helper function to issue a HTTP request with simpletest's cURL.
RestfulListTestCase::addIntegerFields private function Helper function; Add single and multiple integer fields.
RestfulListTestCase::getInfo public static function
RestfulListTestCase::setUp public function Sets up a Drupal site for running functional and integration tests. Overrides DrupalWebTestCase::setUp
RestfulListTestCase::testAccessHandling public function Test error handling when no access is granted to an entity in a list.
RestfulListTestCase::testCountWithUnpublished public function Test node count and pager when there are unpublished nodes.
RestfulListTestCase::testFilter public function Test filtering.
RestfulListTestCase::testPagination public function Test pagination.
RestfulListTestCase::testSort public function Test the sorting of entities.