Esempio n. 1
0
 def test_generate_test_user(self):
     """Assert generation of test user with appropriate defaults."""
     user = helper.generate_test_user()
     self.assertFalse(user.is_superuser)
     other_user = helper.generate_test_user()
     self.assertNotEqual(user, other_user)
     self.assertNotEqual(user.username, other_user.username)
Esempio n. 2
0
    def setUp(self):
        """Set up commonly used data for each test."""
        # various images not belonging to any particular cloud account
        self.image_plain = api_helper.generate_image()
        self.image_rhel = api_helper.generate_image(rhel_detected=True)
        self.image_ocp = api_helper.generate_image(openshift_detected=True)

        # define users
        self.user_1 = util_helper.generate_test_user()
        self.user_2 = util_helper.generate_test_user()
        self.user_super = util_helper.generate_test_user(is_superuser=True)

        # define users' cloud accounts
        self.account_1 = api_helper.generate_cloud_account(user=self.user_1,
                                                           name=_faker.bs())

        # define instances that belong to user_1 account_1
        self.instance_plain = api_helper.generate_instance(
            cloud_account=self.account_1, image=self.image_plain)
        self.instance_rhel = api_helper.generate_instance(
            cloud_account=self.account_1, image=self.image_rhel)
        self.instance_ocp = api_helper.generate_instance(
            cloud_account=self.account_1, image=self.image_ocp)
        self.instance_noimage = api_helper.generate_instance(
            cloud_account=self.account_1, no_image=True)

        api_helper.generate_instance_type_definitions()
Esempio n. 3
0
    def setUp(self):
        """Set up a bunch of test data."""
        self.user1 = util_helper.generate_test_user()
        self.user2 = util_helper.generate_test_user()

        self.account1 = api_helper.generate_cloud_account(user=self.user1)
        self.account2 = api_helper.generate_cloud_account(user=self.user2)

        self.image_plain = api_helper.generate_image()
        self.image_windows = api_helper.generate_image(is_windows=True)
        self.image_rhel = api_helper.generate_image(rhel_detected=True)
        self.image_ocp = api_helper.generate_image(openshift_detected=True)

        self.instance1 = api_helper.generate_instance(
            cloud_account=self.account1, image=self.image_plain
        )
        self.instance2 = api_helper.generate_instance(
            cloud_account=self.account1, image=self.image_windows
        )
        self.instance3 = api_helper.generate_instance(
            cloud_account=self.account1, image=self.image_rhel
        )
        self.instance4 = api_helper.generate_instance(
            cloud_account=self.account1, image=self.image_ocp
        )
Esempio n. 4
0
 def test_generate_test_user(self):
     """Assert generation of test user with appropriate defaults."""
     user = helper.generate_test_user()
     self.assertEqual(user.email, user.username)
     self.assertTrue(user.email.endswith('@mail.127.0.0.1.nip.io'))
     self.assertFalse(user.is_superuser)
     other_user = helper.generate_test_user()
     self.assertNotEqual(user, other_user)
     self.assertNotEqual(user.username, other_user.username)
Esempio n. 5
0
    def setUp(self):
        """
        Set up a bunch of test data.

        This gets very noisy very quickly because we need users who have
        accounts that have instances that have events that used various image
        types.
        """
        # Users
        self.user1 = util_helper.generate_test_user()
        self.user2 = util_helper.generate_test_user()

        # Accounts for the users
        self.account_u1_1 = api_helper.generate_cloud_account(user=self.user1)
        self.account_u1_2 = api_helper.generate_cloud_account(user=self.user1)
        self.account_u2_1 = api_helper.generate_cloud_account(user=self.user2)
        self.account_u2_2 = api_helper.generate_cloud_account(user=self.user2)

        # Images with various contents
        self.image_plain = api_helper.generate_image()
        self.image_windows = api_helper.generate_image(is_windows=True)
        self.image_rhel = api_helper.generate_image(rhel_detected=True)
        self.image_ocp = api_helper.generate_image(openshift_detected=True,
                                                   architecture="arm64")
        self.image_rhel_ocp = api_helper.generate_image(
            rhel_detected=True,
            openshift_detected=True,
            status=MachineImage.UNAVAILABLE)
        self.inspected_image = api_helper.generate_image(
            status=MachineImage.INSPECTED)

        # Instances for the accounts
        self.instance_u1_1 = api_helper.generate_instance(
            cloud_account=self.account_u1_1, image=self.image_plain)
        self.instance_u1_2 = api_helper.generate_instance(
            cloud_account=self.account_u1_2, image=self.image_rhel)
        self.instance_u2_1 = api_helper.generate_instance(
            cloud_account=self.account_u2_1, image=self.image_ocp)
        self.instance_u2_2 = api_helper.generate_instance(
            cloud_account=self.account_u2_2, image=self.image_rhel_ocp)

        # Some initial event activity spread across the accounts
        powered_times = ((
            util_helper.utc_dt(2018, 1, 9, 0, 0, 0),
            util_helper.utc_dt(2018, 1, 10, 0, 0, 0),
        ), )
        instance_images = (
            (self.instance_u1_1, self.image_plain),
            (self.instance_u1_2, self.image_rhel),
            (self.instance_u2_1, self.image_ocp),
            (self.instance_u2_2, self.image_rhel_ocp),
        )
        for instance, image in instance_images:
            self.generate_events(powered_times, instance, image)

        self.factory = APIRequestFactory()
