Example #1
0
def test_runtime_requests_from_future():
    """Test future start and end times for empty set result.

    :id: 133A04EE-55C3-4948-B2F9-D89A6A84C9FC
    :description: Test events that start/end in the future ensuring
        that results are empty [].
    :steps:
        1) Add a cloud account
        2) Insert past instance, image, and event data
        3) Insert future instance, image, and event data
        4) GET from the image report endpoint
    :expectedresults:
        - When start/end times are in the future OR when start>end
            expect runtine_seconds to be empty.
    """
    user = utils.create_user_account()
    auth = utils.get_auth(user)
    acct = inject_aws_cloud_account(user['id'])
    image_type = 'openshift'
    instance_start = 2
    instance_end = 1
    client = api.Client(authenticate=False, response_handler=api.echo_handler)
    events = [instance_start]
    if instance_end:
        events.append(instance_end)
    inject_instance_data(acct['id'], image_type, events)

    report_start, report_end = utils.get_time_range(180)
    params = {
        'start': report_start,
        'end': report_end,
        'account_id': acct['id'],
    }
    response = client.get(urls.REPORT_ACCOUNTS, params=params, auth=auth)
    response_data = response.json()['cloud_account_overviews'][0]
    rhel_instances = response_data['rhel_instances']
    openshift_instances = response_data['openshift_instances']
    rhel_runtime_seconds = response_data['rhel_runtime_seconds']
    openshift_runtime_seconds = response_data['openshift_runtime_seconds']

    assert rhel_instances is None
    assert openshift_instances is None
    assert rhel_runtime_seconds is None
    assert openshift_runtime_seconds is None
    past_date = datetime.datetime.now() + datetime.timedelta(-30)
    backwards_params = {
        'start': report_start,
        'end': past_date,
        'account_id': acct['id'],
    }
    response = client.get(
        urls.REPORT_ACCOUNTS,
        params=backwards_params,
        auth=auth,
    )
    response_error = response.json()['non_field_errors'][0]
    assert response_error == 'End date must be after start date.'
Example #2
0
def test_future_instances(param):
    """Test instance events generate usage summary results for correct tags.

    :id: f3c84697-a40c-40d9-846d-117e2647e9d3
    :description: Test combinations of image tags, start/end events, and the
        resulting counts from the summary report API.
    :steps:
        1) Add a cloud account
        2) Insert instance, image, and event data
        3) GET from the account report endpoint
    :expectedresults:
        - The instance, image, RHEL, and Openshift counts match the expectation
    """
    user = utils.create_user_account()
    auth = utils.get_auth(user)
    acct = inject_aws_cloud_account(user['id'], acct_age=param.acct_age)
    start, end = 0, None

    client = api.Client(authenticate=False)

    events = [start]
    if end:
        events.append(end)
    inject_instance_data(acct['id'], '', events)

    # Set date range for 30 days in the past
    start, end = utils.get_time_range(-30)
    params = {
        'start': start,
        'end': end,
    }
    response = client.get(urls.REPORT_ACCOUNTS, params=params, auth=auth)

    account = response.json()['cloud_account_overviews'][0]
    acct_creation = datetime.today() - timedelta(days=param.acct_age)

    start, end = utils.get_time_range(-30, formatted=False)
    if acct_creation < start:
        info = 'Account created before start of window'
    elif acct_creation > end:
        info = 'Account newer than window'
    else:
        info = 'Account created during window'

    assert account['cloud_account_id'] == acct['aws_account_id']

    if param.unknown:
        exp = None
    else:
        exp = 0
    assert account['images'] == exp, info
    assert account['instances'] == exp, info
    assert account['rhel_instances'] == exp, info
    assert account['openshift_instances'] == exp, info
