cloud-8.x-2.0-beta1/modules/cloud_service_providers/aws_cloud/tests/src/Traits/AwsCloudTestEntityTrait.php

modules/cloud_service_providers/aws_cloud/tests/src/Traits/AwsCloudTestEntityTrait.php
<?php

namespace Drupal\Tests\aws_cloud\Traits;

use Drupal\cloud\Entity\CloudServerTemplate;
use Drupal\Component\Utility\Random;
use Drupal\Tests\aws_cloud\Functional\Utils;
use Drupal\aws_cloud\Entity\Ec2\ElasticIp;
use Drupal\aws_cloud\Entity\Ec2\Instance;
use Drupal\aws_cloud\Entity\Ec2\NetworkInterface;
use Drupal\aws_cloud\Entity\Ec2\Snapshot;
use Drupal\aws_cloud\Entity\Ec2\Volume;
use Drupal\aws_cloud\Entity\Ec2\Image;
use Drupal\aws_cloud\Entity\Ec2\KeyPair;
use Drupal\aws_cloud\Entity\Ec2\SecurityGroup;
use Drupal\aws_cloud\Entity\Vpc\Vpc;
use Drupal\aws_cloud\Entity\Vpc\Subnet;
use Drupal\cloud\Entity\CloudConfig;

/**
 * The trait creating test entity for aws cloud testing.
 */
trait AwsCloudTestEntityTrait {

  /**
   * Internal random number.
   *
   * @var int
   */
  private static $internalRandom;

  /**
   * Generates a random string for AWS long ID.
   *
   * The string is containing 32 length-letters and numbers.
   *
   * @return string
   *   32 length randomly generated string.
   *
   * @see https://www.drupal.org/project/cloud/issues/3025228
   */
  protected function getRandomAwsId() {
    if (!isset(self::$internalRandom)) {
      self::$internalRandom = new Random();
    }

    return self::$internalRandom->name(32, TRUE);
  }

  /**
   * Create an AWS Cloud Instance test entity.
   *
   * @param int $num
   *   The index.
   * @param string $public_ip
   *   The public IP.
   * @param string $instance_name
   *   The Instance name.
   * @param string $instance_id
   *   The Instance ID.
   * @param string $instance_state
   *   The Instance state.
   *
   * @return object
   *   The Instance entity.
   *
   * @throws \Drupal\Core\Entity\EntityStorageException
   */
  protected function createInstanceTestEntity($num = 0, $public_ip = NULL, $instance_name = '', $instance_id = '', $instance_state = 'running') {
    if (!isset($public_ip)) {
      $public_ip = Utils::getRandomPublicIp();
    }
    $private_ip = Utils::getRandomPrivateIp();
    $regions = ['us-west-1', 'us-west-2'];
    $region = $regions[array_rand($regions)];

    $instance = Instance::create([
      'cloud_context' => $this->cloudContext,
      'name' => $instance_name ?: sprintf('instance-entity #%d - %s - %s', $num + 1, date('Y/m/d H:i:s'), $this->random->name(32, TRUE)),
      'image_id' => 'ami-' . $this->getRandomAwsId(),
      'key_pair_name' => "key_pair-{$this->random->name(8, TRUE)}",
      'is_monitoring' => 0,
      'availability_zone' => "us-west-$num",
      'security_groups' => "security_group-{$this->random->name(8, TRUE)}",
      'instance_type' => "t$num.small",
      'kernel_id' => 'aki-' . $this->getRandomAwsId(),
      'ramdisk_id' => 'ari-' . $this->getRandomAwsId(),
      'user_data' => "User Data #$num: {$this->random->string(64, TRUE)}",
      'account_id' => rand(100000000000, 999999999999),
      'reservation_id' => 'r-' . $this->getRandomAwsId(),
      'group_name' => $this->random->name(8, TRUE),
      'host_id' => $this->random->name(8, TRUE),
      'affinity' => $this->random->name(8, TRUE),
      'launch_time' => date('c'),
      'security_group_id' => "sg-{$this->getRandomAwsId()}",
      'security_group_name' => $this->random->name(10, TRUE),
      'public_dns_name' => Utils::getPublicDns($region, $public_ip),
      'public_ip_address' => $public_ip,
      'private_dns_name' => Utils::getPrivateDns($region, $private_ip),
      'private_ip_address' => $private_ip,
      'vpc_id' => 'vpc-' . $this->getRandomAwsId(),
      'subnet_id' => 'subnet-' . $this->getRandomAwsId(),
      'reason' => $this->random->string(16, TRUE),
      'instance_id' => $instance_id ?: "i-{$this->getRandomAwsId()}",
      'instance_state' => $instance_state,
      'uid' => $this->loggedInUser->id(),
    ]);
    $instance->save();

    return $instance;
  }

