示例#1
0
def test_permissions(role, allowed_actions, disallowed_actions):
    # create a user and role
    role = role()  # call function to get role
    role.create()
    group = new_group(role=role.name)
    group.create()
    user = new_user(group=group)
    user.create()
    fails = {}
    try:
        login.login(user.credential.principal, user.credential.secret)
        for name, action_thunk in allowed_actions.items():
            try:
                action_thunk()
            except Exception as e:
                fails[name] = e
        for name, action_thunk in disallowed_actions.items():
            try:
                with error.expected(Exception):
                    action_thunk()
            except error.UnexpectedSuccessException as e:
                fails[name] = e
        if fails:
            raise Exception(fails)
    finally:
        login.login_admin()
def test_permissions(role, allowed_actions, disallowed_actions):
    # create a user and role
    role = role()  # call function to get role
    role.create()
    group = new_group(role=role.name)
    group.create()
    user = new_user(group=group)
    user.create()
    fails = {}
    try:
        login.login(user.credential.principal, user.credential.secret)
        for name, action_thunk in allowed_actions.items():
            try:
                action_thunk()
            except Exception as e:
                fails[name] = e
        for name, action_thunk in disallowed_actions.items():
            try:
                with error.expected(Exception):
                    action_thunk()
            except error.UnexpectedSuccessException as e:
                fails[name] = e
        if fails:
            raise Exception(fails)
    finally:
        login.login_admin()
def test_user_login():
    user = new_user()
    user.create()
    try:
        login.login(user.credential.principal, user.credential.secret)
    finally:
        login.login_admin()
示例#4
0
def test_group_roles(
        request, configure_aws_iam_auth_mode, group_name, group_data, setup_first_provider):
    """Basic default AWS_IAM group role RBAC test

    Validates expected menu and submenu names are present for default
    AWS IAM groups

    """
    request.addfinalizer(login_admin)

    # This should be removed but currently these roles are subject to a bug
    if version.current_version() >= '5.4' and group_name in ['evmgroup-administrator',
                                                             'evmgroup-approver',
                                                             'evmgroup-auditor',
                                                             'evmgroup-operator',
                                                             'evmgroup-security',
                                                             'evmgroup-support',
                                                             'evmgroup-user']:
        pytest.skip("This role currently fails this test")

    try:
        iam_group_name = group_name + '_aws_iam'
        username = credentials[iam_group_name]['username']
        password = credentials[iam_group_name]['password']
    except KeyError:
        pytest.fail('No match in credentials file for group "{}"'.format(iam_group_name))

    login(simple_user(username, password))
示例#5
0
 def reset_password():
     login.update_password(username, current_password, password)
     assert login.logged_in(), "password reset failed"
     login.logout()
     login.login(username, password)
     assert login.logged_in(), "password reset failed"
     login.logout()
示例#6
0
def test_permission_edit(request, product_features, action):
    """
    Ensures that changes in permissions are enforced on next login
    """
    request.addfinalizer(login.login_admin)
    role_name = fauxfactory.gen_alphanumeric()
    role = ac.Role(name=role_name,
                  vm_restriction=None,
                  product_features=[(['Everything'], False)] +    # role_features
                                   [(k, True) for k in product_features])
    role.create()
    group = new_group(role=role.name)
    group.create()
    user = new_user(group=group)
    user.create()
    login.login(user.credential.principal, user.credential.secret)
    try:
        action()
    except Exception:
        pytest.fail('Incorrect permissions set')
    login.login_admin()
    role.update({'product_features': [(['Everything'], True)] +
                                     [(k, False) for k in product_features]
                 })
    login.login(user.credential.principal, user.credential.secret)
    try:
        with error.expected(Exception):
            action()
    except error.UnexpectedSuccessException:
        pytest.Fails('Permissions have not been updated')
示例#7
0
def test_user_login():
    user = new_user()
    user.create()
    try:
        login.login(user.credential.principal, user.credential.secret)
    finally:
        login.login_admin()
def test_user_change_password(request):
    user = ac.User(
        name="user {}".format(fauxfactory.gen_alphanumeric()),
        credential=Credential(principal="user_principal_{}".format(
            fauxfactory.gen_alphanumeric()),
                              secret="very_secret",
                              verify_secret="very_secret"),
        email="*****@*****.**",
        group=usergrp,
    )
    user.create()
    request.addfinalizer(user.delete)
    request.addfinalizer(login.login_admin)
    with user:
        assert not login.logged_in()
        login.login(user)
        assert login.current_full_name() == user.name
    login.login_admin()
    with update(user):
        user.credential = Credential(
            principal=user.credential.principal,
            secret="another_very_secret",
            verify_secret="another_very_secret",
        )
    with user:
        assert not login.logged_in()
        login.login(user)
        assert login.current_full_name() == user.name
示例#9
0
def test_user_change_password(request):
    user = ac.User(
        name="user {}".format(fauxfactory.gen_alphanumeric()),
        credential=Credential(
            principal="user_principal_{}".format(fauxfactory.gen_alphanumeric()),
            secret="very_secret",
            verify_secret="very_secret"
        ),
        email="*****@*****.**",
        group=usergrp,
    )
    user.create()
    request.addfinalizer(user.delete)
    request.addfinalizer(login.login_admin)
    login.logout()
    assert not login.logged_in()
    login.login(user.credential.principal, user.credential.secret)
    assert login.current_full_name() == user.name
    login.login_admin()
    with update(user):
        user.credential = Credential(
            principal=user.credential.principal,
            secret="another_very_secret",
            verify_secret="another_very_secret",
        )
    login.logout()
    assert not login.logged_in()
    login.login(user.credential.principal, user.credential.secret)
    assert login.current_full_name() == user.name