Example #3
0
def test_list_account_while_impersonating(impersonate):
    """Test account data fetched via impersonating a user as a superuser.

    :id: 5f99c7ec-a4d3-4040-868f-9340015e4c9c
    :description: Test that the same assertions can be made for fetching data
        as a regular user and fetching data impersonating that same user
    :steps:
        1) Add a cloud account
        2) Insert instance, image, and event data
        3) GET from the account report endpoint as regular user
        3) GET from the account report endpoint as super user impersonating
    :expectedresults:
        - The instance, image, RHEL, and Openshift counts match the expectation
    """
    user = utils.create_user_account()
    auth = utils.get_auth(user)
    acct = inject_aws_cloud_account(user['id'])
    image_type = 'rhel'
    exp_inst = 1
    exp_images = 1
    exp_rhel = 1
    exp_openshift = 0
    start = 0
    end = None
    offset = 0

    # authenticate (as superuser) if we are impersonating
    client = api.Client(authenticate=impersonate)

    events = [start]
    if end:
        events.append(end)
    inject_instance_data(acct['id'], image_type, events)

    start, end = utils.get_time_range(offset)
    params = {
        'start': start,
        'end': end,
    }
    if impersonate:
        params['user_id'] = user['id']
    response = client.get(urls.REPORT_ACCOUNTS, params=params, auth=auth)

    account = response.json()['cloud_account_overviews'][0]

    assert account['cloud_account_id'] == acct['aws_account_id']
    assert account['images'] == exp_images, repr(account)
    assert account['instances'] == exp_inst, repr(account)
    assert account['rhel_instances'] == exp_rhel, repr(account)
    assert account['openshift_instances'] == exp_openshift, repr(account)
Example #4
0
def test_list_images_while_impersonating(impersonate):
    """Test account data fetched via impersonating a user as a superuser.

    :id: 5f99c7ec-a4d3-4040-868f-9340015e4c9c
    :description: Test that the same assertions can be made for fetching data
        as a regular user and fetching data impersonating that same user
    :steps:
        1) Add a cloud account
        2) Insert instance, image, and event data
        3) GET from the image report endpoint as regular user
        3) GET from the image report endpoint as super user impersonating
    :expectedresults:
        - The images are returned for the user and a super user, but
            no one else.
    """
    user = utils.create_user_account()
    auth = utils.get_auth(user)
    acct = inject_aws_cloud_account(user['id'])
    image_type = 'rhel'
    exp_rhel = True
    exp_openshift = False
    start = 12
    end = 10
    offset = 0
    # start and end values indicate number of days in the past
    # so their difference is the whole number of days of runtime
    expected_runtime = (start - end) * 24 * 60 * 60

    # authenticate (as superuser) if we are impersonating
    client = api.Client(authenticate=impersonate)

    events = [start]
    if end:
        events.append(end)
    inject_instance_data(acct['id'], image_type, events)

    report_start, report_end = utils.get_time_range(offset)
    params = {
        'start': report_start,
        'end': report_end,
        'account_id': acct['id'],
    }
    response = client.get(urls.REPORT_IMAGES, params=params, auth=auth)

    image = response.json()['images'][0]
    assert image['rhel'] == exp_rhel, repr(image)
    assert image['openshift'] == exp_openshift, repr(image)
    assert int(image['runtime_seconds']) == int(expected_runtime), repr(image)
Example #5
0
def test_multiple_runs_counted_once():
    """Test instances being run a different times in the same period count once.

    :id: 0e8d0475-54d9-43af-9c2b-23f84865c6b4
    :description: Within any single period of reporting an instance which has
        been started and stopped multiple times still counts just once.
    :steps:
        1) Add a cloud account
        2) Insert event data with more than one start and stop in the last 30
           day period
        3) GET from the account report endpoint
    :expectedresults:
        - The instance and image should only be counted once
    """
    user = utils.create_user_account()
    auth = utils.get_auth(user)
    acct = inject_aws_cloud_account(user['id'])
    image_type = ''
    exp_inst = 1
    exp_images = 1
    exp_rhel = 0
    exp_openshift = 0

    client = api.Client(authenticate=False)

    start, end = utils.get_time_range()
    params = {
        'start': start,
        'end': end,
    }

    events = [
        20,
        15,
        10,
        5,
    ]
    inject_instance_data(acct['id'], image_type, events)

    response = client.get(urls.REPORT_ACCOUNTS, params=params, auth=auth)

    account = response.json()['cloud_account_overviews'][0]

    assert account['cloud_account_id'] == acct['aws_account_id']
    assert account['images'] == exp_images, repr(account)
    assert account['instances'] == exp_inst, repr(account)
    assert account['rhel_instances'] == exp_rhel, repr(account)
    assert account['openshift_instances'] == exp_openshift, repr(account)
