Commit 82b7b688 authored by Maribeth Pierce's avatar Maribeth Pierce
Browse files

remove last of api tests

parent 0a5dd022
Loading
Loading
Loading
Loading
+0 −350
Original line number Diff line number Diff line
"""Test account report summary API.

:caseautomation: automated
:casecomponent: api
:caseimportance: high
:caselevel: integration
:requirement: Cloud Meter
:testtype: functional
:upstream: yes
"""
from collections import namedtuple
from datetime import datetime, timedelta

import pytest

from integrade import api
from integrade.injector import (
    inject_aws_cloud_account,
    inject_instance_data,
)
from integrade.tests import (
    urls,
    utils,
)


class InstanceTagParams(namedtuple('InstanceTagParams',
                                   'name '
                                   'image_type '
                                   'exp_inst '
                                   'exp_images '
                                   'exp_rhel '
                                   'exp_openshift '
                                   'start '
                                   'end '
                                   'offset ',
                                   )):
    """Configuration parameters for scenarios of instance types and times.

    Parameters:
    name : str
        The name of the parameter, visible in test results for identification
    image_type : str
        An empty string or series of comma-separated tags (rhel or openshift)
    exp_inst : int | None
    exp_images : int | None
    exp_rhel : int | None
    exp_openshift : int | None
        The numbers of instances, images, RHEL, and OpenShift expected to be
        seen
    start : int
    end : int | None
        The start and end times the instance was run. The end time can be None,
        in which case the instance was started and is still running at this
        time.
    offset : int
        An offset for the date range used to fetch data. If 0, fetch the last
        30 days. If -30, fetch (roughly) "last month"

    """


@pytest.skip(reason='Maybe remove- check unit and UI tests first.')
@pytest.mark.parametrize('conf', [
    # No tagged images, started today and 2 weeks ago
    InstanceTagParams('untagged today', '', 1, 1, 0, 0, 0, None, 0),
    InstanceTagParams('untagged 2 weeks', '', 1, 1, 0, 0, 15, None, 0),
    # No tagged images, started and stopped last month
    InstanceTagParams('untagged last month', '', 0, 0, 0, 0, 60, 30, 0),
    # Tagged images started today
    InstanceTagParams('rhel today', 'rhel', 1, 1, 1, 0, 0, None, 0),
    InstanceTagParams('openshift today', 'openshift',
                      1, 1, 0, 1, 0, None, 0),
    InstanceTagParams('windows today', 'windows', 1, 1, 0, 0, 0, None, 0),
    InstanceTagParams('rhel+openshift today', 'rhel,openshift',
                      1, 1, 1, 1, 0, None, 0),
], ids=lambda p: p.name)
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)


class FutureParam(namedtuple('FutureParam', 'acct_age unknown')):
    """Configuration parameters for future instance scenarios.

    Parameters:
    acct_age : int
        The number of days old the account is
    unknown : bool
        True if we expect null/None responses because instance and image counts
        are unknown for the account in the current date range.

    """


@pytest.skip(reason='At least fix docstring. Also, uses injector. Remove?')
@pytest.mark.parametrize('param', [
    # We assume to know the information if the account existed during any
    # part of the date range
    FutureParam(100, False),
    FutureParam(30, False),
    # But not if it was created after
    FutureParam(29, True),
])
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


@pytest.skip(reason='Superuser, injector')
@pytest.mark.parametrize('impersonate', (False, True))
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)


@pytest.skip(reason='Should be tested via UI')
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)


@pytest.skip(reason='Tested via UI and unit tests')
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)
+0 −119
Original line number Diff line number Diff line
"""Test authentication with the server.

:caseautomation: automated
:casecomponent: api
:caseimportance: high
:caselevel: integration
:requirement: Cloud Meter
:testtype: functional
:upstream: yes
"""
import pytest

from integrade import api
from integrade.config import get_config
from integrade.tests import urls
from integrade.tests.utils import create_user_account
from integrade.utils import uuid4


@pytest.skip(reason='injector, also redundant?')
@pytest.mark.smoketest
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.'


@pytest.skip(reason='superuser, injector')
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']


@pytest.skip(reason='Redundant?')
@pytest.mark.parametrize(
    'endpoint', ('account', 'event', 'instance', 'image', 'report/instances'))
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.'}
+0 −107
Original line number Diff line number Diff line
"""Tests for user accounts.

:caseautomation: automated
:casecomponent: api
:caseimportance: high
:caselevel: integration
:requirement: Cloud Meter
:testtype: functional
:upstream: yes
"""
import random

import pytest

from integrade import api
from integrade.config import get_config
from integrade.injector import inject_aws_cloud_account
from integrade.tests import urls
from integrade.tests.utils import create_user_account, get_auth
from integrade.utils import gen_password, uuid4


@pytest.skip(reason='this doesn\'t seem like an actual test. No assertion.')
def test_create():
    """Ensure user accounts can be created with username and password.

    :id: 5099a61d-7aa6-4c1b-8408-d030f210cd08
    :description: Ensure an user account can be created by an super user
        account with only username and password.
    :steps: With an authenticated superuser, send a post request to
        /auth/user/create/ with an username and password.
    :expectedresults: The server returns a 201 response with the information of
        the created user. The information should include the information passed
        as payload to the create request and also an ID should be created.
    """
    create_user_account({
        'email': '',
        'password': gen_password(),
        'username': uuid4(),
    })


@pytest.skip(reason='this doesn\'t seem like an actual test. No assertion.')
def test_create_with_email():
    """Ensure user accounts can be created with username, email and password.

    :id: 003ac47f-9946-4ffe-b49d-732dbffe1cfc
    :description: Ensure an user account can be created by an super user
        account with username, email and password.
    :steps: With an authenticated superuser, send a post request to
        /auth/user/create/ with an username, email and password.
    :expectedresults: The server returns a 201 response with the information of
        the created user. The information should include the information passed
        as payload to the create request and also an ID should be created.
    """
    create_user_account({
        'email': 'my@email.com',
        'username': uuid4(),
        'password': gen_password()
    })


@pytest.skip(reason='superuser')
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