示例#10
0
def test_permissions(role, allowed_actions, disallowed_actions):
    # create a user and role
    role = role()  # call function to get role
    role.create()
    group = new_group(role=role.name)
    group.create()
    user = new_user(group=group)
    user.create()
    fails = {}
    try:
        login.login(user.credential.principal, user.credential.secret)
        for name, action_thunk in allowed_actions.items():
            try:
                action_thunk()
            except Exception:
                fails[name] = "%s: %s" % (name, traceback.format_exc())
        for name, action_thunk in disallowed_actions.items():
            try:
                with error.expected(Exception):
                    action_thunk()
            except error.UnexpectedSuccessException:
                fails[name] = "%s: %s" % (name, traceback.format_exc())
        if fails:
            message = ''
            for failure in fails.values():
                message = "%s\n\n%s" % (message, failure)
            raise Exception(message)
    finally:
        login.login_admin()
示例#11
0
def test_group_roles(configure_ldap_auth_mode, group_name, group_data,
                     setup_first_provider):
    """Basic default LDAP group role RBAC test

    Validates expected menu and submenu names are present for default
    LDAP group roles

    """

    # This should be removed but currently these roles are subject to a bug
    if version.current_version() >= '5.4' and group_name in [
            'evmgroup-administrator', 'evmgroup-approver', 'evmgroup-auditor',
            'evmgroup-operator', 'evmgroup-security', 'evmgroup-support',
            'evmgroup-user'
    ]:
        pytest.skip("This role currently fails this test")

    try:
        username = credentials[group_name]['username']
        password = credentials[group_name]['password']
    except KeyError:
        pytest.fail(
            'No match in credentials file for group "{}"'.format(group_name))

    login(simple_user(username, password))
    assert set(menu.nav.visible_pages()) == set(group_data)
示例#12
0
def test_permission_edit(request, product_features, action):
    """
    Ensures that changes in permissions are enforced on next login
    """
    request.addfinalizer(login.login_admin)
    role_name = fauxfactory.gen_alphanumeric()
    role = ac.Role(
        name=role_name,
        vm_restriction=None,
        product_features=[(['Everything'], False)] +  # role_features
        [(k, True) for k in product_features])
    role.create()
    group = new_group(role=role.name)
    group.create()
    user = new_user(group=group)
    user.create()
    login.login(user.credential.principal, user.credential.secret)
    try:
        action()
    except Exception:
        pytest.fail('Incorrect permissions set')
    login.login_admin()
    role.update({
        'product_features':
        [(['Everything'], True)] + [(k, False) for k in product_features]
    })
    login.login(user.credential.principal, user.credential.secret)
    try:
        with error.expected(Exception):
            action()
    except error.UnexpectedSuccessException:
        pytest.Fails('Permissions have not been updated')
示例#13
0
def test_bad_password():
    """ Tests logging in with a bad password. """
    pytest.sel.get(pytest.sel.base_url())
    login(conf.credentials["default"]["username"], "badpassword@#$")
    expected_error = "the username or password you entered is incorrect"
    assert login_page.is_displayed()
    assert expected_error in pytest.sel.text(login_page.flash)
def test_group_roles(configure_ldap_auth_mode, group_name, group_data, setup_first_provider):
    """Basic default LDAP group role RBAC test

    Validates expected menu and submenu names are present for default
    LDAP group roles

    """

    # This should be removed but currently these roles are subject to a bug
    if version.current_version() >= '5.4' and group_name in ['evmgroup-administrator',
                                                             'evmgroup-approver',
                                                             'evmgroup-auditor',
                                                             'evmgroup-operator',
                                                             'evmgroup-security',
                                                             'evmgroup-support',
                                                             'evmgroup-user']:
        pytest.skip("This role currently fails this test")

    try:
        username = credentials[group_name]['username']
        password = credentials[group_name]['password']
    except KeyError:
        pytest.fail('No match in credentials file for group "{}"'.format(group_name))

    login(simple_user(username, password))
    assert set(menu.nav.visible_pages()) == set(group_data)
示例#15
0
def test_group_roles(request, configure_aws_iam_auth_mode, group_name,
                     group_data, infra_provider):
    """Basic default AWS_IAM group role RBAC test

    Validates expected menu and submenu names are present for default
    AWS IAM groups

    """
    request.addfinalizer(login_admin)

    # This should be removed but currently these roles are subject to a bug
    if version.current_version() >= '5.4' and group_name in [
            'evmgroup-administrator', 'evmgroup-approver', 'evmgroup-auditor',
            'evmgroup-operator', 'evmgroup-security', 'evmgroup-support',
            'evmgroup-user'
    ]:
        pytest.skip("This role currently fails this test")

    try:
        iam_group_name = group_name + '_aws_iam'
        username = credentials[iam_group_name]['username']
        password = credentials[iam_group_name]['password']
    except KeyError:
        pytest.fail('No match in credentials file for group "{}"'.format(
            iam_group_name))

    login(simple_user(username, password))
