You are here

public function CreateTest::testCreateUser in Zircon Profile 8

Same name and namespace in other branches
  1. 8.0 core/modules/rest/src/Tests/CreateTest.php \Drupal\rest\Tests\CreateTest::testCreateUser()

Tests several valid and invalid create requests for 'user' entity type.

File

core/modules/rest/src/Tests/CreateTest.php, line 280
Contains \Drupal\rest\Tests\CreateTest.

Class

CreateTest
Tests the creation of resources.

Namespace

Drupal\rest\Tests

Code

public function testCreateUser() {
  $entity_type = 'user';

  // Enables the REST service for 'user' entity type.
  $this
    ->enableService('entity:' . $entity_type, 'POST');

  // Create two accounts that have the required permissions to create
  // resources. The second one has administrative permissions.
  $accounts = $this
    ->createAccountPerEntity($entity_type);
  foreach ($accounts as $key => $account) {
    $this
      ->drupalLogin($account);
    $entity_values = $this
      ->entityValues($entity_type);
    $entity = User::create($entity_values);

    // Verify that only administrative users can create users.
    if (!$account
      ->hasPermission('administer users')) {
      $serialized = $this->serializer
        ->serialize($entity, $this->defaultFormat, [
        'account' => $account,
      ]);
      $this
        ->httpRequest('entity/' . $entity_type, 'POST', $serialized, $this->defaultMimeType);
      $this
        ->assertResponse(403);
      continue;
    }

    // Changed field can never be added.
    unset($entity->changed);
    $serialized = $this->serializer
      ->serialize($entity, $this->defaultFormat, [
      'account' => $account,
    ]);

    // Create the entity over the REST API.
    $this
      ->assertCreateEntityOverRestApi($entity_type, $serialized);

    // Get the new entity ID from the location header and try to read it from
    // the database.
    $this
      ->assertReadEntityIdFromHeaderAndDb($entity_type, $entity, $entity_values);

    // Try to send invalid data that cannot be correctly deserialized.
    $this
      ->assertCreateEntityInvalidData($entity_type);

    // Try to send no data at all, which does not make sense on POST requests.
    $this
      ->assertCreateEntityNoData($entity_type);

    // Try to send invalid data to trigger the entity validation constraints.
    // Send a UUID that is too long.
    $this
      ->assertCreateEntityInvalidSerialized($entity, $entity_type);
  }
}