示例#1
0
 def test_get_noun(self):
     """Assert "get" requests work."""
     client = helper.SandboxedRestClient()
     client._force_authenticate(self.user)
     account = helper.generate_cloud_account(user=self.user)
     response = client.get_accounts(account.id)
     self.assertEqual(response.status_code, http.HTTPStatus.OK)
     response_json = response.json()
     self.assertEqual(response_json["account_id"], account.id)
示例#2
0
 def test_create_noun(self, mock_notify_sources):
     """Assert "create" requests work."""
     client = helper.SandboxedRestClient(api_root="/internal/api/cloudigrade/v1")
     client._force_authenticate(self.user)
     arn = util_helper.generate_dummy_arn()
     name = _faker.sentence()
     data = util_helper.generate_dummy_aws_cloud_account_post_data()
     data.update({"account_arn": arn, "name": name})
     response = client.create_accounts(data=data)
     self.assertEqual(response.status_code, http.HTTPStatus.CREATED)
     response_json = response.json()
     self.assertEqual(response_json["content_object"]["account_arn"], arn)
     self.assertEqual(response_json["name"], name)
     self.assertEqual(response_json["user_id"], self.user.id)
示例#3
0
    def test_action_noun_verb_detail(self):
        """Assert "detail" requests work."""
        client = helper.SandboxedRestClient()
        client._force_authenticate(self.user)

        account = helper.generate_cloud_account(user=self.user)
        image = helper.generate_image(status=MachineImage.INSPECTED)
        helper.generate_instance(account, image=image)

        response = client.post_machineimages(
            noun_id=image.id,
            detail="reinspect",
            api_root="/internal/api/cloudigrade/v1",
        )
        self.assertEqual(response.status_code, http.HTTPStatus.OK)
        self.assertEqual(MachineImage.PENDING, response.data["status"])
示例#4
0
 def test_list_noun(self):
     """Assert "list" requests work."""
     client = helper.SandboxedRestClient()
     client._force_authenticate(self.user)
     response = client.list_accounts()
     self.assertEqual(response.status_code, http.HTTPStatus.OK)
     response_json = response.json()
     self.assertIn("data", response_json)
     self.assertIsInstance(response_json["data"], list)
     self.assertIn("meta", response_json)
     self.assertIn("count", response_json["meta"])
     self.assertIn("links", response_json)
     self.assertIn("next", response_json["links"])
     self.assertIn("previous", response_json["links"])
     self.assertIn("first", response_json["links"])
     self.assertIn("last", response_json["links"])
示例#5
0
 def test_invalid_request(self):
     """Assert invalid requests raise AttributeError."""
     client = helper.SandboxedRestClient()
     with self.assertRaises(AttributeError):
         client.foo_bar()
示例#6
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()
        self.user3 = 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=models.MachineImage.UNAVAILABLE,
        )
        self.inspected_image = api_helper.generate_image(
            status=models.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),
        )
        self.events = []
        for instance, image in instance_images:
            self.events.extend(
                self.generate_events(powered_times, instance, image))

        self.client = api_helper.SandboxedRestClient(
            api_root="/internal/api/cloudigrade/v1")
        self.client._force_authenticate(self.user3)