示例#16
0
def test_permissions(role, allowed_actions, disallowed_actions):
    # create a user and role
    role = role()  # call function to get role
    role.create()
    group = new_group(role=role.name)
    group.create()
    user = new_user(group=group)
    user.create()
    fails = {}
    try:
        with user:
            login.login(user)
            for name, action_thunk in allowed_actions.items():
                try:
                    action_thunk()
                except Exception:
                    fails[name] = "{}: {}".format(name, traceback.format_exc())
            for name, action_thunk in disallowed_actions.items():
                try:
                    with error.expected(Exception):
                        action_thunk()
                except error.UnexpectedSuccessException:
                    fails[name] = "{}: {}".format(name, traceback.format_exc())
            if fails:
                message = ''
                for failure in fails.values():
                    message = "{}\n\n{}".format(message, failure)
                raise Exception(message)
    finally:
        login.login_admin()
 def test_edit_user_password(self, rest_api, users):
     if "edit" not in rest_api.collections.users.action.all:
         pytest.skip("Edit action for users is not implemented in this version")
     user = users[0]
     new_password = fauxfactory.gen_alphanumeric()
     user.action.edit(password=new_password)
     cred = Credential(principal=user.userid, secret=new_password)
     new_user = User(credential=cred)
     login(new_user)
示例#18
0
def test_bad_password():
    """ Tests logging in with a bad password. """
    pytest.sel.get(pytest.sel.base_url())
    creds = Credential(principal=conf.credentials['default']['username'], secret="badpassword@#$")
    user = User(credential=creds)

    with error.expected("Sorry, the username or password you entered is incorrect."):
        login.login(user)
        assert login.page.is_displayed()
示例#19
0
def test_bad_password(request):
    """ Tests logging in with a bad password. """
    request.addfinalizer(login.login_admin)
    pytest.sel.get(pytest.sel.base_url())
    creds = Credential(principal=conf.credentials["default"]["username"], secret="badpassword@#$")
    user = User(credential=creds)

    with error.expected("Sorry, the username or password you entered is incorrect."):
        login.login(user)
        assert login.page.is_displayed()
 def test_edit_user_password(self, rest_api, users):
     if "edit" not in rest_api.collections.users.action.all:
         pytest.skip(
             "Edit action for users is not implemented in this version")
     user = users[0]
     new_password = fauxfactory.gen_alphanumeric()
     user.action.edit(password=new_password)
     cred = Credential(principal=user.userid, secret=new_password)
     new_user = User(credential=cred)
     login(new_user)
def test_group_ownership_on_user_or_group_role(request, user3,
                                               setup_infra_provider):
    set_vm_to_group = Vm('cu-9-5', setup_infra_provider)
    set_vm_to_group.set_ownership(group=user3.group.description)
    login.login(user3.credential.principal, user3.credential.secret)
    assert (set_vm_to_group.does_vm_exist_in_cfme(), "vm not found")
    # Unset the ownership
    login.login_admin()
    set_vm_to_group.unset_ownership()
    login.login(user3.credential.principal, user3.credential.secret)
    assert (not set_vm_to_group.does_vm_exist_in_cfme(), "vm exists")
示例#22
0
def test_bad_password():
    """ Tests logging in with a bad password. """
    pytest.sel.get(pytest.sel.base_url())
    creds = Credential(principal=conf.credentials['default']['username'],
                       secret="badpassword@#$")
    user = User(credential=creds)

    with error.expected(
            'Sorry, the username or password you entered is incorrect.'):
        login.login(user)
        assert login.page.is_displayed()
def test_user_ownership_crud(request, user1, setup_infra_provider):
    set_vm_to_user = Vm('cu-9-5', setup_infra_provider)
    # Set the ownership and checking it
    set_vm_to_user.set_ownership(user=user1.name)
    login.login(user1.credential.principal, user1.credential.secret)
    assert (set_vm_to_user.does_vm_exist_in_cfme(), "vm not found")
    # Unset the ownership
    login.login_admin()
    set_vm_to_user.unset_ownership()
    login.login(user1.credential.principal, user1.credential.secret)
    assert (not set_vm_to_user.does_vm_exist_in_cfme(), "vm exists")
示例#24
0
def test_external_auth_ipa(request, setup_first_provider, configure_external_auth_ipa_module):
    try:
        data = cfme_data.get("ipa_test", {})
    except KeyError:
        pytest.skip("No ipa_test section in yaml")
    group = Group(description='cfme', role="EvmRole-user")
    request.addfinalizer(group.delete)
    group.create()
    user = User(name=data["fullname"])
    request.addfinalizer(user.delete)
    request.addfinalizer(login.login_admin)
    login.login(data["username"], data["password"])
    assert login.current_full_name() == data["fullname"]
def test_openldap_auth(request, setup_first_provider, configure_openldap_auth_mode):
    data = cfme_data.get("openldap_test", {})
    if not data:
        pytest.skip("No openldap_test section in yaml")
    group = Group(description=data["group_name"], role="EvmRole-user")
    request.addfinalizer(group.delete)
    group.create()
    credentials = Credential(principal=data["username"], secret=data["password"], verify_secret=data["password"])
    user = User(name=data["fullname"], credential=credentials)
    request.addfinalizer(user.delete)
    request.addfinalizer(login.login_admin)
    with user:
        login.login(user)
        assert login.current_full_name() == data["fullname"]
    def test_edit_user_password(self, request, rest_api, users):
        """Tests editing user password.

        Metadata:
            test_flag: rest
        """
        request.addfinalizer(login_admin)
        user = users[0]
        new_password = fauxfactory.gen_alphanumeric()
        user.action.edit(password=new_password)
        assert rest_api.response.status_code == 200
        cred = Credential(principal=user.userid, secret=new_password)
        new_user = User(credential=cred)
        login(new_user)
