コード例 #1
0
ファイル: test_login.py プロジェクト: jjeffers/integrade
def test_superuser_login():
    """Test that we can login as a super user and identify we are super.

    :id: 0815070f-5042-45ba-a6bb-f2596f764c7e
    :description: Test that we can login with a super user's credentials and
        that the token response includes a flag indicating super user status.
    :steps:
        1) Send POST with username and password to the token endpoint.
    :expectedresults:
        1) Receive an authorization token that can then be used to build
           authentication headers and make authenticated requests.
        2) Assert a 200 response is returned and the information about the
           logged in user are correct
        3) Assert the response includes the `is_superuser` field set to True
    """
    config = get_config()
    client = api.Client(authenticate=False)
    user = {
        'username': config['super_user_name'],
        'password': config['super_user_password'],
    }
    response = client.post(urls.AUTH_TOKEN_CREATE, user)
    assert response.status_code == 200
    json_response = response.json()
    assert 'auth_token' in json_response
    assert json_response['is_superuser']
コード例 #2
0
def test_list_accounts_empty(create_user_account):
    """Test accounts without any instance or image history have empty summaries.

    :id: 2a152ef6-fcd8-491c-b3cc-bda81699453a
    :description: Test that an account without any instances or images shows up
        in the results with 0 counts.
    :steps:
        1) Add a cloud account
        2) GET from the account report endpoint
    :expectedresults:
        - The account is in the response and matches the created account
        - Instances, images, RHEL, and Openshift all have 0 counts
    """
    user = create_user_account()
    auth = utils.get_auth(user)
    acct = inject_aws_cloud_account(user['id'])
    client = api.Client(authenticate=False)

    start, end = utils.get_time_range()
    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'] == 0, repr(account)
    assert account['instances'] == 0, repr(account)
    assert account['rhel_instances'] == 0, repr(account)
    assert account['openshift_instances'] == 0, repr(account)
コード例 #3
0
ファイル: test_api.py プロジェクト: jjeffers/integrade
def test_negative_create_no_token():
    """Raise an error if no config entry is found and no url specified."""
    cfg_missing_token = deepcopy(VALID_CONFIG)
    cfg_missing_token.pop('superuser_token')
    with patch.object(config, '_CONFIG', cfg_missing_token):
        with pytest.raises(exceptions.TokenNotFound):
            api.Client(authenticate=True)
コード例 #4
0
def test_negative_create_cloud_account_missing(drop_account_data,
                                               field_to_delete):
    """Ensure attempts to create cloud accounts missing data are rejected.

    :id: a93821ba-4181-47e7-b685-dbe642c1441e
    :description: Ensure an user cannot register a cloud account missing data.
    :steps: 1) Create a user and authenticate with their password
        2) Send a POST with the incomplete cloud account information to
            'api/v1/account/'
    :expectedresults: The server rejects the incomplete request.
    """
    auth = get_auth()
    client = api.Client(authenticate=False, response_handler=api.echo_handler)
    cfg = config.get_config()
    aws_profile = cfg['aws_profiles'][0]
    profile_name = aws_profile['name']
    acct_arn = aws_profile['arn']

    cloud_account = {
        'account_arn': acct_arn,
        'resourcetype': 'AwsAccount',
        'name': profile_name,
    }
    # remove one field
    cloud_account.pop(field_to_delete)
    create_response = client.post(urls.CLOUD_ACCOUNT,
                                  payload=cloud_account,
                                  auth=auth)
    missing_fields = create_response.json().keys()
    assert create_response.status_code == 400, create_response.json()
    assert field_to_delete in missing_fields, create_response.json()
コード例 #5
0
def test_image_report_empty():
    """Test accounts without any instance or image report has empty summary.

    :id: 2a152ef6-fcd8-491c-b3cc-bda81699453a
    :description: Test that an account without any instances or images shows up
        in the results with 0 counts.
    :steps:
        1) Add a cloud account
        2) GET from the image report endpoint
    :expectedresults:
        - An empty list is returned
    """
    user = utils.create_user_account()
    auth = utils.get_auth(user)
    acct = inject_aws_cloud_account(user['id'])
    client = api.Client(authenticate=False)

    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)
