def setup_external_auth_ipa(**data): """Sets up the appliance for an external authentication with IPA. Keywords: get_groups: Get User Groups from External Authentication (httpd). ipaserver: IPA server address. iparealm: Realm. credentials: Key of the credential in credentials.yaml """ ssh = SSHClient() ensure_browser_open() login_admin() if data["ipaserver"] not in get_ntp_servers(): set_ntp_servers(data["ipaserver"]) sleep(120) auth = ExternalAuthSetting(get_groups=data.pop("get_groups", False)) auth.setup() logout() creds = credentials.get(data.pop("credentials"), {}) data.update(**creds) rc, out = ssh.run_command( "appliance_console_cli --ipaserver {ipaserver} --iparealm {iparealm} " "--ipaprincipal {principal} --ipapassword {password}".format(**data)) assert rc == 0, out assert "failed" not in out.lower( ), "External auth setup failed:\n{}".format(out) login_admin()
def test_user_login(): user = new_user() user.create() try: login.login(user.credential.principal, user.credential.secret) finally: login.login_admin()
def tagged_vm(new_tag, setup_provider, provider): ownership_vm = provider.data['ownership_vm'] tag_vm = VM.factory(ownership_vm, provider) tag_vm.add_tag(new_tag) yield tag_vm login.login_admin() tag_vm.remove_tag(new_tag)
def test_login(): """ Tests that the appliance can be logged into and shows dashboard page. """ pytest.sel.get(pytest.sel.base_url()) login.login_admin() assert dashboard.page.is_displayed(), "Could not determine if logged in" login.logout() assert login.page.is_displayed()
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()
def setup_external_auth_openldap(**data): """Sets up the appliance for an external authentication with OpenLdap. Keywords: get_groups: Get User Groups from External Authentication (httpd). ipaserver: IPA server address. iparealm: Realm. credentials: Key of the credential in credentials.yaml """ connect_kwargs = { 'username': credentials['host_default']['username'], 'password': credentials['host_default']['password'], 'hostname': data['ipaddress'], } appliance_obj = appliance.IPAppliance() appliance_name = 'cfmeappliance{}'.format(fauxfactory.gen_alpha(7).lower()) appliance_address = appliance_obj.address appliance_fqdn = '{}.{}'.format(appliance_name, data['domain_name']) with SSHClient(**connect_kwargs) as ldapserver_ssh: # updating the /etc/hosts is a workaround due to the # https://bugzilla.redhat.com/show_bug.cgi?id=1360928 command = 'echo "{}\t{}" >> /etc/hosts'.format(appliance_address, appliance_fqdn) ldapserver_ssh.run_command(command) ldapserver_ssh.get_file(remote_file=data['cert_filepath'], local_path=conf_path.strpath) ensure_browser_open() login_admin() auth = ExternalAuthSetting(get_groups=data.pop("get_groups", True)) auth.setup() appliance_obj.configure_appliance_for_openldap_ext_auth(appliance_fqdn) logout()
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
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')
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
def role_only_user_owned(): login.login_admin() role = ac.Role(name="role_only_user_owned_" + fauxfactory.gen_alphanumeric(), vm_restriction="Only User Owned") role.create() yield role login.login_admin() role.delete()
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_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 group_user_or_group_owned(role_user_or_group_owned): group = ac.Group(description='group_user_or_group_owned_' + fauxfactory.gen_alphanumeric(), role=role_user_or_group_owned.name) group.create() yield group login.login_admin() group.delete()
def setup_external_auth_ipa(**data): """Sets up the appliance for an external authentication with IPA. Keywords: get_groups: Get User Groups from External Authentication (httpd). ipaserver: IPA server address. iparealm: Realm. credentials: Key of the credential in credentials.yaml """ ssh = SSHClient() ensure_browser_open() login_admin() if data["ipaserver"] not in get_ntp_servers(): set_ntp_servers(data["ipaserver"]) sleep(120) auth = ExternalAuthSetting(get_groups=data.pop("get_groups", False)) auth.setup() logout() creds = credentials.get(data.pop("credentials"), {}) data.update(**creds) rc, out = ssh.run_command( "appliance_console_cli --ipaserver {ipaserver} --iparealm {iparealm} " "--ipaprincipal {principal} --ipapassword {password}".format(**data) ) assert rc == 0, out assert "failed" not in out.lower(), "External auth setup failed:\n{}".format(out) login_admin()
def test_permission_edit(request, product_features, action): """ Ensures that changes in permissions are enforced on next login """ product_features = version.pick(product_features) 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() with user: 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] }) with user: try: with error.expected(Exception): action() except error.UnexpectedSuccessException: pytest.Fails('Permissions have not been updated')
def test_permission_edit(request, product_features, action): """ Ensures that changes in permissions are enforced on next login """ product_features = version.pick(product_features) request.addfinalizer(login.login_admin) role_name = fauxfactory.gen_alphanumeric() role = ac.Role( name=role_name, vm_restriction=None, product_features=[(["Everything"], False)] + [(k, True) for k in product_features], # role_features ) role.create() group = new_group(role=role.name) group.create() user = new_user(group=group) user.create() with user: 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]}) with user: try: with error.expected(Exception): action() except error.UnexpectedSuccessException: pytest.Fails("Permissions have not been updated")
def tagged_vm(new_tag, setup_provider_modscope, provider): ownership_vm = provider.data['ownership_vm'] tag_vm = VM.factory(ownership_vm, provider) tag_vm.add_tag(new_tag) yield tag_vm login.login_admin() tag_vm.remove_tag(new_tag)
def setup_external_auth_openldap(**data): """Sets up the appliance for an external authentication with OpenLdap. Keywords: get_groups: Get User Groups from External Authentication (httpd). ipaserver: IPA server address. iparealm: Realm. credentials: Key of the credential in credentials.yaml """ connect_kwargs = { 'username': credentials['host_default']['username'], 'password': credentials['host_default']['password'], 'hostname': data['ipaddress'], } appliance_obj = appliance.IPAppliance() appliance_name = 'cfmeappliance{}'.format(fauxfactory.gen_alpha(7).lower()) appliance_address = appliance_obj.address appliance_fqdn = '{}.{}'.format(appliance_name, data['domain_name']) ldapserver_ssh = SSHClient(**connect_kwargs) # updating the /etc/hosts is a workaround due to the # https://bugzilla.redhat.com/show_bug.cgi?id=1360928 command = 'echo "{}\t{}" >> /etc/hosts'.format(appliance_address, appliance_fqdn) ldapserver_ssh.run_command(command) ldapserver_ssh.get_file(remote_file=data['cert_filepath'], local_path=conf_path.strpath) ldapserver_ssh.close() ensure_browser_open() login_admin() auth = ExternalAuthSetting(get_groups=data.pop("get_groups", True)) auth.setup() appliance_obj.configure_appliance_for_openldap_ext_auth(appliance_fqdn) logout()
def test_user_login(): user = new_user() user.create() try: with user: navigate_to(Server, 'Dashboard') finally: login.login_admin()
def role_user_or_group_owned(): login.login_admin() role = ac.Role(name='role_user_or_group_owned_' + fauxfactory.gen_alphanumeric(), vm_restriction='Only User or Group Owned') role.create() yield role login.login_admin() role.delete()
def test_user_login(): user = new_user() user.create() try: with user: sel.force_navigate("dashboard") finally: login.login_admin()
def test_login(method): """ Tests that the appliance can be logged into and shows dashboard page. """ pytest.sel.get(pytest.sel.base_url()) assert not pytest.sel.is_displayed(dashboard.page.user_dropdown) login.login_admin(submit_method=method) assert pytest.sel.is_displayed(dashboard.page.user_dropdown), "Could not determine if logged in" login.logout() assert login.page.is_displayed()
def test_user_login(): user = new_user() user.create() try: with user: sel.force_navigate('dashboard') finally: login.login_admin()
def test_user_login(): user = new_user() user.create() try: with user: navigate_to(Dashboard, "Main") finally: login.login_admin()
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 >= 3: # Need at least three tries: # 1: login_admin handles an alert or closes the browser due any error # 2: If login_admin handles an alert, go_to can still encounter an unexpected error # 3: 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 # NOQA # browser fixture should do this, but it's needed for subsequent calls ensure_browser_open() # Clear any running "spinnies" try: browser().execute_script('miqSparkleOff();') except: # miqSparkleOff undefined, so it's definitely off. pass try: # What we'd like to happen... login.login_admin() logger.info('Navigating to %s' % page_name) ui_navigate.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) else: # There was still an alert when we tried again, shoot the browser in the head logger.debug("Unxpected alert on try %d, recycling browser" % _tries) browser().quit() force_navigate(page_name, _tries, *args, **kwargs) except Exception as ex: # Anything else happened, nuke the browser and try again. logger.info('Caught %s during navigation, trying again.' % type(ex).__name__) logger.debug(format_exc()) browser().quit() force_navigate(page_name, _tries, *args, **kwargs)
def new_user(new_group): user = ac.User(name='user_' + fauxfactory.gen_alphanumeric(), credential=new_credential(), email='*****@*****.**', group=new_group) user.create() yield user login.login_admin() user.delete()
def disable_external_auth_ipa(): """Unconfigure external auth.""" ssh = SSHClient() ensure_browser_open() login_admin() auth = DatabaseAuthSetting() auth.update() rc, out = ssh.run_command("appliance_console_cli --uninstall-ipa") assert rc == 0, out
def disable_external_auth_ipa(): """Unconfigure external auth.""" ssh = SSHClient() ensure_browser_open() login_admin() auth = DatabaseAuthSetting() auth.update() assert ssh.run_command("appliance_console_cli --uninstall-ipa") appliance.IPAppliance().wait_for_web_ui() logout()
def new_user(group_only_user_owned): login.login_admin() user = ac.User(name='user_' + fauxfactory.gen_alphanumeric(), credential=new_credential(), email='*****@*****.**', group=group_only_user_owned, cost_center='Workload', value_assign='Database') user.create() return user
def disable_external_auth_ipa(): """Unconfigure external auth.""" with SSHClient() as ssh_client: ensure_browser_open() login_admin() auth = DatabaseAuthSetting() auth.update() assert ssh_client.run_command("appliance_console_cli --uninstall-ipa") appliance.IPAppliance().wait_for_web_ui() logout()
def configure_openldap_auth_mode(browser, available_auth_modes): """Configure LDAP authentication mode""" if 'openldap' in available_auth_modes: server_data = cfme_data.get('auth_modes', {})['openldap'] configuration.set_auth_mode(**server_data) yield login_admin() configuration.set_auth_mode(mode='database') else: yield
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")
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")
def generated_request(provider, provider_data, provisioning, template_name, vm_name): """Creates a provision request, that is not automatically approved, and returns the search data. After finishing the test, request should be automatically deleted. Slightly modified code from :py:module:`cfme.tests.infrastructure.test_provisioning` """ first_name = fauxfactory.gen_alphanumeric() last_name = fauxfactory.gen_alphanumeric() notes = fauxfactory.gen_alphanumeric() e_mail = "{}@{}.test".format(first_name, last_name) host, datastore = map(provisioning.get, ('host', 'datastore')) pytest.sel.force_navigate('infrastructure_provision_vms', context={ 'provider': provider, 'template_name': template_name, }) provisioning_data = { 'email': e_mail, 'first_name': first_name, 'last_name': last_name, 'notes': notes, 'vm_name': vm_name, 'host_name': {'name': [host]}, 'datastore_name': {'name': [datastore]}, 'num_vms': "10", # so it won't get auto-approved } # Same thing, different names. :\ if provider_data["type"] == 'rhevm': provisioning_data['provision_type'] = 'Native Clone' elif provider_data["type"] == 'virtualcenter': provisioning_data['provision_type'] = 'VMware' try: provisioning_data['vlan'] = provisioning['vlan'] except KeyError: # provisioning['vlan'] is required for rhevm provisioning if provider_data["type"] == 'rhevm': raise pytest.fail('rhevm requires a vlan value in provisioning info') provisioning_form.fill(provisioning_data) pytest.sel.click(provisioning_form.submit_button) flash.assert_no_errors() request_cells = { "Description": "Provision from [{}] to [{}###]".format(template_name, vm_name), } yield request_cells browser().get(store.base_url) login_admin() requests.delete_request(request_cells) flash.assert_no_errors()
def test_start_page(request, setup_a_provider, start_page): """ Tests start page Metadata: test_flag: visuals """ request.addfinalizer(set_default_page) visual.login_page = start_page login.logout() login.login_admin() level = re.split(r"\/", start_page) assert menu.is_page_active(level[0].strip(), level[1].strip()), "Landing Page Failed"
def logged_in(browser): """ Logs into the system as admin and then returns the browser object. Args: browser: Current browser object. Yields: Browser object """ ensure_browser_open() login_admin() yield browser()
def test_start_page(request, start_page): """ Tests start page Metadata: test_flag: visuals """ request.addfinalizer(set_default_page) visual.login_page = start_page login.logout() login.login_admin() match_args = landing_pages[start_page] assert match_location(**match_args), "Landing Page Failed"
def test_start_page(request, setup_a_provider, start_page): """ Tests start page Metadata: test_flag: visuals """ request.addfinalizer(set_default_page) visual.login_page = start_page login.logout() login.login_admin() match_args = landing_pages[start_page] assert match_location(**match_args), "Landing Page Failed"
def new_user(group_only_user_owned): login.login_admin() user = ac.User( name="user_" + fauxfactory.gen_alphanumeric(), credential=new_credential(), email="*****@*****.**", group=group_only_user_owned, cost_center="Workload", value_assign="Database", ) user.create() return user
def configure_openldap_auth_mode_default_groups(browser, available_auth_modes): """Configure LDAP authentication mode""" if 'openldap' in available_auth_modes: server_data = cfme_data.get('auth_modes', {})['openldap'] server_data['get_groups'] = False server_data['default_groups'] = 'EvmRole-user' configuration.set_auth_mode(**server_data) yield login_admin() configuration.set_auth_mode(mode='database') else: yield
def configure_aws_iam_auth_mode(browser, available_auth_modes): """Configure AWS IAM authentication mode""" if 'aws_iam' in available_auth_modes: aws_iam_data = dict(cfme_data.get('auth_modes', {})['aws_iam']) aws_iam_creds = credentials[aws_iam_data.pop('credentials')] aws_iam_data['access_key'] = aws_iam_creds['username'] aws_iam_data['secret_key'] = aws_iam_creds['password'] configuration.set_auth_mode(**aws_iam_data) yield login_admin() configuration.set_auth_mode(mode='database') else: yield
def generated_request(infra_provider, provider_data, provisioning, template_name, vm_name): """Creates a provision request, that is not automatically approved, and returns the search data. After finishing the test, request should be automatically deleted. Slightly modified code from :py:module:`cfme.tests.infrastructure.test_provisioning` """ first_name = fauxfactory.gen_alphanumeric() last_name = fauxfactory.gen_alphanumeric() notes = fauxfactory.gen_alphanumeric() e_mail = "{}@{}.test".format(first_name, last_name) host, datastore = map(provisioning.get, ('host', 'datastore')) vm = Vm(name=vm_name, provider=infra_provider, template_name=template_name) navigate_to(vm, 'ProvisionVM') provisioning_data = { 'email': e_mail, 'first_name': first_name, 'last_name': last_name, 'notes': notes, 'vm_name': vm_name, 'host_name': {'name': [host]}, 'datastore_name': {'name': [datastore]}, 'num_vms': "10", # so it won't get auto-approved } # Same thing, different names. :\ if provider_data["type"] == 'rhevm': provisioning_data['provision_type'] = 'Native Clone' elif provider_data["type"] == 'virtualcenter': provisioning_data['provision_type'] = 'VMware' try: provisioning_data['vlan'] = provisioning['vlan'] except KeyError: # provisioning['vlan'] is required for rhevm provisioning if provider_data["type"] == 'rhevm': raise pytest.fail('rhevm requires a vlan value in provisioning info') fill(provisioning_form, provisioning_data, action=provisioning_form.submit_button) flash.assert_no_errors() request_cells = { "Description": "Provision from [{}] to [{}###]".format(template_name, vm_name), } yield request_cells browser().get(store.base_url) login_admin() requests.delete_request(request_cells) flash.assert_no_errors()
def test_infra_start_page(request, start_page): """ Tests start page Metadata: test_flag: visuals """ request.addfinalizer(set_default_page) if visual.login_page != start_page: visual.login_page = start_page login.logout() login.login_admin() steps = map(lambda x: x.strip(), start_page.split('/')) longer_steps = copy(steps) longer_steps.insert(0, None)
def test_start_page(request, setup_a_provider, start_page): """ Tests start page Metadata: test_flag: visuals """ request.addfinalizer(set_default_page) visual.login_page = start_page login.logout() login.login_admin() level = re.split(r"\/", start_page) if current_version() >= 5.6: levels = (None, level[0].strip(), level[1].strip()) else: levels = (level[0].strip(), level[1].strip()) assert menu.nav.is_page_active(*levels), "Landing Page Failed"
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")