示例#27
0
    def test_edit_user_password(self, request, appliance, users):
        """Tests editing user password.

        Metadata:
            test_flag: rest
        """
        request.addfinalizer(login_admin)
        user = users[0]
        new_password = fauxfactory.gen_alphanumeric()
        user.action.edit(password=new_password)
        assert appliance.rest_api.response.status_code == 200
        cred = Credential(principal=user.userid, secret=new_password)
        new_user = User(credential=cred)
        login(new_user)
def test_group_roles(configure_ldap_auth_mode, group_name, group_data):
    """Basic default LDAP group role RBAC test

    Validates expected menu and submenu names are present for default
    LDAP group roles

    """
    try:
        username = credentials[group_name]['username']
        password = credentials[group_name]['password']
    except KeyError:
        pytest.fail('No match in credentials file for group "%s"' % group_name)

    login(username, password)
    assert set(menu.visible_pages()) == set(group_data)
示例#29
0
def test_edit_user_password(rest_api, user):
    if "edit" not in rest_api.collections.users.action.all:
        pytest.skip("Edit action for users is not implemented in this version")
    try:
        for cur_user in rest_api.collections.users:
            if cur_user.userid != conf.credentials['default']['username']:
                rest_user = cur_user
                break
    except:
        pytest.skip("There is no user to change password")

    new_password = fauxfactory.gen_alphanumeric()
    rest_user.action.edit(password=new_password)
    cred = Credential(principal=rest_user.userid, secret=new_password)
    new_user = User(credential=cred)
    login(new_user)
示例#30
0
def test_edit_user_password(rest_api, user):
    if "edit" not in rest_api.collections.users.action.all:
        pytest.skip("Edit action for users is not implemented in this version")
    try:
        for cur_user in rest_api.collections.users:
            if cur_user.userid != conf.credentials['default']['username']:
                rest_user = cur_user
                break
    except:
        pytest.skip("There is no user to change password")

    new_password = fauxfactory.gen_alphanumeric()
    rest_user.action.edit(password=new_password)
    cred = Credential(principal=rest_user.userid, secret=new_password)
    new_user = User(credential=cred)
    login(new_user)
示例#31
0
def test_verify_password_update(request):
    """
    Tests that password changes are successful

    Warning: This will temporarily change the password for the default account.
    If you stop the tests unexpectedly, the password may not be reset to the default,
    making future logins based on the defaults unsuccessful until a manual reset of the
    password is done.

    If you need to manually reset the password, the current password should be the value
    of either new_password, username, or username + new_password.
    """
    username = conf.credentials['default']['username']
    password = conf.credentials['default']['password']
    new_password = "******"
    current_password = password

    # Check that original login credentials work
    login.login(username, current_password)
    assert login.logged_in(), "yaml credentials are incorrect!"

    # Reset password once this function stops
    def reset_password():
        login.update_password(username, current_password, password)
        assert login.logged_in(), "password reset failed"
        login.logout()
        login.login(username, password)
        assert login.logged_in(), "password reset failed"
        login.logout()

    request.addfinalizer(reset_password)

    # Simple update
    login.update_password(username, current_password, new_password)
    assert login.logged_in()
    current_password = new_password

    # Username as password
    login.update_password(username, current_password, username)
    assert login.logged_in()
    current_password = username

    # New password starts with old password
    login.update_password(username, current_password, current_password + new_password)
    assert login.logged_in()
    current_password = current_password + new_password
示例#32
0
def test_group_roles(configure_aws_iam_auth_mode, group_name, group_data):
    """Basic default AWS_IAM group role RBAC test

    Validates expected menu and submenu names are present for default
    AWS IAM groups

    """
    try:
        iam_group_name = group_name + '_aws_iam'
        username = credentials[iam_group_name]['username']
        password = credentials[iam_group_name]['password']
    except KeyError:
        pytest.fail('No match in credentials file for group "%s"' %
                    iam_group_name)

    login(username, password)
    assert set(menu.visible_pages()) == set(group_data)
示例#33
0
def test_auth_configure(request, configure_auth, group, user, data):
    """This test checks whether different cfme auth modes are working correctly.
       authmodes tested as part of this test: ext_ipa, ext_openldap, miq_openldap
       e.g. test_auth[ext-ipa_create-group]
        Prerequisities:
            * ``cfme_data.yaml`` file
        Steps:
            * Make sure corresponding auth_modes data is updated to ``cfme_data.yaml``
            * this test fetches the auth_modes from yaml and generates tests per auth_mode.
    """
    request.addfinalizer(auth_finalizer)
    with user:
        login.login(user, submit_method='click_on_login')
        assert login.current_full_name() == data['fullname']
        login.logout()
    login.login_admin()
    assert user.exists is True
def test_openldap_auth(request, setup_first_provider,
                       configure_openldap_auth_mode):
    data = cfme_data.get("openldap_test", {})
    if not data:
        pytest.skip("No openldap_test section in yaml")
    group = Group(description=data["group_name"], role="EvmRole-user")
    request.addfinalizer(group.delete)
    group.create()
    credentials = Credential(
        principal=data["username"],
        secret=data["password"],
        verify_secret=data["password"],
    )
    user = User(name=data["fullname"], credential=credentials)
    request.addfinalizer(user.delete)
    request.addfinalizer(login.login_admin)
    login.login(data["username"], data["password"])
    assert login.current_full_name() == data["fullname"]