  /**
   * Create an AWS Cloud VPC test entity.
   *
   * @param int $index
   *   The VPC index.
   * @param string $vpc_id
   *   The VPC ID.
   * @param string $vpc_name
   *   The VPC name.
   * @param string $cloud_context
   *   The Cloud context.
   *
   * @return \Drupal\aws_cloud\Entity\Vpc\Vpc
   *   The VPC entity.
   *
   * @throws \Drupal\Core\Entity\EntityStorageException
   */
  protected function createVpcTestEntity($index = 0, $vpc_id = '', $vpc_name = '', $cloud_context = '') {

    $entity = Vpc::create([
      'vpc_id' => $vpc_id ?: 'vpc-' . $this->getRandomAwsId(),
      'name' => $vpc_name ?: sprintf('vpc-entity #%d - %s - %s', $index + 1, date('Y/m/d H:i:s'), $this->random->name(32, TRUE)),
      'cloud_context' => $cloud_context ?: $this->cloudContext,
    ]);
    $entity->save();
    return $entity;
  }

  /**
   * Create an AWS Cloud Subnet test entity.
   *
   * @param int $index
   *   The Subnet index.
   * @param string $subnet_id
   *   The Subnet ID.
   * @param string $subnet_name
   *   The Subnet name.
   * @param string $cloud_context
   *   The Cloud context.
   *
   * @return \Drupal\aws_cloud\Entity\Vpc\Subnet
   *   The VPC entity.
   *
   * @throws \Drupal\Core\Entity\EntityStorageException
   */
  protected function createSubnetTestEntity($index = 0, $subnet_id = '', $subnet_name = '', $cloud_context = '') {

    $entity = Subnet::create([
      'subnet_id' => $subnet_id ?: 'subnet-' . $this->getRandomAwsId(),
      'name' => $subnet_name ?: sprintf('subnet-entity #%d - %s - %s', $index + 1, date('Y/m/d H:i:s'), $this->random->name(32, TRUE)),
      'cloud_context' => $cloud_context ?: $this->cloudContext,
    ]);
    $entity->save();
    return $entity;
  }

  /**
   * Create an AWS Cloud Network Interface test entity.
   *
   * @param int $index
   *   The Index.
   * @param string $network_interface_id
   *   The Network Interface ID.
   * @param string $network_interface_name
   *   The Network Interface name.
   * @param string $instance_id
   *   The Instance ID.
   *
   * @return \Drupal\aws_cloud\Entity\Ec2\NetworkInterface
   *   The Network Interface entity.
   *
   * @throws \Drupal\Core\Entity\EntityStorageException
   */
  protected function createNetworkInterfaceTestEntity($index = 0, $network_interface_id = '', $network_interface_name = '', $instance_id = '') {
    $timestamp = time();
    $private_ip = Utils::getRandomPrivateIp();
    $secondary_private_ip = Utils::getRandomPrivateIp();

    $network_interface = NetworkInterface::create([
      'cloud_context' => $this->cloudContext,
      'name' => $network_interface_name ?: sprintf('eni-entity #%d - %s - %s', $index + 1, date('Y/m/d H:i:s'), $this->random->name(32, TRUE)),
      'network_interface_id' => $network_interface_id ?: 'eni-' . $this->getRandomAwsId(),
      'vpc_id' => "vpc-{$this->random->name(8, TRUE)}",
      'mac_address' => NULL,
      'security_groups' => "security_group-{$this->random->name(8, TRUE)}",
      'status' => 'in-use',
      'private_dns' => NULL,
      'primary_private_ip' => $private_ip,
      'secondary_private_ips' => [$secondary_private_ip],
      'attachment_id' => 'attachment-' . $this->getRandomAwsId(),
      'attachment_owner' => NULL,
      'attachment_status' => NULL,
      'owner_id' => rand(100000000000, 999999999999),
      'association_id' => NULL,
      'secondary_association_id' => NULL,
      'subnet_id' => NULL,
      'description' => NULL,
      'public_ips' => NULL,
      'source_dest_check' => NULL,
      'instance_id' => $instance_id ?: 'i-' . $this->getRandomAwsId(),
      'device_index' => NULL,
      'delete_on_termination' => NULL,
      'allocation_id' => NULL,
      'created' => $timestamp,
      'changed' => $timestamp,
      'refreshed' => $timestamp,
    ]);
    $network_interface->save();
    return $network_interface;
  }

