def step(self, *args, **kwargs): try: row = self.prerequisite_view.paginator.find_row_on_pages( table=self.prerequisite_view.entities, name=self.obj.name) row.click() except NoSuchElementException: raise ItemNotFound( 'Could not locate ansible repository table row with name {}'. format(self.obj.name))
def step(self, *args, **kwargs): """Navigate to the item""" try: row = self.prerequisite_view.entities.get_entity( name=self.obj.name, surf_pages=True) except ItemNotFound: raise ItemNotFound('Resource pool {} not found'.format( self.obj.name)) row.click()
def db_id(self): table = self.appliance.db.client['miq_ae_methods'] try: return self.appliance.db.client.session.query(table.id).filter( table.name == self.name, table.class_id == self.klass.db_id)[0] # noqa except IndexError: raise ItemNotFound( 'Method named {} not found in the database'.format(self.name))
def visible_widget(self): for widget in (self.input, self.dropdown, self.param_input, self.param_dropdown, self.select): try: widget.wait_displayed('15s') return widget except TimedOutError: pass else: raise ItemNotFound("Visible widget is not found")
def step(self, *args, **kwargs): self.prerequisite_view.toolbar.view_selector.select('List View') try: row = self.prerequisite_view.entities.get_entity( name=self.obj.name, surf_pages=True) except ItemNotFound: raise ItemNotFound( 'Could not locate host aggregate "{}" on provider {}'.format( self.obj.name, self.obj.provider.name)) row.click()
def step(self, *args, **kwargs): try: # ToDo: use get_entity method as JS API issue (#2898) resolve. row = self.prerequisite_view.entities.paginator.find_row_on_pages( self.prerequisite_view.entities.elements, key=self.obj.key) row.click() except NoSuchElementException: raise ItemNotFound('Could not locate container {}'.format( self.obj.key))
def db_id(self): table = self.appliance.db.client['miq_ae_namespaces'] try: return self.appliance.db.client.session.query(table.id).filter( table.name == self.name, table.parent_id == self.parent_obj.db_id)[0] # noqa except IndexError: raise ItemNotFound( 'Namespace named {} not found in the database'.format( self.name))
def step(self): try: row = self.prerequisite_view.paginator.find_row_on_pages( table=self.prerequisite_view.credentials, name=self.obj.name) row[0].click() except NoSuchElementException: raise ItemNotFound( 'Could not locate ansible credential table row with name {}'. format(self.obj.name)) self.prerequisite_view.toolbar.policy.item_select('Edit Tags')
def sort_by(self, option): """Sort VM list by using one of the 'Started','VM Name' or 'Status' option. Args: status(str): Takes status string as arg. """ try: self.sort_by_dropdown.item_select(option) except NoSuchElementException: raise ItemNotFound("Migration plan is in Not Started State," " hence sort_by dropdown not visible")
def _select_template(self, template_name, provider_name): try: self.parent.paginator.find_row_on_pages( self.parent.image_table, name=template_name, provider=provider_name).click() # image was not found, therefore raise an exception except IndexError: raise ItemNotFound( 'Cannot find template "{}" for provider "{}"'.format( template_name, provider_name))
def get_tags(self, tenant="My Company Tags"): """ Get list of tags assigned to item. Details entities should have smart_management widget For vm, providers, and other like pages 'SummaryTable' widget should be used, for user, group like pages(no tables on details page) use 'SummaryForm' Args: tenant: string, tags tenant, default is "My Company Tags" Returns: :py:class:`list` List of Tag objects Raises: ItemNotFound: when nav destination DNE, or times out on wait (is_displayed was false) """ try: view = navigate_to(self, 'Details') except (NavigationDestinationNotFound, DestinationNotFound): raise ItemNotFound( 'Details page does not exist for: {}'.format(self)) except TimedOutError: raise ItemNotFound( 'Timed out navigating to details for: {}'.format(self)) tags = [] entities = view.entities if hasattr(entities, 'smart_management'): tag_table = entities.smart_management else: tag_table = entities.summary('Smart Management') tags_text = tag_table.get_text_of(tenant) if tags_text != 'No {} have been assigned'.format(tenant): # check for users/groups page in case one tag string is returned for tag in [tags_text] if isinstance( tags_text, six.string_types) else list(tags_text): tag_category, tag_name = tag.split(':') category = self.appliance.collections.categories.instantiate( display_name=tag_category) tags.append( category.collections.tags.instantiate( display_name=tag_name.strip())) return tags
def host(provider): # TODO: Implement .filter() for OpenstackNode with all() """Find a host for test scenario""" host_collection = provider.appliance.collections.openstack_nodes hosts = host_collection.all(provider) # Find a compute host with no instances on it for host in hosts: view = navigate_to(host, 'Details') vms = int(view.entities.summary('Relationships').get_text_of('VMs')) if 'Compute' in host.name and vms == 0: return host raise ItemNotFound('There is no proper host for tests')
def check_hosts(self, hosts): hosts = list(hosts) checked_hosts = list() view = navigate_to(self, 'All') for host in hosts: try: view.entities.get_entity(name=host.name, surf_pages=True).ensure_checked() checked_hosts.append(host) except ItemNotFound: raise ItemNotFound(f'Could not find host {host.name} in the UI') return view
def delete(self, *objects): view = navigate_to(self, 'All') for obj in objects: try: view.entities.get_entity(key=obj.key, surf_pages=True).check() except ItemNotFound: raise ItemNotFound('Could not locate object {}'.format( obj.key)) view.toolbar.configuration.item_select('Remove Object Storage Objects', handle_alert=True) view.flash.assert_no_error()
def visible_widget(self): if self.input.is_displayed: return self.input elif self.dropdown.is_displayed: return self.dropdown elif self.param_input.is_displayed: return self.param_input elif self.param_dropdown.is_displayed: return self.param_dropdown elif self.select.is_displayed: return self.select else: raise ItemNotFound("Visible widget is not found")
def delete(self, *objects): # TODO: capture flash message after BZ 1497113 resolve. view = navigate_to(self, 'All') for obj in objects: try: row = view.entities.paginator.find_row_on_pages( view.entities.elements, Key=obj.key) row[0].check() except NoSuchElementException: raise ItemNotFound('Could not locate object {}'.format(obj.key)) view.toolbar.configuration.item_select('Remove Object Storage Objects', handle_alert=True)
def delete(self, *volumes): """Delete one or more Volumes from list of Volumes Args: One or Multiple 'cfme.storage.volume.Volume' objects """ view = navigate_to(self, 'All') if view.entities.get_all(): for volume in volumes: try: view.entities.get_entity(name=volume.name).ensure_checked() except ItemNotFound: raise ItemNotFound(f"Volume {volume.name} not found") view.toolbar.configuration.item_select( 'Delete selected Cloud Volumes', handle_alert=True) for volume in volumes: volume.wait_for_disappear() else: raise ItemNotFound('No Cloud Volume for Deletion')
def filter_by_status(self, status): """Set filter_by_dropdown to 'Status' and uses status arg by user to set status filter. Args: status(str): Takes status string as arg. Valid status options are: ['Pending', 'Validating', 'Pre-migration', 'Migrating', 'VM Transformations Ccompleted', 'VM Transformations Failed'] """ try: self.filter_by_dropdown.item_select("Status") self.filter_by_status_dropdown.item_select(status) except NoSuchElementException: raise ItemNotFound("Migration plan is in Not Started State," " hence filter status dropdown not visible")
def find_quadicon(self, **kwargs): """Find and return a quadicon belonging to a specific instance TODO: remove this method and refactor callers to use view entities instead Args: Returns: entity of appropriate type """ view = navigate_to(self.parent, 'All') view.toolbar.view_selector.select('Grid View') try: return view.entities.get_entity(name=self.name, surf_pages=True) except ItemNotFound: raise ItemNotFound(f"Instance '{self.name}' not found in UI!")
def get_item(self, by_name=None, surf_pages=False): """ obtains one item matched to by_name raises exception if no items or several items were found Args: by_name (str): only item which match to by_name will be returned surf_pages (bool): current page items if False, all items otherwise Returns: matched item (QuadIcon/etc.) """ items = self.get_items(by_name=by_name, surf_pages=surf_pages) if len(items) == 0: raise ItemNotFound("Item {name} isn't found on this page".format(name=by_name)) elif len(items) > 1: raise ManyItemsFound("Several items with {name} were found".format(name=by_name)) return items[0]
def delete(self, wait=True): """Delete the tenant""" try: view = navigate_to(self, 'Details') except NoSuchElementException as ex: # Catch general navigation exceptions and raise raise ItemNotFound( 'Exception while navigating to Tenant details: {}'.format(ex)) view.toolbar.configuration.item_select('Delete Cloud Tenant') result = view.flash.assert_success_message( 'Delete initiated for 1 Cloud Tenant.') if wait: self.provider.refresh_provider_relationships() result = self.wait_for_disappear(600) return result
def step(self): # as for 5.9 floating ip doesn't have name att, will get id for navigation if self.obj.appliance.version < '5.9': element = self.prerequisite_view.entities.get_entity( name=self.obj.address, surf_pages=True) else: all_items = self.prerequisite_view.entities.get_all( surf_pages=True) for entity in all_items: if entity.data['address'] == self.obj.address: entity_id = entity.data['id'] element = self.prerequisite_view.entities.get_entity( entity_id=entity_id, surf_pages=True) break try: element.click() except Exception: raise ItemNotFound('Floating IP not found on the page')
def visible_widget(self): if self.browser.wait_for_element(self.input.locator, exception=False): return self.input elif self.browser.wait_for_element(self.dropdown.locator, exception=False): return self.dropdown elif self.browser.wait_for_element(self.param_input.locator, exception=False): return self.param_input elif self.browser.wait_for_element(self.param_dropdown.locator, exception=False): return self.param_dropdown elif self.browser.wait_for_element(self.select.locator, exception=False): return self.select else: raise ItemNotFound("Visible widget is not found")
def rest(self): if self.partial_check: matching_requests = self.appliance.rest_api.collections.requests.find_by( description='%{}%'.format(self.cells['Description'])) else: matching_requests = self.appliance.rest_api.collections.requests.find_by( description=self.cells['Description']) if len(matching_requests) > 1: raise RequestException('Multiple requests with matching \"{}\" ' 'found - be more specific!'.format( self.description)) elif len(matching_requests) == 0: raise ItemNotFound( 'Nothing matching "{}" with partial_check={} was found'.format( self.cells['Description'], self.partial_check)) else: self.description = matching_requests[0].description return matching_requests[0]
def find_quadicon(self, from_any_provider=False, use_search=True): """Find and return a quadicon belonging to a specific vm Args: from_any_provider: Whether to look for it anywhere (root of the tree). Useful when looking up archived or orphaned VMs Returns: entity of appropriate type Raises: ItemNotFound """ # todo :refactor this method replace it with vm methods like get_state if from_any_provider: view = navigate_to(self.parent, 'All') else: view = navigate_to(self, 'AllForProvider', use_resetter=False) view.toolbar.view_selector.select('Grid View') try: return view.entities.get_entity(name=self.name, surf_pages=True, use_search=use_search) except ItemNotFound: raise ItemNotFound("VM '{}' not found in UI!".format(self.name))
def az_pwsh_vm(appliance): """ azure_pwsh contains powershell and necessary scripts to upload vhd, create VM, get ip of the resource and delete the VM. Find the provider that contains that template. The example of the configuration can be found in data/az_pwsh_cloudinit.cfg """ filter_pwsh_template = ProviderFilter( required_fields=[['templates', 'powershell_vm']]) providers = list_providers(filters=[filter_pwsh_template]) if not providers: pytest.skip( "There's no provider that contains a template with powershell") # If there's more than 1 provider that has the template, we select the first provider = providers[0] vm_name = random_vm_name(context="pwsh") pwsh_vm = provider.data.templates.powershell_vm.name collection = provider.appliance.provider_based_collection(provider) try: vm = collection.instantiate(vm_name, provider, pwsh_vm) vm.create_on_provider(allow_skip="default") except IndexError: from cfme.exceptions import ItemNotFound raise ItemNotFound('VM with powershell not found!') vm.mgmt.ensure_state(VmState.RUNNING) @wait_for_decorator(timeout="10m", delay=5) def get_ip_address(): ip = vm.ip_address return ip is not None yield vm vm.cleanup_on_provider()
def get_detail(field, server): """ Open the about modal and fetch the value for one of the fields 'title' and 'trademark' fields are allowed and get the header/footer values Raises ItemNotFound if the field isn't in the about modal :param field: string label for the detail field :return: string value from the requested field """ view = navigate_to(server, 'About') try: if field.lower() in ['title', 'trademark']: return getattr(view.modal, field.lower()) else: # this is AboutModal.items function, TODO rename return view.modal.items()[field] except (KeyError, AttributeError): raise ItemNotFound(f'No field named {field} found in "About" modal.') finally: # close since its a blocking modal and will break further navigation view.modal.close()
def rest(self): if self.partial_check: matching_requests = self.appliance.rest_api.collections.requests.find_by( description=f'%{self.cells["Description"]}%') else: matching_requests = self.appliance.rest_api.collections.requests.find_by( description=self.cells['Description']) if len(matching_requests) > 1: # TODO: This forces anything using requests to handle this exception # The class needs support for identifying a request by its ID # This ID might not be available on instantiation, but needs to be set somehow # Ideally before MIQ receives multiple orders for the same service, which have same desc raise RequestException( f'Multiple requests with matching "{self.description}" found - be more specific!' ) elif len(matching_requests) == 0: raise ItemNotFound( f'Nothing matching "{self.cells["Description"]}" with ' f'partial_check={self.partial_check} was found' ) else: return matching_requests[0]
def vm_default_args_rest(self): """Represents dictionary used for REST API Instance provision with minimum required default args """ from cfme.cloud.provider.azure import AzureProvider from cfme.cloud.provider.ec2 import EC2Provider if not self.provider.is_refreshed(): self.provider.refresh_provider_relationships(wait=600) provisioning = self.provider.data['provisioning'] provider_rest = self.appliance.rest_api.collections.providers.get( name=self.provider.name) # find out image guid image_name = provisioning['image']['name'] image = self.appliance.rest_api.collections.templates.get( name=image_name, ems_id=provider_rest.id) # find out flavor if ':' in provisioning['instance_type'] and self.provider.one_of( EC2Provider): instance_type = provisioning['instance_type'].split(':')[0].strip() else: instance_type = provisioning['instance_type'] flavor = self.appliance.rest_api.collections.flavors.get( name=instance_type, ems_id=provider_rest.id) # find out cloud network cloud_network_name = provisioning.get('cloud_network').strip() if self.provider.one_of(EC2Provider, AzureProvider): cloud_network_name = cloud_network_name.split()[0] cloud_network = self.appliance.rest_api.collections.cloud_networks.get( name=cloud_network_name, enabled='true') # find out cloud subnet cloud_subnet = self.appliance.rest_api.collections.cloud_subnets.get( cloud_network_id=cloud_network['id']) # find out availability zone azone_id = None av_zone_name = provisioning.get('availability_zone') if av_zone_name: azone_id = self.appliance.rest_api.collections.availability_zones.get( name=av_zone_name, ems_id=flavor.ems_id).id # find out cloud tenant tenant_name = provisioning.get('cloud_tenant') if tenant_name: try: tenant = self.appliance.rest_api.collections.cloud_tenants.get( name=tenant_name, ems_id=provider_rest.id, enabled='true') except IndexError: raise ItemNotFound("Tenant {} not found on provider {}".format( tenant_name, self.provider.name)) resource_group_id = None if self.provider.one_of(AzureProvider): resource_groups = self.appliance.rest_api.get( f'{provider_rest._href}?attributes=resource_groups' )['resource_groups'] resource_group_id = None resource_group_name = provisioning.get('resource_group') for res_group in resource_groups: if (res_group['name'] == resource_group_name and res_group['ems_id'] == provider_rest.id): resource_group_id = res_group['id'] break inst_args = { "version": "1.1", "template_fields": { "guid": image.guid }, "vm_fields": { "placement_auto": False, "vm_name": self.name, "instance_type": flavor['id'], "request_type": "template", "cloud_network": cloud_network['id'], "cloud_subnet": cloud_subnet['id'], }, "requester": { "user_name": "admin", "owner_email": "*****@*****.**", "auto_approve": True, }, "tags": {}, "ems_custom_attributes": {}, "miq_custom_attributes": {} } if tenant_name: inst_args['vm_fields']['cloud_tenant'] = tenant['id'] if resource_group_id: inst_args['vm_fields']['resource_group'] = resource_group_id if azone_id: inst_args['vm_fields']['placement_availability_zone'] = azone_id if self.provider.one_of(EC2Provider): inst_args['vm_fields']['monitoring'] = 'basic' return inst_args
def get_console_ctrl_alt_del_btn(self): try: return self.appliance.browser.widgetastic.selenium.find_element_by_xpath( self._ctrl_alt_del_xpath) except Exception: raise ItemNotFound("Element not found on screen, is current focus on console window?")