def test_current_user_login_delete(request):
    """Test for deleting current user login.

    Steps:
        * Login as Admin user
        * Create a new user
        * Login with the new user
        * Try deleting the user
    """
    group_user = ac.Group("EvmGroup-super_administrator")
    user = ac.User(
        name='user' + fauxfactory.gen_alphanumeric(),
        credential=new_credential(),
        email='*****@*****.**',
        group=group_user)
    user.create()
    request.addfinalizer(user.delete)
    request.addfinalizer(login.login_admin)
    login.login(user.credential.principal, user.credential.secret)
    with error.expected("Current EVM User \"%s\" cannot be deleted" % user.name):
        user.delete()
示例#36
0
def test_openldap_auth(request, group, add_from_ldap, configure_openldap_auth_mode):
    data = cfme_data.get("openldap_test", {})
    if add_from_ldap:
        group.add_group_from_ldap_lookup()
    else:
        group.create()
    request.addfinalizer(group.delete)
    credentials = Credential(
        principal=data["username"],
        secret=data["password"],
        verify_secret=data["password"],
    )
    user = User(name=data["fullname"], credential=credentials)
    request.addfinalizer(user.delete)
    request.addfinalizer(login.login_admin)
    with user:
        login.login(user)
        assert login.current_full_name() == data["fullname"]
        login.logout()
    login.login_admin()
    assert user.exists is True
示例#37
0
def test_current_user_login_delete(request):
    """Test for deleting current user login.

    Steps:
        * Login as Admin user
        * Create a new user
        * Login with the new user
        * Try deleting the user
    """
    group_user = ac.Group("EvmGroup-super_administrator")
    user = ac.User(name='user' + fauxfactory.gen_alphanumeric(),
                   credential=new_credential(),
                   email='*****@*****.**',
                   group=group_user)
    user.create()
    request.addfinalizer(user.delete)
    request.addfinalizer(login.login_admin)
    login.login(user.credential.principal, user.credential.secret)
    with error.expected("Current EVM User \"%s\" cannot be deleted" %
                        user.name):
        user.delete()
示例#38
0
def test_verify_bad_password_update():
    """
    Tests that if any information on the password update form is incorrect that the system
    rejects the change attempt and does not update the login information
    """
    username = conf.credentials['default']['username']
    password = conf.credentials['default']['password']
    new_password = "******"

    # Ensure original login credentials work
    login.login(username, password)
    assert login.logged_in(), "yaml credentials are incorrect!"

    # Incorrect original password
    login.update_password(username, password + "ThisPartIsWrong", new_password)
    assert login.flash.is_error(login.flash.get_messages()[0])

    # New passwords don't match
    login.update_password(username, password, new_password, new_password + "3xtraCharacters")
    assert login.flash.is_error(login.flash.get_messages()[0])

    # Empty new password field
    login.clear_fields()
    login.update_password(username, password, "", new_password)
    assert login.flash.is_error(login.flash.get_messages()[0])

    # Empty new password verification field
    login.clear_fields()
    login.update_password(username, password, new_password, "")
    assert login.flash.is_error(login.flash.get_messages()[0])

    # Reset password to same password
    login.clear_fields()
    login.update_password(username, password, password)
    assert login.flash.is_error(login.flash.get_messages()[0])

    # Ensure original password still works
    login.close_password_update_form()
    login.login(username, password)
    assert login.logged_in(), "Password has been changed!"
def test_ownership_transfer(request, user1, user3, setup_infra_provider):
    set_vm_to_user = Vm('cu-9-5', setup_infra_provider)
    # Setting ownership
    login.login_admin()
    set_vm_to_user.set_ownership(user=user1.name)
    login.login(user1.credential.principal, user1.credential.secret)
    # Checking before and after the ownership transfer
    assert (set_vm_to_user.does_vm_exist_in_cfme(), "vm not found")
    set_vm_to_user.set_ownership(user=user3.name)
    assert (not set_vm_to_user.does_vm_exist_in_cfme(), "vm exists")
    login.login(user3.credential.principal, user3.credential.secret)
    assert (set_vm_to_user.does_vm_exist_in_cfme(), "vm not found")
    # Unset the ownership
    login.login_admin()
    set_vm_to_user.unset_ownership()
    login.login(user3.credential.principal, user3.credential.secret)
    assert (set_vm_to_user.does_vm_exist_in_cfme(), "vm exists")