Esempio n. 6
0
    def test_lock_task_for_user_ids_create_usertasklock(self):
        """Assert UserTaskLock is created by context manager."""
        user1 = util_helper.generate_test_user()
        user2 = util_helper.generate_test_user()

        with lock_task_for_user_ids([user1.id, user2.id]):
            locks = UserTaskLock.objects.all()
            for lock in locks:
                self.assertEqual(lock.locked, True)
        locks = UserTaskLock.objects.all()
        for lock in locks:
            self.assertEqual(lock.locked, False)
Esempio n. 7
0
def generate_aws_account(arn=None, aws_account_id=None, user=None, name=None):
    """
    Generate an AwsAccount for testing.

    Any optional arguments not provided will be randomly generated.

    Args:
        arn (str): Optional ARN.
        aws_account_id (12-digit string): Optional AWS account ID.
        user (User): Optional Django auth User to be this account's owner.
        name (str): Optional name for this account.

    Returns:
        AwsAccount: The created AwsAccount.

    """
    if arn is None:
        arn = helper.generate_dummy_arn(account_id=aws_account_id)

    if user is None:
        user = helper.generate_test_user()

    return AwsAccount.objects.create(
        account_arn=arn,
        aws_account_id=aws.AwsArn(arn).account_id,
        user=user,
        name=name,
    )
Esempio n. 8
0
    def test_save_with_concurrent_usages(self):
        """Test that save deletes the related concurrent_usages."""
        user = util_helper.generate_test_user()
        aws_account_id = util_helper.generate_dummy_aws_account_id()
        account = api_helper.generate_cloud_account(
            aws_account_id=aws_account_id,
            user=user,
        )
        image = api_helper.generate_image(
            owner_aws_account_id=aws_account_id,
            rhel_detected=True,
        )
        instance = api_helper.generate_instance(account, image=image)
        api_helper.generate_single_run(
            instance,
            (
                util_helper.utc_dt(2019, 5, 1, 1, 0, 0),
                util_helper.utc_dt(2019, 5, 1, 2, 0, 0),
            ),
            image=instance.machine_image,
        )
        request_date = datetime.date(2019, 5, 1)
        calculate_max_concurrent_usage(request_date, user_id=user.id)

        self.assertEquals(1, ConcurrentUsage.objects.count())
        image.rhel_detected_by_tag = True
        image.save()
        self.assertEquals(0, ConcurrentUsage.objects.count())
Esempio n. 9
0
    def test_create_fails_when_account_not_verified(self):
        """Test that an account is not saved if verification fails."""
        aws_account_id = util_helper.generate_dummy_aws_account_id()
        arn = util_helper.generate_dummy_arn(aws_account_id)
        role = util_helper.generate_dummy_role()
        validated_data = {
            'account_arn': arn,
        }

        mock_request = Mock()
        mock_request.user = util_helper.generate_test_user()
        context = {'request': mock_request}

        failed_actions = ['foo', 'bar']

        with patch.object(aws, 'verify_account_access') as mock_verify, \
                patch.object(aws.sts, 'boto3') as mock_boto3:
            mock_assume_role = mock_boto3.client.return_value.assume_role
            mock_assume_role.return_value = role
            mock_verify.return_value = False, failed_actions
            serializer = AwsAccountSerializer(context=context)

            with self.assertRaises(serializers.ValidationError) as cm:
                serializer.create(validated_data)

            exception = cm.exception
            self.assertIn('account_arn', exception.detail)
            for index in range(len(failed_actions)):
                self.assertIn(failed_actions[index],
                              exception.detail['account_arn'][index + 1])