Example #6
0
def test_list_account_with_multiple():
    """Test that a user with multiple accounts can list all.

    :id: 1f16a664-a4ea-410e-9ff8-0a6e42cb4df2
    :description: Test that the same assertions can be made for fetching data
        with just one account works with multiple.
    :steps:
        1) Add a cloud account
        2) Insert instance, image, and event data
        3) GET from the account report endpoint as regular user
    :expectedresults:
        - The instance, image, RHEL, and Openshift counts match the expectation
    """
    user = utils.create_user_account()
    auth = utils.get_auth(user)
    acct = inject_aws_cloud_account(user['id'])
    image_type = 'rhel'
    exp_inst = 1
    exp_images = 1
    exp_rhel = 1
    exp_openshift = 0
    time = 0
    offset = 0

    acct2 = inject_aws_cloud_account(user['id'])

    client = api.Client(authenticate=False)

    inject_instance_data(acct['id'], image_type, [time])

    start, end = utils.get_time_range(offset)
    params = {
        'start': start,
        'end': end,
    }
    response = client.get(urls.REPORT_ACCOUNTS, params=params, auth=auth)

    accounts = response.json()['cloud_account_overviews']
    account = accounts[0]
    account2 = accounts[1]

    assert account['cloud_account_id'] == acct['aws_account_id']
    assert account2['cloud_account_id'] == acct2['aws_account_id']
    assert account['images'] == exp_images, repr(account)
    assert account['instances'] == exp_inst, repr(account)
    assert account['rhel_instances'] == exp_rhel, repr(account)
    assert account['openshift_instances'] == exp_openshift, repr(account)
Example #7
0
def test_past_without_instances():
    """Test accounts with instances only after the filter period.

    :id: 72aaa6e2-2c60-4e71-bb47-3644bd6beb71
    :description: Test that an account with instances that were created prior
        to the current report end date.
    :steps:
        1) Add a cloud account
        2) Inject instance data for today
        3) GET from the account report endpoint for 30 days ago
    :expectedresults:
        - The account is in the response and matches the created account
        - Instances, images, RHEL, and Openshift all have None counts
    """
    user = utils.create_user_account()
    auth = utils.get_auth(user)
    acct = inject_aws_cloud_account(user['id'])
    client = api.Client(authenticate=False)

    # ask for last 30 days
    report_start, report_end = utils.get_time_range()
    params = {
        'start': report_start,
        'end': report_end,
        'account_id': acct['id'],
    }

    response = client.get(urls.REPORT_IMAGES, params=params, auth=auth)
    images = response.json()['images']

    assert images == [], repr(images)

    # No tagged images, started 60 days ago and stopped 45 days ago
    image_type = ''
    instance_start = 60
    instance_end = 45
    events = [instance_start, instance_end]
    inject_instance_data(acct['id'], image_type, events)

    # test that still have no images in report
    response = client.get(urls.REPORT_IMAGES, params=params, auth=auth)
    images = response.json()['images']

    assert images == [], repr(images)