コード例 #6
0
def create_user_account():
    """Create a factory to create user accounts.

    This fixture creates a factory (a function) which will create a user
    account. Repeated calls will create return new users. All users created
    with this factory will delete any cloud accounts associated with the users
    after the test has run.

    Optional arguments can be passed as a dictionary:
        {'username': '******', 'password': '******', 'email': 'str'}

    If none are provided, values will be generated and returned.
    """
    users = []

    def factory(**kwargs):
        """Create a user, add it to our list of users, and return it."""
        user = utils.create_user_account(**kwargs)
        users.append(user)
        return user

    yield factory

    client = api.Client()

    for user in users:
        auth = utils.get_auth(user)
        while client.get(urls.CLOUD_ACCOUNT, auth=auth).json()['results']:
            account = client.get(
                urls.CLOUD_ACCOUNT, auth=auth).json()['results'][0]
            client.delete(urljoin(urls.CLOUD_ACCOUNT, str(account['id'])))
コード例 #7
0
def wait_for_cloudigrade_instance(
        instance_id, auth, timeout=800, sleep_period=15):
    """Wait for image to be inspected and assert on findings.

    :param instance_id: The ec2 instance id you expect to find.
    :param auth: the auth object for using with the server to authenticate as
        the user in question.

    :raises: AssertionError if the image is not inspected or if the results do
        not match the expected results for product identification.
    """
    # Wait, keeping track of what images are inspected
    client = api.Client(authenticate=False, response_handler=api.json_handler)
    start = time.time()
    timepassed = 0
    sys.stdout.write('\n')
    with click.progressbar(
            length=timeout,
            label=f'Waiting for instance {instance_id} to appear in'
            ' cloudigrade'
    ) as bar:
        while True:
            list_instances = client.get(urls.INSTANCE, auth=auth)
            found_instances = [instance['ec2_instance_id']
                               for instance in list_instances['results']]
            if instance_id in found_instances:
                return found_instances
            sleep(sleep_period)
            now = time.time()
            timepassed = now - start
            bar.update(timepassed)
            if timepassed >= timeout:
                return found_instances
コード例 #8
0
def test_superuser_instances_report(instances_report_data):
    """Test that a superuser can retrieves a regular user's instances report.

    :id: d222617b-9304-4081-9b95-f1a193412b6e
    :description: Test that a superuser can retrieve a regular user's instances
        report.
    :steps:
        1) Add a cloud account for a regular user
        2) Add some instance usage data for the following images: blank, RHEL,
           OpenShift and RHEL + OpenShift
        3) As a superuser, generate an instances report for a given period
           providing a regular user ID.
        4) Ensure the report only shows information about the usage on the
           given period.
    :expectedresults:
        An instances report can be generated by a superuser impersonating a
        regular user and the information provided is accurate.
    """
    user1, user2, auth1, auth2, accounts1 = instances_report_data
    cfg = config.get_config()
    superuser_auth = api.TokenAuth(cfg.get('superuser_token'))
    client = api.Client(response_handler=api.json_handler)

    response = client.get(
        urls.REPORT_INSTANCES,
        params={
            'start': REPORT_START_DATE,
            'end': REPORT_END_DATE,
            'user_id': user1['id'],
        },
        auth=superuser_auth
    )

    assert response == EXPECTED_REPORT_DATA, response