Esempio n. 10
0
    def test_create_fails_when_assume_role_fails_unexpectedly(self):
        """Test that account is not saved if assume_role fails unexpectedly."""
        aws_account_id = util_helper.generate_dummy_aws_account_id()
        arn = util_helper.generate_dummy_arn(aws_account_id)
        validated_data = {
            'account_arn': arn,
        }

        mock_request = Mock()
        mock_request.user = util_helper.generate_test_user()
        context = {'request': mock_request}

        client_error = ClientError(
            error_response=MagicMock(),
            operation_name=Mock(),
        )

        with patch.object(aws.sts, 'boto3') as mock_boto3:
            mock_assume_role = mock_boto3.client.return_value.assume_role
            mock_assume_role.side_effect = client_error
            serializer = AwsAccountSerializer(context=context)

            with self.assertRaises(ClientError) as cm:
                serializer.create(validated_data)
            raised_exception = cm.exception
            self.assertEqual(raised_exception, client_error)
Esempio n. 11
0
    def test_create_fails_when_arn_access_denied(self):
        """Test that an account is not saved if ARN access is denied."""
        aws_account_id = util_helper.generate_dummy_aws_account_id()
        arn = util_helper.generate_dummy_arn(aws_account_id)
        validated_data = {
            'account_arn': arn,
        }

        mock_request = Mock()
        mock_request.user = util_helper.generate_test_user()
        context = {'request': mock_request}

        client_error = ClientError(
            error_response={'Error': {
                'Code': 'AccessDenied'
            }},
            operation_name=Mock(),
        )

        with patch.object(aws.sts, 'boto3') as mock_boto3:
            mock_assume_role = mock_boto3.client.return_value.assume_role
            mock_assume_role.side_effect = client_error
            serializer = AwsAccountSerializer(context=context)

            with self.assertRaises(ValidationError) as cm:
                serializer.create(validated_data)
            raised_exception = cm.exception
            self.assertIn('account_arn', raised_exception.detail)
            self.assertIn(arn, raised_exception.detail['account_arn'][0])
Esempio n. 12
0
    def test_create_fails_when_cloudtrail_fails(self):
        """Test that an account is not saved if cloudtrails errors."""
        aws_account_id = util_helper.generate_dummy_aws_account_id()
        arn = util_helper.generate_dummy_arn(aws_account_id)
        role = util_helper.generate_dummy_role()

        validated_data = {
            'account_arn': arn,
        }

        client_error = ClientError(
            error_response={'Error': {
                'Code': 'AccessDeniedException'
            }},
            operation_name=Mock(),
        )

        mock_request = Mock()
        mock_request.user = util_helper.generate_test_user()
        context = {'request': mock_request}

        with patch.object(aws, 'verify_account_access') as mock_verify, \
                patch.object(aws.sts, 'boto3') as mock_boto3, \
                patch.object(aws, 'configure_cloudtrail') as mock_cloudtrail:
            mock_assume_role = mock_boto3.client.return_value.assume_role
            mock_assume_role.return_value = role
            mock_verify.return_value = True, []
            mock_cloudtrail.side_effect = client_error
            serializer = AwsAccountSerializer(context=context)

            with self.assertRaises(ValidationError) as cm:
                serializer.create(validated_data)
            raised_exception = cm.exception
            self.assertIn('account_arn', raised_exception.detail)
            self.assertIn(arn, raised_exception.detail['account_arn'][0])