Example #8
0
def test_image_tagging(conf):
    """Test instance events generate image usage results with correct tags.

    :id: f3c84697-a40c-40d9-846d-117e2647e9d3
    :description: Test combinations of image tags, start/end events, and the
        resulting counts from the summary report API.
    :steps:
        1) Add a cloud account
        2) Insert instance, image, and event data
        3) GET from the image report endpoint
    :expectedresults:
        - The images have correct tags and usage amounts
    """
    user = utils.create_user_account()
    auth = utils.get_auth(user)
    acct = inject_aws_cloud_account(user['id'])
    image_type, exp_inst, exp_images, exp_rhel, exp_openshift, \
        instance_start, instance_end, offset = conf
    # start and end values indicate number of days in the past
    # so their difference is the whole number of days of runtime
    expected_runtime = (instance_start - instance_end) * 24 * 60 * 60
    client = api.Client(authenticate=False)

    events = [instance_start]
    if instance_end:
        events.append(instance_end)
    inject_instance_data(acct['id'], image_type, events)

    report_start, report_end = utils.get_time_range(offset)
    params = {
        'start': report_start,
        'end': report_end,
        'account_id': acct['id'],
    }
    response = client.get(urls.REPORT_IMAGES, params=params, auth=auth)

    image = response.json()['images'][0]
    assert image['rhel'] == exp_rhel, repr(image)
    assert image['openshift'] == exp_openshift, repr(image)
    assert int(image['runtime_seconds']) == int(expected_runtime), repr(image)
Example #9
0
def accounts_report_data():
    """Create cloud account data for the accounts report tests.

    Create three cloud accounts and create some instance data.
    """
    user = utils.create_user_account()
    auth = utils.get_auth(user)
    first_account = inject_aws_cloud_account(
        user['id'],
        name='a greatest account ever',
    )
    second_account = inject_aws_cloud_account(
        user['id'],
        name='b just another account',
    )
    third_account = inject_aws_cloud_account(
        user['id'],
        name='c my awesome account',
    )

    # Make first account have one RHEL instance and image that was running for
    # 3 days
    inject_instance_data(first_account['id'], 'rhel', [5, 2])

    # Make second account have one RHEL and one OpenShift instance and image
    # that was running for 5 days
    inject_instance_data(second_account['id'], 'rhel,openshift', [12, 7])

    # Make third account have one OpenShift instance and image that was running
    # for 10 days
    inject_instance_data(third_account['id'], 'openshift', [13, 3])

    return auth, first_account, second_account, third_account
Example #10
0
def test_list_account_tagging(conf):
    """Test instance events generate usage summary results for correct tags.

    :id: f3c84697-a40c-40d9-846d-117e2647e9d3
    :description: Test combinations of image tags, start/end events, and the
        resulting counts from the summary report API.
    :steps:
        1) Add a cloud account
        2) Insert instance, image, and event data
        3) GET from the account report endpoint
    :expectedresults:
        - The instance, image, RHEL, and Openshift counts match the expectation
    """
    user = utils.create_user_account()
    auth = utils.get_auth(user)
    acct = inject_aws_cloud_account(user['id'])
    image_type, exp_inst, exp_images, exp_rhel, exp_openshift, \
        start, end, offset = conf[1:]

    client = api.Client(authenticate=False)

    events = [start]
    if end:
        events.append(end)
    inject_instance_data(acct['id'], image_type, events)

    start, end = utils.get_time_range(offset)
    params = {
        'start': start,
        'end': end,
    }
    response = client.get(urls.REPORT_ACCOUNTS, params=params, auth=auth)

    account = response.json()['cloud_account_overviews'][0]

    assert account['cloud_account_id'] == acct['aws_account_id']
    assert account['images'] == exp_images, repr(account)
    assert account['instances'] == exp_inst, repr(account)
    assert account['rhel_instances'] == exp_rhel, repr(account)
    assert account['openshift_instances'] == exp_openshift, repr(account)