コード例 #9
0
def test_instances_report(instances_report_data):
    """Test that instances report provides expected results.

    :id: 7dd5ac11-7429-4030-9996-dbf3684f39e1
    :description: Test that regular users can retrieve their own instances
        report.
    :steps:
        1) Add a cloud account for a regular user
        2) Add some instance usage data for the following images: blank, RHEL,
           OpenShift and RHEL + OpenShift
        3) Generate an instances report for a given period.
        4) Ensure the report only shows information about the usage on the
           given period.
    :expectedresults:
        An instances report can be generated and the information provided is
        accurate.
    """
    user1, user2, auth1, auth2, accounts1 = instances_report_data
    client = api.Client(response_handler=api.json_handler)

    response = client.get(
        urls.REPORT_INSTANCES,
        params={
            'start': REPORT_START_DATE,
            'end': REPORT_END_DATE,
        },
        auth=auth1
    )

    for i, exp_data in enumerate(EXPECTED_REPORT_DATA['daily_usage']):
        seen_day = response['daily_usage'][i]
        vcpu = seen_day['rhel_vcpu_seconds']
        runtime = seen_day['rhel_runtime_seconds']
        assert exp_data == seen_day, (runtime - vcpu) / 60 / 60
コード例 #10
0
ファイル: test_api.py プロジェクト: jjeffers/integrade
def test_create_no_config():
    """If a base url is specified we use it."""
    with patch.object(config, '_CONFIG', {}):
        assert config.get_config() == {}
        other_host = 'http://hostname.com'
        client = api.Client(url=other_host, authenticate=False)
        assert 'http://example.com/api/v1/' != client.url
        assert other_host == client.url
コード例 #11
0
ファイル: test_api.py プロジェクト: jjeffers/integrade
def test_create_override_config():
    """If a base url is specified, we use that instead of config file."""
    with patch.object(config, '_CONFIG', VALID_CONFIG):
        other_host = 'http://hostname.com'
        client = api.Client(url=other_host, authenticate=False)
        cfg_host = config.get_config()['base_url']
        assert cfg_host != client.url
        assert other_host == client.url
コード例 #12
0
ファイル: test_api.py プロジェクト: jjeffers/integrade
def test_head(good_response):
    """Test that when we use the head method, a well formed request is sent."""
    with patch.object(config, '_CONFIG', VALID_CONFIG):
        cl = api.Client()
        cl.request = Mock(return_value=good_response)
        r = cl.head('api/v1/')
        assert r == good_response
        cl.request.assert_called_once_with(
            'HEAD', urljoin(cl.url, 'api/v1/'))
コード例 #13
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.'
コード例 #14
0
ファイル: test_api.py プロジェクト: jjeffers/integrade
def test_delete(good_response):
    """Test that the delete method sends a well formed request."""
    with patch.object(config, '_CONFIG', VALID_CONFIG):
        cl = api.Client()
        cl.request = Mock(return_value=good_response)
        r = cl.delete('api/v1/')
        assert r == good_response
        cl.request.assert_called_once_with(
            'DELETE', urljoin(cl.url, 'api/v1/'))
コード例 #15
0
ファイル: test_api.py プロジェクト: jjeffers/integrade
def test_patch(good_response):
    """Test that the patch method sends a well formed request."""
    with patch.object(config, '_CONFIG', VALID_CONFIG):
        cl = api.Client()
        cl.request = Mock(return_value=good_response)
        r = cl.patch('api/v1/', {})
        assert r == good_response
        cl.request.assert_called_once_with(
            'PATCH', urljoin(cl.url, 'api/v1/'), json={})
コード例 #16
0
def check_superuser():
    """Ensure that we have a valid superuser for the test run."""
    try:
        config.get_config()
        client = api.Client(response_handler=api.echo_handler)
        response = client.get(urls.AUTH_ME)
        assert response.status_code == 200, response.url
    except (AssertionError, exceptions.MissingConfigurationError) as e:
        pytest.fail('Super user creation must have failed. '
                    f'Error: {repr(e)}')