Esempio n. 13
0
    def test_create_fails_cloudtrail_configuration_error(
            self, mock_notify_sources):
        """Test that an exception occurs if cloudtrail configuration fails."""
        mock_request = Mock()
        mock_request.user = util_helper.generate_test_user()
        context = {"request": mock_request}
        serializer = CloudAccountSerializer(context=context)

        client_error = ClientError(
            error_response={"Error": {
                "Code": "AccessDeniedException"
            }},
            operation_name=Mock(),
        )

        with patch.object(
                aws, "verify_account_access") as mock_verify, patch.object(
                    aws.sts, "boto3") as mock_boto3, patch.object(
                        aws, "configure_cloudtrail") as mock_cloudtrail:
            mock_assume_role = mock_boto3.client.return_value.assume_role
            mock_assume_role.return_value = self.role
            mock_verify.return_value = True, []
            mock_cloudtrail.side_effect = client_error

            expected_error = "Could not enable"
            with self.assertLogs(
                    "api.models",
                    level="INFO") as cm, self.assertRaises(ValidationError):
                serializer.create(self.validated_data)
            log_record = cm.records[1]
            self.assertIn(expected_error, log_record.msg.detail["account_arn"])
Esempio n. 14
0
    def test_copy_ami_snapshot_encrypted(self, mock_aws):
        """Assert that the task marks the image as encrypted in the DB."""
        mock_account_id = util_helper.generate_dummy_aws_account_id()
        mock_region = random.choice(util_helper.SOME_AWS_REGIONS)
        mock_arn = util_helper.generate_dummy_arn(mock_account_id, mock_region)

        mock_image_id = util_helper.generate_dummy_image_id()
        mock_image = util_helper.generate_mock_image(mock_image_id)
        mock_snapshot_id = util_helper.generate_dummy_snapshot_id()
        mock_snapshot = util_helper.generate_mock_snapshot(mock_snapshot_id,
                                                           encrypted=True)
        mock_session = mock_aws.boto3.Session.return_value

        mock_aws.get_session.return_value = mock_session
        mock_aws.get_ami.return_value = mock_image
        mock_aws.get_ami_snapshot_id.return_value = mock_snapshot_id
        mock_aws.get_snapshot.return_value = mock_snapshot

        account = AwsAccount(
            aws_account_id=mock_account_id,
            account_arn=mock_arn,
            user=util_helper.generate_test_user(),
        )
        account.save()
        ami = AwsMachineImage.objects.create(account=account,
                                             is_windows=False,
                                             ec2_ami_id=mock_image_id)

        ami.save()

        with patch.object(tasks, 'create_volume') as mock_create_volume,\
                self.assertRaises(AwsSnapshotEncryptedError):
            copy_ami_snapshot(mock_arn, mock_image_id, mock_region)
            self.assertTrue(ami.is_encrypted)
            mock_create_volume.delay.assert_not_called()
Esempio n. 15
0
    def test_openshift_tag_added(self, mock_aws, mock_check_image_state):
        """Test openshift tag added to MachineImage."""
        mock_session = mock_aws.boto3.Session.return_value

        ami_id = util_helper.generate_dummy_image_id()
        ami_region = random.choice(util_helper.SOME_AWS_REGIONS)
        mock_ami = util_helper.generate_mock_image(ami_id)
        mock_ami.tags = [{
            'Key': 'cloudigrade-ocp-present',
            'Value': 'cloudigrade-ocp-present'
        }]
        mock_resource = mock_session.resource.return_value
        mock_resource.Image.return_value = mock_ami

        test_user = util_helper.generate_test_user()
        test_account = AwsAccount.objects.create(
            user=test_user,
            aws_account_id=util_helper.generate_dummy_aws_account_id,
            account_arn=util_helper.generate_dummy_arn)
        test_image = AwsMachineImage.objects.create(account=test_account,
                                                    ec2_ami_id=ami_id)

        serializer = AwsAccountSerializer()
        openshift_tag = test_image.tags.filter(description='openshift').first()
        self.assertEqual(openshift_tag, None)

        serializer.add_openshift_tag(mock_session, ami_id, ami_region,
                                     test_image)

        openshift_tag = test_image.tags.filter(description='openshift').first()
        self.assertNotEqual(openshift_tag, None)
Esempio n. 16
0
 def test_generate_test_user_with_args(self):
     """Assert generation of test user with specified arguments."""
     email = f'{uuid.uuid4()}@example.com'
     user = helper.generate_test_user(email=email, is_superuser=True)
     self.assertEqual(user.email, email)
     self.assertEqual(user.username, email)
     self.assertTrue(user.is_superuser)