  /**
   * Create an AWS Cloud Elastic IP test entity.
   *
   * @param int $index
   *   The Elastic IP index.
   * @param string $elastic_ip_name
   *   The Elastic IP name.
   * @param string $public_ip
   *   The public IP address.
   *
   * @return \Drupal\aws_cloud\Entity\Ec2\ElasticIp
   *   The Elastic IP entity.
   *
   * @throws \Drupal\Core\Entity\EntityStorageException
   */
  protected function createElasticIpTestEntity($index = 0, $elastic_ip_name = '', $public_ip = '') {
    $timestamp = time();

    $entity = ElasticIp::create([
      'cloud_context' => $this->cloudContext,
      'name' => $elastic_ip_name ?: sprintf('eip-entity #%d - %s - %s', $index + 1, date('Y/m/d H:i:s'), $this->random->name(32, TRUE)),
      'public_ip' => $public_ip ?: Utils::getRandomPublicIp(),
      'instance_id' => NULL,
      'network_interface_id' => NULL,
      'private_ip_address' => NULL,
      'network_interface_owner' => NULL,
      'allocation_id' => NULL,
      'association_id' => NULL,
      'domain' => 'standard',
      'created' => $timestamp,
      'changed' => $timestamp,
      'refreshed' => $timestamp,
    ]);
    $entity->save();
    return $entity;
  }

  /**
   * Create an AWS Cloud Snapshot test entity.
   *
   * @param int $index
   *   The index.
   * @param string $snapshot_id
   *   The Snapshot ID.
   * @param string $snapshot_name
   *   The Snapshot name.
   * @param string $cloud_context
   *   The Cloud context.
   *
   * @return \Drupal\aws_cloud\Entity\Ec2\Snapshot
   *   The snapshot entity.
   *
   * @throws \Drupal\Core\Entity\EntityStorageException
   */
  protected function createSnapshotTestEntity($index = 0, $snapshot_id = '', $snapshot_name = '', $cloud_context = '') {
    $entity = Snapshot::create([
      'snapshot_id' => $snapshot_id,
      'name' => $snapshot_name ?: sprintf('snapshot-entity #%d - %s - %s', $index + 1, date('Y/m/d H:i:s'), $this->random->name(32, TRUE)),
      'cloud_context' => $cloud_context,
      'created' => time(),
    ]);
    $entity->save();
    return $entity;
  }

  /**
   * Create an AWS Cloud Volume test entity.
   *
   * @param int $num
   *   The Volume number.
   * @param string $volume_id
   *   The Volume ID.
   * @param string $volume_name
   *   The Volume name.
   * @param string $cloud_context
   *   The Cloud context.
   * @param int $uid
   *   The User ID.
   *
   * @return \Drupal\aws_cloud\Entity\Ec2\Volume
   *   The Volume entity.
   *
   * @throws \Drupal\Core\Entity\EntityStorageException
   */
  protected function createVolumeTestEntity($num, $volume_id, $volume_name, $cloud_context, $uid) {
    $entity = Volume::create([
      'volume_id'         => $volume_id,
      'name'              => $volume_name ?: sprintf('volume-entity #%d - %s - %s', $num + 1, date('Y/m/d H:i:s'), $this->random->name(32, TRUE)),
      'cloud_context'     => $cloud_context,
      'uid' => $uid,
      'size'              => $num * 10,
      'availability_zone' => "us-west-$num",
      'iops'              => $num * 1000,
      'encrypted'         => $num % 2,
      'volume_type'       => 'io1',
      'volume_status'     => 'Available',
      'state' => 'available',
    ]);
    $entity->save();
    return $entity;
  }

  /**
   * Create an AWS Cloud cloud service provider (CloudConfig) test entity.
   *
   * @param int $index
   *   The index.
   * @param string $cloud_context
   *   The Cloud Context.
   * @param string $cloud_config_name
   *   The cloud service provider (CloudConfig) name.
   * @param string $bundle_type
   *   The CloudConfig bundle Type string.
   *
   * @return \Drupal\cloud\Entity\CloudConfig
   *   The cloud service provider (CloudConfig) entity.
   *
   * @throws \Drupal\Core\Entity\EntityStorageException
   */
  protected function createCloudConfigTestEntity($index = 0, $cloud_context = '', $cloud_config_name = '', $bundle_type = 'aws_ec2') {
    $entity = CloudConfig::create([
      'cloud_context'    => $cloud_context,
      'name'             => $cloud_config_name ?: sprintf('config-entity #%d - %s - %s', $index + 1, date('Y/m/d H:i:s'), $this->random->name(4, TRUE)),
      'type'             => $bundle_type,
    ]);
    $entity->save();
    return $entity;
  }