コード例 #17
0
def test_user_list(drop_account_data):
    """Super users can request lists of created user accounts.

    :id: 52567e92-2b6a-43b0-bdc0-5a347b9dd4bc
    :description: Super users, and only super users, are able to request a user
        list.
    :steps:
        1) Authenticate with a super user account and request the user list
            end point contains yourself and a created non-super user account.
        2) Authenticate with a non-super user account and request the user list
            to verify a 4xx error
    :expectedresults: The super user can get the list, but not the regular user
        account.
    """
    client = api.Client()
    response = client.get(urls.USER_LIST)
    pre_user_list = response.json()
    usernames = [user['username'] for user in pre_user_list]
    assert get_config()['super_user_name'] in usernames

    new_user = create_user_account()
    account_number = random.randint(2, 5)
    for _ in range(account_number):
        inject_aws_cloud_account(new_user['id'])
    response = client.get(urls.USER_LIST).json()

    for user in response:
        assert 'accounts' in user, user
        assert 'challenged_images' in user, user

        if user['id'] == new_user['id']:
            assert user['accounts'] == account_number
            assert user['challenged_images'] == 0

    new_user_list = [user for user in response if user not in pre_user_list]
    new_user_ids = [user['id'] for user in new_user_list]

    assert new_user['id'] in new_user_ids

    auth = get_auth(new_user)
    client = api.Client(authenticate=False, response_handler=api.echo_handler)
    response = client.get(urls.USER_LIST, auth=auth)
    assert response.status_code == 403
コード例 #18
0
def test_filter_by_account_id_and_name(accounts_report_data, superuser):
    """Test that cloud accounts report can be filtered by account ID and name.

    :id: edacb611-dfec-4d8b-b480-b0c0d901c08e
    :description: Test that regular users and superusers can filter cloud
        accounts by account ID and name. This is not useful since the account
        ID will restrict the list to a single account but, since this is a
        possibility, ensure that an and operation will be done to match both
        account ID and name.
    :steps:
        1) Add three cloud accounts
        2) Insert some instance events for all accounts.
        3) Filter the cloud accounts by providing the account_id and a name
           pattern that does not match the account's name.
        4) Ensure an emptly list is returned since it won't match anything.
        5) Now update the account ID and the name pattern to match both the
           account ID and the name.
        4) Ensure a single account is returned and assert that their instance
           events are correct.
    :expectedresults:
        No result should be returned if both account ID and name pattern don't
        match any account. One result is returned when both account ID and name
        pattern match an account. All instance events should match for the
        matched account.
    """
    auth, first_account, second_account, third_account = accounts_report_data
    client = api.Client(authenticate=superuser)
    start, end = utils.get_time_range()
    params = {
        'end': end,
        'account_id': second_account['id'],
        'name_pattern': 'EaT sOme ToFu',
        'start': start,
    }
    if superuser:
        params['user_id'] = first_account['user_id']

    # No result will be returned since it will try to mach the account ID and
    # the name pattern
    response = client.get(urls.REPORT_ACCOUNTS, params=params, auth=auth)
    cloud_account_overviews = response.json()['cloud_account_overviews']
    assert len(cloud_account_overviews) == 0, cloud_account_overviews

    # Now update the account ID to point to an account that the name pattern
    # will match, it should return a single result.
    params['account_id'] = first_account['id']
    response = client.get(urls.REPORT_ACCOUNTS, params=params, auth=auth)
    cloud_account_overviews = response.json()['cloud_account_overviews']
    assert len(cloud_account_overviews) == 1, cloud_account_overviews
    account = cloud_account_overviews[0]
    assert first_account['aws_account_id'] == account['cloud_account_id']
    assert account['images'] == 1, repr(account)
    assert account['instances'] == 1, repr(account)
    assert account['rhel_instances'] == 1, repr(account)
    assert account['openshift_instances'] == 0, repr(account)