Esempio n. 17
0
    def test_create_fails_access_denied(self, mock_notify_sources):
        """Test that an exception is raised if access is denied to the arn."""
        client_error = ClientError(
            error_response={"Error": {
                "Code": "AccessDenied"
            }},
            operation_name=Mock(),
        )

        mock_request = Mock()
        mock_request.user = util_helper.generate_test_user()
        context = {"request": mock_request}
        serializer = CloudAccountSerializer(context=context)

        with patch.object(
                aws, "verify_account_access") as mock_verify, patch.object(
                    aws.sts, "boto3") as mock_boto3:
            mock_assume_role = mock_boto3.client.return_value.assume_role
            mock_assume_role.side_effect = client_error
            mock_verify.return_value = True, []

            expected_error = {
                "account_arn":
                ['Permission denied for ARN "{0}"'.format(self.arn)]
            }
            with self.assertLogs(
                    "api.models",
                    level="INFO") as cm, self.assertRaises(ValidationError):
                serializer.create(self.validated_data)
            log_record = cm.records[1]
            self.assertIn(
                expected_error["account_arn"][0],
                log_record.msg.detail["account_arn"][0],
            )
Esempio n. 18
0
    def test_create_new_machine_images(self):
        """Test that new machine images are saved to the DB."""
        aws_account_id = util_helper.generate_dummy_aws_account_id()
        arn = util_helper.generate_dummy_arn(aws_account_id)
        account = AwsAccount(
            account_arn=arn,
            aws_account_id=aws_account_id,
            user=util_helper.generate_test_user(),
        )
        account.save()

        region = random.choice(util_helper.SOME_AWS_REGIONS)
        running_instances = {
            region: [
                util_helper.generate_dummy_describe_instance(
                    state=aws.InstanceState.running
                )
            ]
        }
        ami_id = running_instances[region][0]['ImageId']

        result = util.create_new_machine_images(account, running_instances)

        amis = AwsMachineImage.objects.filter(account=account).all()

        self.assertEqual(result, [ami_id])
        for ami in amis:
            self.assertEqual(ami.ec2_ami_id, ami_id)
Esempio n. 19
0
    def test_create_succeeds_when_account_verified(self, mock_enable):
        """Test saving of a test ARN."""
        mock_request = Mock()
        mock_request.user = util_helper.generate_test_user()
        context = {"request": mock_request}

        serializer = CloudAccountSerializer(context=context)

        result = serializer.create(self.validated_data)
        self.assertIsInstance(result, CloudAccount)
        mock_enable.assert_called()

        # Verify that we created the account.
        account = AwsCloudAccount.objects.get(
            aws_account_id=self.aws_account_id)
        self.assertEqual(self.aws_account_id, account.aws_account_id)
        self.assertEqual(self.arn, account.account_arn)

        # Verify that we created no instances yet.
        instances = Instance.objects.filter(
            cloud_account=account.cloud_account.get()).all()
        self.assertEqual(len(instances), 0)

        # Verify that we created no images yet.
        amis = AwsMachineImage.objects.all()
        self.assertEqual(len(amis), 0)
Esempio n. 20
0
    def test_create_new_machine_images_with_windows_image(self):
        """Test that new windows machine images are marked appropriately."""
        aws_account_id = util_helper.generate_dummy_aws_account_id()
        arn = util_helper.generate_dummy_arn(aws_account_id)
        account = AwsAccount(
            account_arn=arn,
            aws_account_id=aws_account_id,
            user=util_helper.generate_test_user(),
        )
        account.save()

        region = random.choice(util_helper.SOME_AWS_REGIONS)
        running_instances = {
            region: [
                util_helper.generate_dummy_describe_instance(
                    state=aws.InstanceState.running
                )
            ]
        }
        running_instances[region][0]['Platform'] = 'Windows'
        ami_id = running_instances[region][0]['ImageId']

        result = util.create_new_machine_images(account, running_instances)

        amis = AwsMachineImage.objects.filter(account=account).all()

        self.assertEqual(result, [ami_id])
        for ami in amis:
            self.assertEqual(ami.ec2_ami_id, ami_id)
            self.assertEqual(ImageTag.objects.filter(
                description='windows').first(),
                ami.tags.filter(description='windows').first())
    def test_create_aws_clount_fails_with_different_user_same_account_id(
            self, mock_enable, mock_notify_sources):
        """Test create_aws_cloud_account failure message for different user."""
        # The first call just creates the existing objects.
        util.create_aws_cloud_account(self.user, self.arn, self.name,
                                      self.auth_id, self.app_id,
                                      self.source_id)

        other_arn = util_helper.generate_dummy_arn(
            account_id=self.aws_account_id, resource=_faker.word())
        other_auth_id = _faker.pyint()
        other_app_id = _faker.pyint()
        other_source_id = _faker.pyint()
        other_user = util_helper.generate_test_user()

        with self.assertRaises(ValidationError) as raise_context:
            util.create_aws_cloud_account(
                other_user,
                other_arn,
                self.name,
                other_auth_id,
                other_app_id,
                other_source_id,
            )
        exception_detail = raise_context.exception.detail
        self.assertIn("Could not set up cloud metering.",
                      exception_detail["account_arn"])
        self.assertNotIn("CG1002", exception_detail["account_arn"])