def test_db_migrate(stabilize_current_appliance, db_url, db_version, db_desc):
    app = get_or_create_current_appliance()

    # Download the database
    logger.info("Downloading database: {}".format(db_desc))
    url_basename = os_path.basename(db_url)
    rc, out = app.ssh_client.run_command(
        'curl -o "/tmp/{}" "{}"'.format(url_basename, db_url), timeout=30)
    assert rc == 0, "Failed to download database: {}".format(out)

    # The v2_key is potentially here
    v2key_url = os_path.join(os_path.dirname(db_url), "v2_key")

    # Drop vmdb_production DB
    app.drop_database()

    # restore new DB and migrate it
    with app.ssh_client as ssh:
        rc, out = ssh.run_command('createdb vmdb_production', timeout=30)
        assert rc == 0, "Failed to create clean database: {}".format(out)
        rc, out = ssh.run_command(
            'pg_restore -v --dbname=vmdb_production /tmp/{}'.format(url_basename), timeout=600)
        assert rc == 0, "Failed to restore new database: {}".format(out)
        rc, out = ssh.run_rake_command("db:migrate", timeout=300)
        assert rc == 0, "Failed to migrate new database: {}".format(out)
        rc, out = ssh.run_rake_command(
            'db:migrate:status 2>/dev/null | grep "^\s*down"', timeout=30)
        assert rc != 0, "Migration failed; migrations in 'down' state found: {}".format(out)
        # fetch GUID and REGION from the DB and use it to replace data in /var/www/miq/vmdb/GUID
        # and /var/www/miq/vmdb/REGION respectively
        data_query = {
            'guid': 'select guid from miq_servers',
            'region': 'select region from miq_regions'
        }
        for data_type, db_query in data_query.items():
            data_filepath = '/var/www/miq/vmdb/{}'.format(data_type.upper())
            rc, out = ssh.run_command(
                'psql -d vmdb_production -t -c "{}"'.format(db_query), timeout=15)
            assert rc == 0, "Failed to fetch {}: {}".format(data_type, out)
            db_data = out.strip()
            assert db_data, "No {} found in database; query '{}' returned no records".format(
                data_type, db_query)
            rc, out = ssh.run_command(
                "echo -n '{}' > {}".format(db_data, data_filepath), timeout=15)
            assert rc == 0, "Failed to replace data in {} with '{}': {}".format(
                data_filepath, db_data, out)
        # fetch v2_key
        try:
            rc, out = ssh.run_command(
                'curl "{}"'.format(v2key_url), timeout=15)
            assert rc == 0, "Failed to download v2_key: {}".format(out)
            assert ":key:" in out, "Not a v2_key file: {}".format(out)
            rc, out = ssh.run_command(
                'curl -o "/var/www/miq/vmdb/certs/v2_key" "{}"'.format(v2key_url), timeout=15)
            assert rc == 0, "Failed to download v2_key: {}".format(out)
        # or change all invalid (now unavailable) passwords to 'invalid'
        except AssertionError:
            rc, out = ssh.run_command("fix_auth -i invalid", timeout=45)
            assert rc == 0, "Failed to change invalid passwords: {}".format(out)
    # start evmserverd, wait for web UI to start and try to log in
    try:
        app.start_evm_service()
    except ApplianceException:
        rc, out = app.ssh_client.run_rake_command("evm:start")
        assert rc == 0, "Couldn't start evmserverd: {}".format(out)
    app.wait_for_web_ui(timeout=600)
    # Reset user's password, just in case (necessary for customer DBs)
    rc, out = ssh.run_rails_command(
        '"u = User.find_by_userid(\'admin\'); u.password = \'{}\'; u.save!"'
        .format(app.user.credential.secret))
    assert rc == 0, "Failed to change UI password of {} to {}:" \
                    .format(app.user.credential.principal, app.user.credential.secret, out)
    login(app.user)
def test_db_migrate(app_creds, temp_appliance_extended_db, db_url, db_version,
                    db_desc):
    app = temp_appliance_extended_db

    # Download the database
    logger.info("Downloading database: {}".format(db_desc))
    url_basename = os_path.basename(db_url)
    rc, out = app.ssh_client.run_command('curl -o "/tmp/{}" "{}"'.format(
        url_basename, db_url),
                                         timeout=30)
    assert rc == 0, "Failed to download database: {}".format(out)

    # The v2_key is potentially here
    v2key_url = os_path.join(os_path.dirname(db_url), "v2_key")

    # Stop EVM service and drop vmdb_production DB
    app.stop_evm_service()
    app.drop_database()

    # restore new DB and migrate it
    with app.ssh_client as ssh:
        rc, out = ssh.run_command('createdb vmdb_production', timeout=30)
        assert rc == 0, "Failed to create clean database: {}".format(out)
        rc, out = ssh.run_command(
            'pg_restore -v --dbname=vmdb_production /tmp/{}'.format(
                url_basename),
            timeout=600)
        assert rc == 0, "Failed to restore new database: {}".format(out)
        rc, out = ssh.run_rake_command("db:migrate", timeout=300)
        assert rc == 0, "Failed to migrate new database: {}".format(out)
        rc, out = ssh.run_rake_command(
            'db:migrate:status 2>/dev/null | grep "^\s*down"', timeout=30)
        assert rc != 0, "Migration failed; migrations in 'down' state found: {}".format(
            out)
        # fetch GUID and REGION from the DB and use it to replace data in /var/www/miq/vmdb/GUID
        # and /var/www/miq/vmdb/REGION respectively
        data_query = {
            'guid': 'select guid from miq_servers',
            'region': 'select region from miq_regions'
        }
        for data_type, db_query in data_query.items():
            data_filepath = '/var/www/miq/vmdb/{}'.format(data_type.upper())
            rc, out = ssh.run_command(
                'psql -d vmdb_production -t -c "{}"'.format(db_query),
                timeout=15)
            assert rc == 0, "Failed to fetch {}: {}".format(data_type, out)
            db_data = out.strip()
            assert db_data, "No {} found in database; query '{}' returned no records".format(
                data_type, db_query)
            rc, out = ssh.run_command("echo -n '{}' > {}".format(
                db_data, data_filepath),
                                      timeout=15)
            assert rc == 0, "Failed to replace data in {} with '{}': {}".format(
                data_filepath, db_data, out)
        # fetch v2_key
        try:
            rc, out = ssh.run_command('curl "{}"'.format(v2key_url),
                                      timeout=15)
            assert rc == 0, "Failed to download v2_key: {}".format(out)
            assert ":key:" in out, "Not a v2_key file: {}".format(out)
            rc, out = ssh.run_command(
                'curl -o "/var/www/miq/vmdb/certs/v2_key" "{}"'.format(
                    v2key_url),
                timeout=15)
            assert rc == 0, "Failed to download v2_key: {}".format(out)
        # or change all invalid (now unavailable) passwords to 'invalid'
        except AssertionError:
            rc, out = ssh.run_command("fix_auth -i invalid", timeout=45)
            assert rc == 0, "Failed to change invalid passwords: {}".format(
                out)
        # fix db password
        rc, out = ssh.run_command("fix_auth --databaseyml -i {}".format(
            app_creds['password']),
                                  timeout=45)
        assert rc == 0, "Failed to change invalid password: {}".format(out)
    # start evmserverd, wait for web UI to start and try to log in
    try:
        app.start_evm_service()
    except ApplianceException:
        rc, out = app.ssh_client.run_rake_command("evm:start")
        assert rc == 0, "Couldn't start evmserverd: {}".format(out)
    app.wait_for_web_ui(timeout=600)
    # Reset user's password, just in case (necessary for customer DBs)
    rc, out = ssh.run_rails_command(
        '"u = User.find_by_userid(\'admin\'); u.password = \'{}\'; u.save!"'.
        format(app.user.credential.secret))
    assert rc == 0, "Failed to change UI password of {} to {}:" \
                    .format(app.user.credential.principal, app.user.credential.secret, out)
    login(app.user)
