You are here

RestfulCreateEntityTestCase.test in RESTful 7.2

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

Contains RestfulCreateEntityTestCase

File

tests/RestfulCreateEntityTestCase.test
View source
<?php

/**
 * @file
 * Contains RestfulCreateEntityTestCase
 */
use Drupal\restful\Exception\BadRequestException;
use Drupal\restful\Http\Request;
use Drupal\restful\Http\RequestInterface;

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

  /**
   * {@inheritdoc}
   */
  public static function getInfo() {
    return array(
      'name' => 'Create entity',
      'description' => 'Test the creation of an entity.',
      'group' => 'RESTful',
    );
  }

  /**
   * @var string
   *
   * Holds the path to a random generated image for upload purposes.
   */
  private $imagePath;

  /**
   * @var \stdClass
   *
   * Holds the created account.
   */
  protected $account;

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

    // Add common fields, vocabulary and terms.
    restful_test_add_fields();
    $images = $this
      ->drupalGetTestFiles('image');
    $image = reset($images);
    $this->imagePath = drupal_realpath($image->uri);
    $this->account = $this
      ->drupalCreateUser();
  }

  /**
   * Test creating an entity (POST method).
   */
  public function testCreateEntity() {
    $resource_manager = restful()
      ->getResourceManager();

    // Create test entities to be referenced.
    $ids = array();
    for ($i = 0; $i < 2; $i++) {

      /* @var \Entity $entity */
      $entity = entity_create('entity_test', array(
        'name' => 'main',
      ));
      $entity
        ->save();
      $ids[] = $entity->pid;
    }
    $images = array();
    foreach ($this
      ->drupalGetTestFiles('image') as $file) {
      $file = file_save($file);
      $images[] = $file->fid;
    }
    $resource_manager
      ->clearPluginCache('main:1.1');
    $handler = $resource_manager
      ->getPlugin('main:1.1');
    $query = new EntityFieldQuery();
    $result = $query
      ->entityCondition('entity_type', 'taxonomy_term')
      ->entityCondition('bundle', 'test_vocab')
      ->execute();
    $tids = array_keys($result['taxonomy_term']);
    $text1 = $this
      ->randomName();
    $text2 = $this
      ->randomName();
    $request = array(
      'text_single' => $text1,
      'text_multiple' => array(
        $text1,
        $text2,
      ),
      'text_single_processing' => $text1,
      'text_multiple_processing' => array(
        $text1,
        $text2,
      ),
      'entity_reference_single' => $ids[0],
      'entity_reference_multiple' => $ids,
      'term_single' => $tids[0],
      'term_multiple' => array(
        $tids[0],
        $tids[1],
      ),
      'file_single' => $images[0],
      'file_multiple' => array(
        $images[0],
        $images[1],
      ),
      'image_single' => $images[0],
      'image_multiple' => array(
        $images[0],
        $images[1],
      ),
    );
    $response = drupal_json_decode(restful()
      ->getFormatterManager()
      ->format($handler
      ->doPost($request)));
    $response = $response['data'];
    $result = $response[0];
    $text_single = trim(strip_tags($result['text_single']));
    $text_multiple = array(
      trim(strip_tags($result['text_multiple'][0])),
      trim(strip_tags($result['text_multiple'][1])),
    );
    $expected_result = $request;

    // Strip some elements, and the text, for easier assertion.
    $striped_result = $result;
    unset($striped_result['id']);
    unset($striped_result['label']);
    unset($striped_result['self']);
    unset($striped_result['entity_reference_single_resource']);
    unset($striped_result['entity_reference_multiple_resource']);
    $striped_result['text_single'] = $text_single;
    $striped_result['text_multiple'] = $text_multiple;
    $striped_result['text_single_processing'] = $text_single;
    $striped_result['text_multiple_processing'] = $text_multiple;
    ksort($striped_result);
    ksort($expected_result);
    $this
      ->assertEqual($expected_result, $striped_result, 'Entity was created with correct values.');
    $this
      ->assertEqual($result['entity_reference_single_resource']['id'], $ids[0], ' Entity reference single resource was created correctly');
    $this
      ->assertEqual($result['entity_reference_multiple_resource'][0]['id'], $ids[0], ' Entity reference multiple resource was created correctly');

    // Create an entity with empty request.
    try {
      $handler
        ->setRequest(Request::create('', array(), RequestInterface::METHOD_POST));
      $handler
        ->setPath('');
      restful()
        ->getFormatterManager()
        ->format($handler
        ->process(), 'json');
      $this
        ->fail('User can create an entity with empty request.');
    } catch (BadRequestException $e) {
      $this
        ->pass('User cannot create an entity with empty request.');
    }

    // Create an entity with invalid property name.
    $request['invalid'] = 'wrong';
    try {
      $handler
        ->setRequest(Request::create('', array(), RequestInterface::METHOD_POST, NULL, FALSE, NULL, array(), array(), array(), $request));
      $handler
        ->setPath('');
      restful()
        ->getFormatterManager()
        ->format($handler
        ->process(), 'json');
      $this
        ->fail('User can create an entity with invalid property name.');
    } catch (BadRequestException $e) {
      $this
        ->pass('User cannot create an entity with invalid property name.');
    }

    // Create entity with comma separated multiple entity reference.
    $request = array(
      'entity_reference_multiple' => implode(',', $ids),
    );
    $handler
      ->setRequest(Request::create('', array(), RequestInterface::METHOD_POST, NULL, FALSE, NULL, array(), array(), array(), $request));
    $handler
      ->setPath('');
    $response = drupal_json_decode(restful()
      ->getFormatterManager()
      ->format($handler
      ->process(), 'json'));
    $response = $response['data'];
    $result = $response[0];
    $this
      ->assertEqual($result['entity_reference_multiple'], $ids, 'Created entity with comma separated multiple entity reference.');

    // Create entity with comma separated multiple taxonomy term reference.
    $ids = array(
      $tids[0],
      $tids[1],
    );
    $request = array(
      'term_multiple' => implode(',', $ids),
    );
    $handler
      ->setRequest(Request::create('', array(), RequestInterface::METHOD_POST, NULL, FALSE, NULL, array(), array(), array(), $request));
    $handler
      ->setPath('');
    $response = drupal_json_decode(restful()
      ->getFormatterManager()
      ->format($handler
      ->process(), 'json'));
    $response = $response['data'];
    $result = $response[0];
    $this
      ->assertEqual($result['term_multiple'], $ids, 'Created entity with comma separated multiple taxonomy term reference.');

    // Create entity with comma separated multiple file reference.
    $ids = array(
      $images[0],
      $images[1],
    );
    $request = array(
      'file_multiple' => implode(',', $ids),
    );
    $handler
      ->setRequest(Request::create('', array(), RequestInterface::METHOD_POST, NULL, FALSE, NULL, array(), array(), array(), $request));
    $handler
      ->setPath('');
    $response = drupal_json_decode(restful()
      ->getFormatterManager()
      ->format($handler
      ->process(), 'json'));
    $response = $response['data'];
    $result = $response[0];
    $this
      ->assertEqual($result['file_multiple'], $ids, 'Created entity with comma separated multiple file reference.');

    // Create entity with comma separated multiple image reference.
    $ids = array(
      $images[0],
      $images[1],
    );
    $request = array(
      'image_multiple' => implode(',', $ids),
    );
    $handler
      ->setRequest(Request::create('', array(), RequestInterface::METHOD_POST, NULL, FALSE, NULL, array(), array(), array(), $request));
    $handler
      ->setPath('');
    $response = drupal_json_decode(restful()
      ->getFormatterManager()
      ->format($handler
      ->process(), 'json'));
    $response = $response['data'];
    $result = $response[0];
    $this
      ->assertEqual($result['image_multiple'], $ids, 'Created entity with comma separated multiple image reference.');
  }

  /**
   * Test access for file upload.
   */
  public function testFileUploadAccess() {
    variable_set('restful_file_upload', TRUE);
    variable_set('restful_file_upload_allow_anonymous_user', TRUE);

    // Make sure the user is logged out even when using the UI tests.
    $this
      ->drupalLogout();

    // Test access for anonymous user (allowed).
    $handler = $this
      ->fileResource();
    $this
      ->assertTrue($handler
      ->access(), 'File upload is allowed to anonymous users.');
    variable_set('restful_file_upload_allow_anonymous_user', FALSE);

    // Now that we have a successfully uploaded file, make sure it's the same
    // file that was uploaded.
    $response = drupal_json_decode(restful()
      ->getFormatterManager()
      ->format($handler
      ->process()));
    $original = hash_file('md5', $this->imagePath);
    $file = file_load($response['data'][0][0]['id']);
    $uploaded = hash_file('md5', file_create_url($file->uri));
    $this
      ->assertEqual($original, $uploaded, 'Original and uploaded file are identical.');

    // Test access for anonymous user (denied).
    $handler = $this
      ->fileResource();
    $this
      ->assertFalse($handler
      ->access(), 'File upload is denied to anonymous users.');
    $this
      ->drupalLogin($this->account);

    // Test access for authenticated users (allowed).
    $handler = $this
      ->fileResource();
    $this
      ->assertTrue($handler
      ->access(), 'File upload is allowed to authenticated users.');

    // Test access for authenticated users (denied).
    variable_set('restful_file_upload', FALSE);
    try {
      $this
        ->fileResource();
      $this
        ->fail('The file upload endpoint is not disalbed.');
    } catch (\Drupal\restful\Exception\ServiceUnavailableException $e) {
      $this
        ->pass('The file upload endpoint is disalbed.');
    }
  }

  /**
   * Uploads a file issuing a POST HTTP request.
   *
   * @return \Drupal\restful\Plugin\resource\ResourceInterface
   *   The file resource.
   *
   * @throws \Drupal\restful\Exception\BadRequestException
   * @throws \Drupal\restful\Exception\ServiceUnavailableException
   */
  protected function fileResource() {

    // We are setting the $_FILES array directly on tests, so we need to
    // override the is_uploaded_file PHP method by setting a custom variable.
    // Otherwise the manually set file will not be detected.
    variable_set('restful_insecure_uploaded_flag', TRUE);

    // Clear the plugin definition cache to regenerate authenticationOptional
    // based on the variable value.
    $resource_manager = restful()
      ->getResourceManager();
    $resource_manager
      ->clearPluginCache('files_upload_test:1.0');
    if (!($handler = $resource_manager
      ->getPlugin('files_upload_test:1.0'))) {
      throw new \Drupal\restful\Exception\ServiceUnavailableException();
    }
    $plugin_definition = $handler
      ->getPluginDefinition();
    $plugin_definition['authenticationOptional'] = variable_get('restful_file_upload_allow_anonymous_user', FALSE);
    $handler
      ->setPluginDefinition($plugin_definition);
    $account = $this->account;
    if (!$this->loggedInUser) {
      $account = drupal_anonymous_user();
    }
    $handler
      ->setAccount($account);

    // Due to entity_metadata_file_access we need to set the global user to the
    // user for the test.
    $GLOBALS['user'] = $account;
    $value = '@' . $this->imagePath;

    // PHP 5.5 introduced a CurlFile object that deprecates the old @filename
    // syntax. See: https://wiki.php.net/rfc/curl-file-upload
    if (function_exists('curl_file_create')) {
      $value = curl_file_create($this->imagePath);
    }
    $tmp_name = drupal_tempnam('/tmp', 'restful_test_');
    file_put_contents($tmp_name, file_get_contents($this->imagePath));
    $headers = new \Drupal\restful\Http\HttpHeaderBag(array(
      'Content-Type' => 'multipart/form-data',
    ));

    // Mock the $_FILES global variable.
    $files = array(
      'my-filename' => array(
        'error' => 0,
        'name' => basename($this->imagePath),
        'size' => filesize($this->imagePath),
        'tmp_name' => $tmp_name,
        'type' => 'image/png',
      ),
    );
    $handler
      ->setRequest(Request::create('api/file-upload', array(), RequestInterface::METHOD_POST, $headers, FALSE, NULL, array(), $files, array(), array(
      'filename' => $value,
    )));
    $handler
      ->setPath('');
    return $handler;
  }

}

Classes

Namesort descending Description
RestfulCreateEntityTestCase Class RestfulCreateEntityTestCase.