Esempio n. 22
0
 def test_generate_test_user_with_args(self):
     """Assert generation of test user with specified arguments."""
     account_number = _faker.random_int(min=100000, max=999999)
     user = helper.generate_test_user(account_number=account_number,
                                      is_superuser=True)
     self.assertEqual(user.username, account_number)
     self.assertTrue(user.is_superuser)
Esempio n. 23
0
    def test_openshift_no_tags(self, mock_aws, mock_check_image_state):
        """Test case where AMI has no tags."""
        mock_session = mock_aws.boto3.Session.return_value

        ami_id = util_helper.generate_dummy_image_id()
        ami_region = random.choice(util_helper.SOME_AWS_REGIONS)
        mock_ami = util_helper.generate_mock_image(ami_id)
        mock_ami.tags = None
        mock_resource = mock_session.resource.return_value
        mock_resource.Image.return_value = mock_ami

        test_user = util_helper.generate_test_user()
        test_account = AwsAccount.objects.create(
            user=test_user,
            aws_account_id=util_helper.generate_dummy_aws_account_id,
            account_arn=util_helper.generate_dummy_arn)
        test_image = AwsMachineImage.objects.create(account=test_account,
                                                    ec2_ami_id=ami_id)

        serializer = AwsAccountSerializer()
        openshift_tag = test_image.tags.filter(description='openshift').first()
        self.assertEqual(openshift_tag, None)

        serializer.add_openshift_tag(mock_session, ami_id, ami_region,
                                     test_image)

        openshift_tag = test_image.tags.filter(description='openshift').first()
        self.assertEqual(openshift_tag, None)
Esempio n. 24
0
 def setUp(self):
     """Set up common variables for tests."""
     self.user = util_helper.generate_test_user()
     self.aws_account_id = util_helper.generate_dummy_aws_account_id()
     self.account = api_helper.generate_cloud_account(
         aws_account_id=self.aws_account_id, user=self.user)
     self.arn = util_helper.generate_dummy_arn(
         account_id=self.aws_account_id)
Esempio n. 25
0
    def test_create_fails_when_another_arn_has_same_aws_account_id(self):
        """Test that an account is not saved if ARN reuses an AWS account."""
        user = util_helper.generate_test_user()
        aws_account_id = util_helper.generate_dummy_aws_account_id()
        arn = util_helper.generate_dummy_arn(aws_account_id)
        role = util_helper.generate_dummy_role()
        region = random.choice(util_helper.SOME_AWS_REGIONS)
        running_instances = {
            region: [
                util_helper.generate_dummy_describe_instance(
                    state=aws.InstanceState.running),
                util_helper.generate_dummy_describe_instance(
                    state=aws.InstanceState.stopping)
            ]
        }

        validated_data = {
            'account_arn': arn,
        }

        # Create one with the same AWS account ID but a different ARN.
        account_helper.generate_aws_account(
            aws_account_id=aws_account_id,
            user=user,
        )

        mock_request = Mock()
        mock_request.user = util_helper.generate_test_user()
        context = {'request': mock_request}

        with patch.object(aws, 'verify_account_access') as mock_verify, \
                patch.object(aws.sts, 'boto3') as mock_boto3, \
                patch.object(aws, 'get_running_instances') as mock_get_run:
            mock_assume_role = mock_boto3.client.return_value.assume_role
            mock_assume_role.return_value = role
            mock_verify.return_value = True, []
            mock_get_run.return_value = running_instances
            serializer = AwsAccountSerializer(context=context)

            with self.assertRaises(ValidationError) as cm:
                serializer.create(validated_data)
            raised_exception = cm.exception
            self.assertIn('account_arn', raised_exception.detail)
            self.assertIn(aws_account_id,
                          raised_exception.detail['account_arn'][0])