示例#7
0
    def __init__(self):
        """Initialize all the data for the examples."""
        api_helper.generate_instance_type_definitions(cloud_type="aws")
        api_helper.generate_instance_type_definitions(cloud_type="azure")

        self.customer_account_number = "100001"
        self.customer_user = util_helper.get_test_user(
            self.customer_account_number, is_superuser=False)
        self.customer_user.date_joined = util_helper.utc_dt(
            2019, 1, 1, 0, 0, 0)
        self.customer_user.save()

        self.customer_client = api_helper.SandboxedRestClient()
        self.customer_client._force_authenticate(self.customer_user)
        self.internal_client = api_helper.SandboxedRestClient(
            api_root="/internal/api/cloudigrade/v1")
        self.internal_client._force_authenticate(self.customer_user)

        self.customer_arn = util_helper.generate_dummy_arn()

        # Times to use for various account and event activity.
        self.now = get_now()
        self.this_morning = self.now.replace(hour=0,
                                             minute=0,
                                             second=0,
                                             microsecond=0)
        self.yesterday = self.this_morning - timedelta(days=1)
        self.last_month = self.this_morning - timedelta(days=31)
        self.last_week = self.this_morning - timedelta(days=7)
        self.three_days_ago = self.this_morning - timedelta(days=3)
        self.two_days_ago = self.this_morning - timedelta(days=2)
        self.two_weeks_ago = self.this_morning - timedelta(weeks=2)
        self.tomorrow = self.this_morning + timedelta(days=1)
        self.next_week = self.this_morning + timedelta(weeks=1)

        ######################################
        # Generate AWS data for the customer user.
        self.aws_customer_account = api_helper.generate_cloud_account(
            arn=util_helper.generate_dummy_arn(),
            user=self.customer_user,
            name="greatest account ever",
            created_at=self.two_weeks_ago,
        )
        self.azure_customer_account = api_helper.generate_cloud_account(
            user=self.customer_user,
            name="meh account",
            created_at=self.two_weeks_ago,
            cloud_type="azure",
            azure_subscription_id=str(seeded_uuid4()),
            azure_tenant_id=str(seeded_uuid4()),
        )
        self.customer_instances = [
            api_helper.generate_instance(self.aws_customer_account),
            api_helper.generate_instance(self.aws_customer_account),
            api_helper.generate_instance(self.aws_customer_account),
            api_helper.generate_instance(self.azure_customer_account,
                                         cloud_type="azure"),
            api_helper.generate_instance(self.azure_customer_account,
                                         cloud_type="azure"),
            api_helper.generate_instance(self.azure_customer_account,
                                         cloud_type="azure"),
        ]

        # Generate events so we can see customer activity in the responses.
        # These events represent all customer instances starting one week ago,
        # stopping two days ago, and starting again yesterday.
        self.events = []
        for instance in self.customer_instances[:2]:
            self.events.extend(
                api_helper.generate_instance_events(
                    instance,
                    [
                        (self.last_week, self.three_days_ago),
                        (self.yesterday, None),
                    ],
                ))
        for instance in self.customer_instances[3:6]:
            self.events.extend(
                api_helper.generate_instance_events(
                    instance,
                    [
                        (self.last_week, self.three_days_ago),
                        (self.yesterday, None),
                    ],
                    cloud_type="azure",
                ))

        # Build the runs for the created events.
        # Note: this crude and *direct* implementation of Run-saving should be
        # replaced as we continue porting pilot functionality and (eventually)
        # better general-purpose Run-handling functions materialize.
        normalized_runs = normalize_runs(models.InstanceEvent.objects.all())
        for normalized_run in normalized_runs:
            run = models.Run(
                start_time=normalized_run.start_time,
                end_time=normalized_run.end_time,
                machineimage_id=normalized_run.image_id,
                instance_id=normalized_run.instance_id,
                instance_type=normalized_run.instance_type,
                memory=normalized_run.instance_memory,
                vcpu=normalized_run.instance_vcpu,
            )
            run.save()

        # Force all images to have RHEL detected ("7.7")
        self.images = list(
            set(instance.machine_image for instance in self.customer_instances
                if instance.machine_image is not None))
        for image in self.images:
            image.inspection_json = json.dumps({
                "rhel_enabled_repos_found": True,
                "rhel_version": "7.7",
                "syspurpose": {
                    "role": "Red Hat Enterprise Linux Server",
                    "service_level_agreement": "Premium",
                    "usage": "Development/Test",
                },
            })
            image.status = image.INSPECTED
            image.region = "us-east-1"
            image.save()

        # Pre-calculate concurrent usage data for upcoming requests.
        # Calculate each day since "last week" (oldest date we use in example requests).
        the_date = self.last_week.date()
        one_day_delta = timedelta(days=1)
        # while the_date <= self.this_morning.date():
        while the_date <= self.next_week.date():
            task_id = f"calculate-concurrent-usage-{seeded_uuid4()}"
            models.ConcurrentUsageCalculationTask.objects.create(
                user_id=self.customer_user.id,
                date=the_date.isoformat(),
                task_id=task_id,
                status=models.ConcurrentUsageCalculationTask.COMPLETE,
            )
            calculate_max_concurrent_usage(the_date, self.customer_user.id)
            the_date = the_date + one_day_delta