Example #11
0
def test_flagged_account_numbers():
    """Test the number of flagged images in accounts.

    :id: BBD687F5-0B78-4E86-8368-C5C8EEBD9263
    :description: Test that the number of images reported as flagged matches
    the flagged/challenged images in accounts.

    :steps:
        1) Add a cloud account
        2) Insert RHEL and RHOCP image
        3) Check number of challenged/flagged RHEL/RHOCP images
        4) Challenge images
        5) Check number of challenged/flagged RHEL/RHOCP images
    :expectedresults:
        - Challenged RHEL images = 0 when none are challenged
        - Challenged RHEL images > 0 when one or more are challenged
        - Challenged RHOCP images = 0 when none are challenged
        - Challenged RHOCP images > 0 when one or more are challenged
    """
    user = utils.create_user_account()
    auth = utils.get_auth(user)
    acct = inject_aws_cloud_account(user['id'])

    images = {}
    for tag in ('rhel', 'openshift'):
        image_type = tag
        events = [1, 2]
        client = api.Client(authenticate=False,
                            response_handler=api.echo_handler)
        images[tag] = inject_instance_data(
            acct['id'],
            image_type,
            events,
        )

        report_start, report_end = utils.get_time_range()
        params = {
            'start': report_start,
            'end': report_end,
            'account_id': acct['id'],
        }
    response = client.get(urls.REPORT_ACCOUNTS, params=params,
                          auth=auth).json()['cloud_account_overviews'][0]
    assert response['rhel_instances'] == 1
    assert response['openshift_instances'] == 1
    assert response['rhel_images_challenged'] == 0
    assert response['openshift_images_challenged'] == 0

    rhel_image = images.get('rhel')
    openshift_image = images.get('openshift')
    images = [rhel_image, openshift_image]
    # Shuffle images to be sure that each is called first, to ensure that
    # order doesn't matter
    shuffle(images)
    first_image_url = urljoin(urls.IMAGE, str(images[0]['image_id'])) + '/'
    second_image_url = urljoin(urls.IMAGE, str(images[1]['image_id'])) + '/'
    first_image_response = client.get(first_image_url, auth=auth).json()
    second_image = ''
    challenged_image = ''
    unchallenged_image = ''

    # Challenge first image
    if first_image_response['rhel']:
        first_image_response['rhel_challenged'] = True
        client.put(first_image_url, first_image_response, auth=auth)
        first_image = 'rhel'
        second_image = 'openshift'
        challenged_image = 'rhel_images_challenged'
        unchallenged_image = 'openshift_images_challenged'
    else:
        first_image_response['openshift_challenged'] = True
        client.put(first_image_url, first_image_response, auth=auth)
        first_image = 'openshift'
        second_image = 'rhel'
        challenged_image = 'openshift_images_challenged'
        unchallenged_image = 'rhel_images_challenged'
    first_response = client.get(urls.REPORT_ACCOUNTS, params=params,
                                auth=auth).json()['cloud_account_overviews'][0]

    assert first_response[challenged_image] == 1
    assert first_response[unchallenged_image] == 0
    assert first_response[f'{second_image}_instances'] == 1
    assert first_response[f'{first_image}_instances'] == 0

    # Challenge second image
    second_image_response = client.get(second_image_url, auth=auth).json()
    second_image_response[f'{second_image}_challenged'] = True

    client.put(second_image_url, second_image_response, auth=auth)
    second_response = client.get(
        urls.REPORT_ACCOUNTS, params=params,
        auth=auth).json()['cloud_account_overviews'][0]

    assert second_response[challenged_image] == 1
    assert second_response[unchallenged_image] == 1
    assert second_response[f'{second_image}_instances'] == 0
    assert second_response[f'{first_image}_instances'] == 0