Esempio n. 26
0
 def test_lock_task_for_user_ids_updates_usertasklock(self):
     """Assert UserTaskLock is updated by context manager."""
     user = util_helper.generate_test_user()
     UserTaskLock.objects.create(user=user)
     with lock_task_for_user_ids([user.id]) as locks:
         for lock in locks:
             self.assertEqual(lock.locked, True)
     lock = UserTaskLock.objects.get(user=user)
     self.assertEqual(lock.locked, False)
Esempio n. 27
0
 def setUp(self):
     """Set up common variables for tests."""
     self.user = util_helper.generate_test_user()
     self.mock_account_id = str(util_helper.generate_dummy_aws_account_id())
     self.mock_arn = util_helper.generate_dummy_arn(self.mock_account_id)
     self.mock_account = account_helper.generate_aws_account(
         arn=self.mock_arn,
         aws_account_id=self.mock_account_id,
         user=self.user)
Esempio n. 28
0
 def setUp(self):
     """Set up data for tests."""
     self.account_number = str(_faker.pyint())
     self.account_number_not_found = str(_faker.pyint())
     self.user = util_helper.generate_test_user(self.account_number)
     self.internal_rh_header = util_helper.get_internal_identity_auth_header(
     )
     self.auth_class = IdentityHeaderAuthenticationInternalAllowFakeIdentityHeader(
     )
Esempio n. 29
0
 def setUp(self):
     """Set up an AwsCloudAccount for relevant events."""
     self.user = util_helper.generate_test_user()
     self.aws_account_id = util_helper.generate_dummy_aws_account_id()
     self.account = api_helper.generate_cloud_account(
         aws_account_id=self.aws_account_id,
         user=self.user,
         created_at=util_helper.utc_dt(2017, 12, 1, 0, 0, 0),
     )
Esempio n. 30
0
    def test_create_succeeds_when_account_verified(self):
        """Test saving and processing of a test ARN."""
        aws_account_id = util_helper.generate_dummy_aws_account_id()
        arn = util_helper.generate_dummy_arn(aws_account_id)
        role = util_helper.generate_dummy_role()
        region = random.choice(util_helper.SOME_AWS_REGIONS)
        running_instances = {
            region: [
                util_helper.generate_dummy_describe_instance(
                    state=aws.InstanceState.running),
                util_helper.generate_dummy_describe_instance(
                    state=aws.InstanceState.stopping)
            ]
        }

        validated_data = {
            'account_arn': arn,
        }

        mock_request = Mock()
        mock_request.user = util_helper.generate_test_user()
        context = {'request': mock_request}

        with patch.object(aws, 'verify_account_access') as mock_verify, \
                patch.object(aws.sts, 'boto3') as mock_boto3, \
                patch.object(aws, 'get_running_instances') as mock_get_run, \
                patch.object(account_serializers,
                             'copy_ami_snapshot') as mock_copy_snapshot:
            mock_assume_role = mock_boto3.client.return_value.assume_role
            mock_assume_role.return_value = role
            mock_verify.return_value = True, []
            mock_get_run.return_value = running_instances
            mock_copy_snapshot.return_value = None
            serializer = AwsAccountSerializer(context=context)

            result = serializer.create(validated_data)
            self.assertIsInstance(result, AwsAccount)

        account = AwsAccount.objects.get(aws_account_id=aws_account_id)
        self.assertEqual(aws_account_id, account.aws_account_id)
        self.assertEqual(arn, account.account_arn)

        instances = AwsInstance.objects.filter(account=account).all()
        self.assertEqual(len(running_instances[region]), len(instances))
        for region, mock_instances_list in running_instances.items():
            for mock_instance in mock_instances_list:
                instance_id = mock_instance['InstanceId']
                instance = AwsInstance.objects.get(ec2_instance_id=instance_id)
                self.assertIsInstance(instance, AwsInstance)
                self.assertEqual(region, instance.region)
                event = InstanceEvent.objects.get(instance=instance)
                self.assertIsInstance(event, InstanceEvent)
                self.assertEqual(InstanceEvent.TYPE.power_on, event.event_type)

        amis = AwsMachineImage.objects.filter(account=account).all()
        self.assertEqual(len(running_instances[region]), len(amis))