示例#42
0
 def _login_func():
     if not current_user:  # default to admin user
         login.login_admin()
     else:  # we recycled and want to log back in
         login.login(store.user)
示例#43
0
def force_navigate(page_name, _tries=0, *args, **kwargs):
    """force_navigate(page_name)

    Given a page name, attempt to navigate to that page no matter what breaks.

    Args:
        page_name: Name a page from the current :py:data:`ui_navigate.nav_tree` tree to navigate to.

    """
    if _tries > 2:
        # Need at least three tries:
        # 1: login_admin handles an alert or CannotContinueWithNavigation appears.
        # 2: Everything should work. If not, NavigationError.
        raise exceptions.NavigationError(page_name)

    _tries += 1

    logger.debug('force_navigate to %s, try %d' % (page_name, _tries))
    # circular import prevention: cfme.login uses functions in this module
    from cfme import login
    # Import the top-level nav menus for convenience
    from cfme.web_ui import menu

    # browser fixture should do this, but it's needed for subsequent calls
    ensure_browser_open()

    # Clear any running "spinnies"
    try:
        execute_script('miqSparkleOff();')
    except:
        # miqSparkleOff undefined, so it's definitely off.
        pass

    # Set this to True in the handlers below to trigger a browser restart
    recycle = False

    # remember the current user, if any
    current_user = login.current_user()

    try:
        # What we'd like to happen...
        if not current_user:  # default to admin user
            login.login_admin()
        else:  # we recycled and want to log back in
            login.login(current_user.username, current_user.password)
        logger.info('Navigating to %s' % page_name)
        menu.nav.go_to(page_name, *args, **kwargs)
    except (KeyboardInterrupt, ValueError):
        # KeyboardInterrupt: Don't block this while navigating
        # ValueError: ui_navigate.go_to can't handle this page, give up
        raise
    except UnexpectedAlertPresentException:
        if _tries == 1:
            # There was an alert, accept it and try again
            handle_alert(wait=0)
            force_navigate(page_name, _tries, *args, **kwargs)
        else:
            # There was still an alert when we tried again, shoot the browser in the head
            logger.debug('Unxpected alert, recycling browser')
            recycle = True
    except (ErrorInResponseException, InvalidSwitchToTargetException):
        # Unable to switch to the browser at all, need to recycle
        logger.info('Invalid browser state, recycling browser')
        recycle = True
    except exceptions.CannotContinueWithNavigation as e:
        # The some of the navigation steps cannot succeed
        logger.info('Cannot continue with navigation due to: %s; Recycling browser' % str(e))
        recycle = True
    except (NoSuchElementException, InvalidElementStateException, WebDriverException):
        from cfme.web_ui import cfme_exception as cfme_exc  # To prevent circular imports
        # If the page is blocked, then recycle...
        if is_displayed("//div[@id='blocker_div']"):
            logger.warning("Page was blocked with blocker div, recycling.")
            recycle = True
        elif cfme_exc.is_cfme_exception():
            logger.exception("CFME Exception before force_navigate started!: `{}`".format(
                cfme_exc.cfme_exception_text()
            ))
            recycle = True
        elif is_displayed("//body/div[@class='dialog' and ./h1 and ./p]"):
            # Rails exception detection
            logger.exception("Rails exception before force_navigate started!: {}:{} at {}".format(
                text("//body/div[@class='dialog']/h1").encode("utf-8"),
                text("//body/div[@class='dialog']/p").encode("utf-8"),
                current_url()
            ))
            recycle = True
        elif elements("//ul[@id='maintab']/li[@class='inactive']") and not\
                elements("//ul[@id='maintab']/li[@class='active']/ul/li"):
            # If upstream and is the bottom part of menu is not displayed
            logger.exception("Detected glitch from BZ#1112574. HEADSHOT!")
            recycle = True
        else:
            logger.error("Could not determine the reason for failing the navigation. Reraising.")
            raise

    if recycle:
        browser().quit()  # login.current_user() will be retained for next login
        logger.debug('browser killed on try %d' % _tries)
        # If given a "start" nav destination, it won't be valid after quitting the browser
        kwargs.pop("start", None)
        force_navigate(page_name, _tries, *args, **kwargs)