Example #12
0
def test_multiple_accounts(
        events,
        drop_account_data,
        ui_user,
        ui_dashboard,
        browser_session):
    """Test that having multiple accounts does not interfere with detail view.

    :id: 8bc0e630-2f52-4c73-a46d-355a7f79e339
    :description: Test that having many accounts does not change how detail
        view works for a given individual account.
    :steps:
        1) Given a user and several cloud accounts, mock usage for an image
            associated with one of the accounts.
        2) Assert the accounts with no usage have no detail view.
        3) Navigate to the account detail view of the active account.
        4) Assert that the image is listed.
        5) Assert that the image has the correct number of hours displayed.
    :expectedresults:
        Only accounts with usage have detail views and having multiple accounts
        does not degrade any use of the detail view.
    """
    selenium = browser_session
    with return_url(selenium):

        ec2_ami_id = 'ami-{}'.format(randint(1000, 99999))
        hours, spare_min, events = get_expected_hours_in_past_30_days(events)
        hours = round_hours(hours, spare_min)
        accts = []
        num_accounts = 3
        active_account_indx = randint(0, num_accounts - 1)

        # inject aws accounts
        for _ in range(num_accounts):
            name = 'cloud_account_{}'.format(randint(1000000, 999999999))
            acct = inject_aws_cloud_account(ui_user['id'], name=name)
            accts.append(acct)

        selenium.refresh()
        time.sleep(1)

        # inject instance activity for the account
        account = accts[active_account_indx]
        inject_instance_data(
            account['id'],
            'rhel',
            events,
            ec2_ami_id=ec2_ami_id
        )
        selenium.refresh()
        time.sleep(1)

        for indx in range(len(accts)):
            acct = accts[indx]
            if indx != active_account_indx:
                account_bar = find_element_by_text(selenium, acct['name'])
                account_bar.click()
                assert find_element_by_text(
                    selenium,
                    'No instances available',
                    exact=False)

        account_bar = find_element_by_text(selenium, account['name'])
        assert account_bar
        account_bar.click()

        time.sleep(1)
        ctn = selenium.find_element_by_css_selector('.list-view-pf-main-info')
        hours_el = find_element_by_text(ctn, f'RHEL', exact=False)
        hours_txt = hours_el.get_attribute('innerText')

        assert find_element_by_text(ctn, ec2_ami_id, exact=False)
        label = f'{hours}RHEL'
        assert find_element_by_text(ctn, label, exact=False),\
            f'"{hours} RHEL" expected; instead, saw "{hours_txt}"'
Example #13
0
def images_data():
    """Create test data for the tests on this module.

    To be able to verify that the image API endpoing works we need:

    * One super user acccount
    * Two regular user account
    * Image data for each user
    """
    utils.drop_image_data()

    user1 = utils.create_user_account()
    user2 = utils.create_user_account()
    auth1 = utils.get_auth(user1)
    auth2 = utils.get_auth(user2)

    # user1 will have 2 images
    images1 = [
        {
            'ec2_ami_id': str(random.randint(100000, 999999999999)),
            'rhel': True,
            'rhel_detected': True,
            'openshift': False,
            'openshift_detected': False,
        },
        {
            'ec2_ami_id': str(random.randint(100000, 999999999999)),
            'rhel': False,
            'rhel_detected': False,
            'openshift': True,
            'openshift_detected': True,
        },
    ]

    # user2 will have 3 images
    images2 = [
        {
            'ec2_ami_id': str(random.randint(100000, 999999999999)),
            'rhel': True,
            'rhel_detected': True,
            'openshift': False,
            'openshift_detected': False,
        },
        {
            'ec2_ami_id': str(random.randint(100000, 999999999999)),
            'rhel': True,
            'rhel_detected': True,
            'openshift': True,
            'openshift_detected': True,
        },
        {
            'ec2_ami_id': str(random.randint(100000, 999999999999)),
            'rhel': False,
            'rhel_detected': False,
            'openshift': True,
            'openshift_detected': True,
        },
    ]

    for user, images in zip((user1, user2), (images1, images2)):
        account = inject_aws_cloud_account(
            user['id'],
            name=uuid4(),
        )

        for image in images:
            if image['rhel'] and image['openshift']:
                image_type = 'rhel,openshift'
            elif image['rhel'] and not image['openshift']:
                image_type = 'rhel'
            elif not image['rhel'] and image['openshift']:
                image_type = 'openshift'
            else:
                raise ValueError('Not a valid image type.')

            image['id'] = inject_instance_data(
                account['id'],
                image_type,
                [random.randint(0, 20)],
                ec2_ami_id=image['ec2_ami_id'],
            )['image_id']

    return user1, user2, auth1, auth2, images1, images2