コード例 #19
0
ファイル: test_images.py プロジェクト: jjeffers/integrade
def test_list_specific_image(images_data):
    """Test if a specific image can be fetched.

    :id: 99aaec58-6053-476d-9674-ee650ffa33a9
    :description: Check if a regular user can fetch one of its images. Check if
        a superuser can fetch all images. Check if a regular user can't fetch
        an image that belongs to another user.
    :steps:
        1. Fetch all images
        2. For each image, check if its owner and a superuser can fetch each.
           Also check if another user can't fetch it.
    :expectedresults:
        A regular user can only fetch its images and a superuser can fetch all
        images.
    """
    user1, user2, auth1, auth2, images1, images2 = images_data
    cfg = config.get_config()
    superuser_auth = api.TokenAuth(cfg.get('superuser_token'))
    client = api.Client(authenticate=False)
    start, end = utils.get_time_range()

    response = client.get(urls.IMAGE, auth=superuser_auth).json()
    assert response['count'] == len(images1) + len(images2), response
    all_images = response['results']
    ec2_ami_ids1 = [image['ec2_ami_id'] for image in images1]
    ec2_ami_ids2 = [image['ec2_ami_id'] for image in images2]

    for image in all_images:
        if image['ec2_ami_id'] in ec2_ami_ids1:
            auth = auth1
            other_auth = auth2
        elif image['ec2_ami_id'] in ec2_ami_ids2:
            auth = auth2
            other_auth = auth1
        else:
            raise ValueError(
                f'{image} not in {ec2_ami_ids1} or {ec2_ami_ids2}')
        image_url = urljoin(urls.IMAGE, str(image['id']))

        # Ensure superuser can fetch it
        response = client.get(image_url, auth=superuser_auth).json()
        assert response == image

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

        # Ensure any other user can't fetch it
        old_handler = client.response_handler
        client.response_handler = api.echo_handler
        response = client.get(image_url, auth=other_auth)
        client.response_handler = old_handler
        assert response.status_code == 404
        assert response.json()['detail'] == 'Not found.'
コード例 #20
0
def test_another_users_instances_report(instances_report_data):
    """Test that a regular can't retrieve another regular user's instances report.

    :id: abc19456-327d-4707-b8d6-7a99a6151c1e
    :description: Test that a regular user can't retrieve a regular user's
        instances report.
    :steps:
        1) Create two regular users
        2) Add a cloud account for each user.
        3) Add some instance usage data for one of the regular users, using the
           following images: blank, RHEL, OpenShift and RHEL + OpenShift
        4) As the regular user that does not have the usage data, generate its
           instances report and ensure it is blank.
        5) As the regular user that does not have the usage data, try to
           impersonate the other regular user and generate an instances report.
        6) Ensure that a regular user can't impersonate another regular user
           and retrieve their instances report. And its own instances report
           will be returned.
    :expectedresults:
        An instances report cannot be generated by a regular impersonating
        another regular user. A regular user will always retrieve its own
        instances report, even when trying to impersonate another regular user.
    """
    user1, user2, auth1, auth2, accounts1 = instances_report_data
    client = api.Client(response_handler=api.json_handler)

    # Ensure that the second user's instances report is empty
    response = client.get(
        urls.REPORT_INSTANCES,
        params={
            'start': REPORT_START_DATE,
            'end': REPORT_END_DATE,
        },
        auth=auth2
    )
    assert response['instances_seen_with_openshift'] == 0, response
    assert response['instances_seen_with_rhel'] == 0, response
    for usage in response['daily_usage']:
        assert usage['openshift_instances'] == 0
        assert usage['openshift_runtime_seconds'] == 0
        assert usage['rhel_instances'] == 0
        assert usage['rhel_runtime_seconds'] == 0

    # Try to impersonate the first user and retrieve their instances report
    impersonate_response = client.get(
        urls.REPORT_INSTANCES,
        params={
            'start': REPORT_START_DATE,
            'end': REPORT_END_DATE,
            'user_id': user1['id'],
        },
        auth=auth2
    )
    assert impersonate_response == response