示例#44
0
def test_bad_password():
    """ Tests logging in with a bad password. """
    pytest.sel.get(pytest.sel.base_url())
    with error.expected('Sorry, the username or password you entered is incorrect.'):
        login.login(conf.credentials['default']['username'], "badpassword@#$")
    assert login.page.is_displayed()
 def _login_func():
     if not current_user:  # default to admin user
         login.login_admin()
     else:  # we recycled and want to log back in
         login.login(current_user.username, current_user.password)
示例#46
0
 def _login_func():
     if not current_user:  # default to admin user
         login.login_admin()
     else:  # we recycled and want to log back in
         login.login(current_user.username, current_user.password)
示例#47
0
def force_navigate(page_name, _tries=0, *args, **kwargs):
    """force_navigate(page_name)

    Given a page name, attempt to navigate to that page no matter what breaks.

    Args:
        page_name: Name a page from the current :py:data:`ui_navigate.nav_tree` tree to navigate to.

    """
    if _tries > 2:
        # Need at least three tries:
        # 1: login_admin handles an alert or CannotContinueWithNavigation appears.
        # 2: Everything should work. If not, NavigationError.
        raise exceptions.NavigationError(page_name)

    _tries += 1

    logger.debug('force_navigate to %s, try %d' % (page_name, _tries))
    # circular import prevention: cfme.login uses functions in this module
    from cfme import login
    # Import the top-level nav menus for convenience
    from cfme.web_ui import menu

    # browser fixture should do this, but it's needed for subsequent calls
    ensure_browser_open()

    # Clear any running "spinnies"
    try:
        execute_script('miqSparkleOff();')
    except:
        # miqSparkleOff undefined, so it's definitely off.
        pass

    # Set this to True in the handlers below to trigger a browser restart
    recycle = False

    # remember the current user, if any
    current_user = login.current_user()

    try:
        # What we'd like to happen...
        if not current_user:  # default to admin user
            login.login_admin()
        else:  # we recycled and want to log back in
            login.login(current_user.username, current_user.password)
        logger.info('Navigating to %s' % page_name)
        menu.nav.go_to(page_name, *args, **kwargs)
    except (KeyboardInterrupt, ValueError):
        # KeyboardInterrupt: Don't block this while navigating
        # ValueError: ui_navigate.go_to can't handle this page, give up
        raise
    except UnexpectedAlertPresentException:
        if _tries == 1:
            # There was an alert, accept it and try again
            handle_alert(wait=0)
            force_navigate(page_name, _tries, *args, **kwargs)
        else:
            # There was still an alert when we tried again, shoot the browser in the head
            logger.debug('Unxpected alert, recycling browser')
            recycle = True
    except (ErrorInResponseException, InvalidSwitchToTargetException):
        # Unable to switch to the browser at all, need to recycle
        logger.info('Invalid browser state, recycling browser')
        recycle = True
    except exceptions.CannotContinueWithNavigation as e:
        # The some of the navigation steps cannot succeed
        logger.info(
            'Cannot continue with navigation due to: %s; Recycling browser' %
            str(e))
        recycle = True
    except (NoSuchElementException, InvalidElementStateException,
            WebDriverException):
        from cfme.web_ui import cfme_exception as cfme_exc  # To prevent circular imports
        # If the page is blocked, then recycle...
        if is_displayed("//div[@id='blocker_div']"):
            logger.warning("Page was blocked with blocker div, recycling.")
            recycle = True
        elif cfme_exc.is_cfme_exception():
            logger.exception(
                "CFME Exception before force_navigate started!: `{}`".format(
                    cfme_exc.cfme_exception_text()))
            recycle = True
        elif is_displayed("//body/div[@class='dialog' and ./h1 and ./p]"):
            # Rails exception detection
            logger.exception(
                "Rails exception before force_navigate started!: {}:{} at {}".
                format(
                    text("//body/div[@class='dialog']/h1").encode("utf-8"),
                    text("//body/div[@class='dialog']/p").encode("utf-8"),
                    current_url()))
            recycle = True
        elif elements("//ul[@id='maintab']/li[@class='inactive']") and not\
                elements("//ul[@id='maintab']/li[@class='active']/ul/li"):
            # If upstream and is the bottom part of menu is not displayed
            logger.exception("Detected glitch from BZ#1112574. HEADSHOT!")
            recycle = True
        else:
            logger.error(
                "Could not determine the reason for failing the navigation. Reraising."
            )
            raise

    if recycle:
        browser().quit(
        )  # login.current_user() will be retained for next login
        logger.debug('browser killed on try %d' % _tries)
        # If given a "start" nav destination, it won't be valid after quitting the browser
        kwargs.pop("start", None)
        force_navigate(page_name, _tries, *args, **kwargs)