Example #14
0
def test_challenge_image(superuser, method):
    """Test if a challenge flags for RHEL and OS can be changed.

    :id: ec5fe0b6-9852-48db-a2ba-98d01aeaac28
    :description: Try to change challenge flags on an image and ensure that
        change is reflected afterwards.
    :steps:
        1. Create an image in a known account and make sure the challenge
           flags are false by default.
        2. Use both PUT and PATCH forms of the image endpoint to set a flag to
           true
    :expectedresults:
        The image data now reflects this change.
    """
    cfg = config.get_config()
    user = utils.create_user_account()
    auth = utils.get_auth(user)

    client = api.Client(authenticate=False)
    account = inject_aws_cloud_account(
        user['id'],
        name=uuid4(),
    )
    image_type = ''
    ec2_ami_id = str(random.randint(100000, 999999999999))

    image_id = inject_instance_data(
        account['id'],
        image_type,
        [random.randint(0, 20)],
        ec2_ami_id=ec2_ami_id,
    )['image_id']

    if superuser:
        auth = api.TokenAuth(cfg.get('superuser_token'))

    image_url = urljoin(urls.IMAGE, str(image_id)) + '/'

    # Ensure the image owner can fetch it
    response = client.get(image_url, auth=auth).json()

    assert response['rhel_challenged'] is False
    assert response['openshift_challenged'] is False

    for tag in ('rhel', 'openshift'):
        if method == 'put':
            response[f'{tag}_challenged'] = True
            response = client.put(image_url, response, auth=auth).json()
        elif method == 'patch':
            data = {
                'resourcetype': 'AwsMachineImage',
                f'{tag}_challenged': True,
            }
            response = client.patch(image_url, data, auth=auth).json()
        else:
            pytest.fail(f'Unknown method "{method}"')
        assert response[f'{tag}_challenged'] is True

    # Make sure the change is reflected in new responses
    response = client.get(image_url, auth=auth).json()
    response[f'{tag}_challenged'] = True

    # Ensure any other user can't fetch it
    response = client.get(image_url, auth=auth)
    assert response.status_code == 200
    assert response.json()[f'{tag}_challenged']