コード例 #21
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
コード例 #22
0
ファイル: test_api.py プロジェクト: jjeffers/integrade
def test_response_handlers(good_response, handler):
    """Test that when we get a good 2xx response, it is returned."""
    with patch.object(config, '_CONFIG', VALID_CONFIG):
        assert config.get_config() == VALID_CONFIG
        client = api.Client(
            authenticate=False,
            response_handler=handler
        )
        r = client.response_handler(good_response)
        if handler == api.json_handler:
            assert r == good_response.json()
        else:
            assert r == good_response
コード例 #23
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)
コード例 #24
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)
コード例 #25
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)
コード例 #26
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)
コード例 #27
0
ファイル: test_login.py プロジェクト: jjeffers/integrade
def test_login_logout():
    """Test that we can login, make requests and logout to the server.

    :id: 2eb55229-4e1e-4d35-ac4a-4f2424d37cf6
    :description: Test that we can login, make requests and logout to the
        server.
    :steps:
        1) Send POST with username and password to the token endpoint.
        2) Send a GET request to /auth/me/ with the authorization token from
           previous step in the headers.
        3) Send a POST request to /auth/token/destroy/.
        4) Try to access /auth/me/ again with the authorization token from step
           1.
    :expectedresults:
        1) Receive an authorization token that can then be used to build
           authentication headers and make authenticated requests.
        2) Assert a 200 response is returned and the information about the
           logged in user are correct, including being flagged as a non-super
           user
        3) Assert a 204 response is returned
        4) Assert a 401 response is returned and the detailed message states
           the authentication token is now invalid.
    """
    user = create_user_account()
    client = api.Client(authenticate=False)
    response = client.post(urls.AUTH_TOKEN_CREATE, user)
    assert response.status_code == 200
    json_response = response.json()
    assert 'auth_token' in json_response
    assert not json_response['is_superuser']
    auth = api.TokenAuth(json_response['auth_token'])

    response = client.get(urls.AUTH_ME, auth=auth)
    assert response.status_code == 200
    json_response = response.json()
    assert json_response['email'] == user['email']
    assert json_response['username'] == user['username']

    response = client.post(urls.AUTH_TOKEN_DESTROY, {}, auth=auth)
    assert response.status_code == 204

    client.response_handler = api.echo_handler
    response = client.get(urls.AUTH_ME, auth=auth)
    assert response.status_code == 401
    json_response = response.json()
    assert json_response['detail'] == 'Invalid token.'
コード例 #28
0
def test_sysconfig_negative():
    """Ensure unauthenticated requests can't access configuration information.

    :id: 41b8309d-610e-4980-904d-72e19c0e1b63
    :description: Ensure that unauthenticated requests to sysconfig can't
        access configuration information.
    :steps: Do an unauthenticated GET request to /api/v1/sysconfig/.
    :expectedresults: The server returns a 401 response informing that the
        authentication information is needed to access the system
        configuration.
    """
    client = api.Client(authenticate=False, response_handler=api.echo_handler)
    response = client.get(urls.SYSCONFIG)
    assert response.status_code == 401
    assert response.json() == {
        'detail': 'Authentication credentials were not provided.'
    }
コード例 #29
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)
    # TODO: refactor inject_aws_cloud_account to use seed data
    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]
    print(events)
    # 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)
コード例 #30
0
ファイル: test_login.py プロジェクト: jjeffers/integrade
def test_token_negative(endpoint):
    """Given that we have an invalid token, we cannot make requests.

    :id: a87f7069-3ee9-4435-a953-fd8664199419
    :description: Test that if we have a bad token, we cannot use it to make
        requests to any of the /api/v1/* endpoints
    :steps:
        1) Send a GET request with a invalid authorization token in the header
           to all /api/v1/* endpoints.
        2) Assert that we get a 401 response for all requests.
    :expectedresults: The server rejects our invalid token for all /api/v1/*
        endpoints.
    """
    client = api.Client(response_handler=api.echo_handler)
    auth = api.TokenAuth(uuid4())
    response = client.get(f'/api/v1/{endpoint}', auth=auth)
    assert response.status_code == 401
    assert response.json() == {'detail': 'Invalid token.'}