  /**
   * Initialize mock instance types.
   *
   * The mock instance types will be saved to configuration
   * aws_cloud_mock_instance_types.
   */
  protected function initMockInstanceTypes() {
    $mock_instance_types = [
      'm1.small' => 'm1.small:1:2:2:0.048:170:300',
      'm1.medium' => 'm1.medium:1:3:3.75:0.096:340:600',
      'm1.large' => 'm1.large:2:7:7.5:0.192:700:1200',
      't1.micro' => 't1.micro:1:2:2:0.048:170:300',
      't2.micro' => 't2.micro:1:2:2:0.048:170:300',
      't3.micro' => 't3.micro:1:2:2:0.048:170:300',
      'm1.xlarge' => 'm1.xlarge:2:7:7.5:0.384:1400:3000',
      'm2.xlarge' => 'm2.xlarge:2:7:7.5:0.766:2800:6000',
      'm3.xlarge' => 'm3.xlarge:2:7:7.5:1.5:6000:12000',
    ];

    $config = \Drupal::configFactory()->getEditable('aws_cloud.settings');
    $config->set('aws_cloud_mock_instance_types', json_encode($mock_instance_types))
      ->save();
  }

  /**
   * Create an AWS Cloud Security Group test entity.
   *
   * @param int $index
   *   The Security Group index.
   * @param string $group_id
   *   The Security Group.
   * @param string $group_name
   *   The Security Group name.
   * @param string $vpc_id
   *   The VPC ID.
   * @param string $cloud_context
   *   The Cloud context.
   *
   * @return \Drupal\aws_cloud\Entity\Ec2\SecurityGroup
   *   The Security Group entity.
   *
   * @throws \Drupal\Core\Entity\EntityStorageException
   */
  protected function createSecurityGroupTestEntity($index = 0, $group_id = '', $group_name = '', $vpc_id = '', $cloud_context = '') {

    $group_name = $group_name ?: sprintf('sg-entity #%d - %s - %s', $index + 1, date('Y/m/d H:i:s'), $this->random->name(8, TRUE));

    $entity = SecurityGroup::create([
      'name'          => $group_name,
      'group_name'    => $group_name,
      'group_id'      => $group_id ?: 'sg-' . $this->getRandomAwsId(),
      'vpc_id'        => $vpc_id,
      'cloud_context' => $cloud_context,
    ]);
    $entity->save();
    return $entity;
  }

  /**
   * Create an AWS Cloud Image test entity.
   *
   * @param int $index
   *   The Image index.
   * @param string $image_id
   *   The Image ID.
   * @param string $cloud_context
   *   Tne Cloud context.
   *
   * @return \Drupal\aws_cloud\Entity\Ec2\Snapshot
   *   The Image entity.
   *
   * @throws \Drupal\Core\Entity\EntityStorageException
   */
  protected function createImageTestEntity($index = 0, $image_id = '', $cloud_context = '') {
    $name = sprintf('image-entity #%d - %s - %s', $index + 1, date('Y/m/d H:i:s'), $this->random->name(32, TRUE));
    $entity = Image::create([
      'image_id' => $image_id ?: "ami-{$this->getRandomAwsId()}",
      'name' => $name,
      'ami_name' => $name,
      'cloud_context' => $cloud_context,
      'root_device_type' => 'ebs',
      'created' => time(),
    ]);
    $entity->save();
    return $entity;
  }