def instances_report_data():
    """Create instance usage data for the instance report tests.

    Create two cloud accounts and create some instance data for each of them.
    """
    user1 = utils.create_user_account()
    user2 = utils.create_user_account()
    auth1 = utils.get_auth(user1)
    auth2 = utils.get_auth(user2)
    plain_ami_id = str(random.randint(100000, 999999999999))
    rhel_ami_id = str(random.randint(100000, 999999999999))
    openshift_ami_id = str(random.randint(100000, 999999999999))
    rhel_openshift_ami_id = str(random.randint(100000, 999999999999))
    accounts1 = [
        inject_aws_cloud_account(
            user1['id'],
            name='greatest account ever',
        ),
        inject_aws_cloud_account(
            user1['id'],
            name='just another account',
        )
    ]

    # Run an unmetered instance from 3AM Jan 9th to 3AM the 11th
    inject_instance_data(
        accounts1[0]['id'],
        '',
        [
            utils.utc_dt(2018, 1, 9, 3, 0, 0),
            utils.utc_dt(2018, 1, 11, 3, 0, 0),
        ],
        ec2_ami_id=plain_ami_id,
    )
    # Run an OCP instance from 7AM Jan 11th to 5AM the 13th
    # With a 2 VCPU instance type, counting hours double towards
    # the 'openshift_vcpu_seconds' metric.
    # On the 11th: 17 hours
    # On the 12th: 24 hours
    # On the 13th: 5 hours
    inject_instance_data(
        accounts1[0]['id'],
        'openshift',
        [
            utils.utc_dt(2018, 1, 11, 7, 0, 0),
            utils.utc_dt(2018, 1, 13, 5, 0, 0),
        ],
        ec2_ami_id=openshift_ami_id,
        vcpu=2,
        memory=1,
    )
    # Run an OCP instance from 4AM Jan 1st to 9PM the 31st
    inject_instance_data(
        accounts1[0]['id'],
        'openshift',
        [
            utils.utc_dt(2018, 1, 1, 4, 0, 0),
            utils.utc_dt(2018, 1, 31, 21, 0, 0),
        ],
        ec2_ami_id=openshift_ami_id,
    )
    # Run a RHEL instance with multiple runtime durations
    # Dec 24th to 29th
    # Jan 8th to 10th
    # Jan 11th on and off multiple times
    # Jan 20th to 23rd
    inject_instance_data(
        accounts1[0]['id'],
        'rhel',
        [
            utils.utc_dt(2017, 12, 24, 3, 0, 0),
            utils.utc_dt(2017, 12, 29, 3, 0, 0),
            utils.utc_dt(2018, 1, 8, 5, 0, 0),
            utils.utc_dt(2018, 1, 10, 5, 0, 0),

            utils.utc_dt(2018, 1, 11, 5, 0, 0),
            utils.utc_dt(2018, 1, 11, 6, 0, 0),
            utils.utc_dt(2018, 1, 11, 7, 0, 0),
            utils.utc_dt(2018, 1, 11, 8, 0, 0),
            utils.utc_dt(2018, 1, 11, 9, 0, 0),
            utils.utc_dt(2018, 1, 11, 10, 0, 0),

            utils.utc_dt(2018, 2, 20, 5, 0, 0),
            utils.utc_dt(2018, 2, 23, 5, 0, 0),
        ],
        ec2_ami_id=rhel_ami_id,
    )
    # Run a RHEL instance with multiple runtime durations,
    # on a different account and with 2 vCPU instances, so double counting
    # hours for the RHEL vCPU metrics accordingly:
    # Jan 12: 21 hours (6 + 1 + 14, see below)
    inject_instance_data(
        accounts1[1]['id'],
        'rhel',
        [
            # Run for 6 hours
            utils.utc_dt(2018, 1, 12, 0, 0, 0),
            utils.utc_dt(2018, 1, 12, 6, 0, 0),
            # Run for 1 hour
            utils.utc_dt(2018, 1, 12, 7, 0, 0),
            utils.utc_dt(2018, 1, 12, 8, 0, 0),
            # Run for 14 hours
            utils.utc_dt(2018, 1, 12, 9, 0, 0),
            utils.utc_dt(2018, 1, 12, 23, 0, 0),
        ],
        ec2_ami_id=rhel_ami_id,
        vcpu=2,
        memory=1,
    )
    # Run a RHEL+OCP instance from Jan 9th at 9AM to the 14th at 9AM
    # With 2GB of memory, so double counting hours for the memory metrics
    # This adds extra to both RHEL and OCP memory hours metrics for each day:
    # Jan 9: 15 hours
    # jan 10-13: 24 hours
    # Jan 14: 9 hours
    inject_instance_data(
        accounts1[1]['id'],
        'rhel,openshift',
        [
            utils.utc_dt(2018, 1, 9, 9, 0, 0),
            utils.utc_dt(2018, 1, 14, 9, 0, 0),
        ],
        ec2_ami_id=rhel_openshift_ami_id,
        memory=2,
    )

    return user1, user2, auth1, auth2, accounts1
Example #16
0
 def factory(tag, events, **kwargs):
     name = kwargs.pop('name', None)
     if name:
         inject_aws_cloud_account(ui_user['id'], name=name)
     inject_instance_data(cloud_account['id'], tag, events, **kwargs)