  /**
   * Test bulk operation for entities.
   *
   * @param string $entity_type_name
   *   The name of the entity type. For example, instance.
   * @param array $entities_data
   *   The data of entities.
   * @param string $operation
   *   The operation.
   * @param string $operation_passive
   *   The passive voice of operation.
   * @param string $path_prefix
   *   The URL path of prefix.
   */
  protected function doTestEntityBulk($entity_type_name,
                                      array $entities_data,
                                      $operation = 'delete',
                                      $operation_passive = 'deleted',
                                      $path_prefix = '/clouds/aws_cloud') {

    $cloud_context = !empty($this->cloudContext)
      ? '/' . $this->cloudContext
      : '';

    $entity_count = count($entities_data);

    $entity_type_id = $entities_data[0]->getEntityTypeId();
    $data = [];
    $data['action'] = "${entity_type_id}_${operation}_action";

    $this->drupalGet("$path_prefix$cloud_context/$entity_type_name");

    $checkboxes = $this->cssSelect('input[type=checkbox]');
    foreach ($checkboxes as $checkbox) {
      if ($checkbox->getAttribute('name') == NULL) {
        continue;
      }

      $data[$checkbox->getAttribute('name')] = $checkbox->getAttribute('value');
    }

    // Confirm.
    $this->drupalPostForm(
      "$path_prefix$cloud_context/$entity_type_name",
      $data,
      t('Apply to selected items')
    );
    $this->assertResponse(200);

    $message = \Drupal::translation()->formatPlural($entity_count,
      'Are you sure you want to @operation this @item?',
      'Are you sure you want to @operation these @item entities?', [
        '@operation' => $operation,
        '@item' => $entities_data[0]->getEntityType()->getLowercaseLabel(),
      ]
    );

    $this->assertText($message);
    foreach ($entities_data as $entity_data) {
      $entity_name = $entity_data->label();
      $this->assertText($entity_name);
    }

    // Operation.
    $operation_upper = ucfirst($operation);
    $this->drupalPostForm(
      "$path_prefix$cloud_context/$entity_type_name/${operation}_multiple",
      [],
      $operation_upper
    );

    $this->assertResponse(200);

    foreach ($entities_data as $entity_data) {
      $this->assertText(
        t('The @type "@label" has been @operation_passive.', [
          '@type' => $entity_data->getEntityType()->getLabel(),
          '@label' => $entity_data->label(),
          '@operation_passive' => $operation_passive,
        ])
      );
    }

    $operation_passive_upper = ucfirst($operation_passive);
    $message = \Drupal::translation()->formatPlural($entity_count,
      t('@operation_passive_upper @entity_count item.', [
        '@operation_passive_upper' => $operation_passive_upper,
        '@entity_count' => $entity_count,
      ]),
      t('@operation_passive_upper @entity_count items.', [
        '@operation_passive_upper' => $operation_passive_upper,
        '@entity_count' => $entity_count,
      ])
    );
    $this->assertText($message);

  }

  /**
   * Create an AWS Cloud Key Pair test entity.
   *
   * @param int $index
   *   The Key Pair index.
   * @param string $key_pair_name
   *   The Key Pair Name.
   * @param string $key_fingerprint
   *   The Fingerprint.
   * @param string $cloud_context
   *   The Cloud context.
   *
   * @return \Drupal\aws_cloud\Entity\Ec2\KeyPair
   *   The Key Pair entity.
   *
   * @throws \Drupal\Core\Entity\EntityStorageException
   */
  protected function createKeyPairTestEntity($index = 0, $key_pair_name = '', $key_fingerprint = '', $cloud_context = '') {
    $entity = KeyPair::create([
      'key_pair_name' => $key_pair_name ?: sprintf('key_pair-entity #%d - %s - %s', $index + 1, date('Y/m/d H:i:s'), $this->random->name(32, TRUE)),
      'key_fingerprint' => $key_fingerprint,
      'cloud_context' => $cloud_context,
      'created' => time(),
    ]);
    $entity->save();
    return $entity;
  }

  /**
   * Create Cloud Server Template.
   *
   * @param array $iam_roles
   *   The IAM Roles.
   * @param \Drupal\aws_cloud\Entity\Ec2\Image $image
   *   The Image Entity.
   * @param string $cloud_context
   *   The cloud context.
   */
  protected function createServerTemplateTestEntity(array $iam_roles = [],
                                                    Image $image = NULL,
                                                    $cloud_context = '') {

    $data = [
      'type' => 'aws_cloud',
      'name' => 'test_template1',
    ];

    // Create template.
    $template = CloudServerTemplate::create($data);
    $template->setCloudContext($cloud_context ?: $this->cloudContext);
    $template->field_test_only->value = '1';
    $template->field_max_count->value = 1;
    $template->field_min_count->value = 1;
    $template->field_monitoring->value = '0';
    $template->field_instance_type->value = 't1.micro';
    $template->field_image_id->value = $image->getImageId()
      ?: "ami-{$this->getRandomAwsId()}";

    // Set the IAM role which can be NULL or something.
    $iam_role_index = array_rand($iam_roles);
    if ($iam_role_index === 0) {
      $template->field_iam_role = NULL;
    }
    else {

      // @TODO: Is this correct? Make sure if field_iam_role->value is correct or not
      $template->field_iam_role = str_replace(
        'role/',
        'instance-profile/',
        $iam_roles[$iam_role_index]['Arn']
      );
    }

    $template->save();
    return $template;
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc