def is_external_user_needed(self, obj_dict): """Return True if request related to controls or GCAs for controls.""" if not self.is_api: return False obj_dict = obj_dict[0][obj_dict[0].keys()[0]] if isinstance( obj_dict, list) else obj_dict[obj_dict.keys()[0]] return (self.endpoint == objects.get_singular(objects.CONTROLS) or (self.endpoint == objects.get_singular( objects.CUSTOM_ATTRIBUTES) and obj_dict["definition_type"] == objects.get_singular( objects.CONTROLS)))
def new_rest_fixture(fixture, factory_params=None): """Extract arguments of 'new_rest_fixture' fixture from fixture name, create new objects via REST API and return created. """ if "new_cas_for_" in fixture: fixture_params = fixture.replace("new_cas_for_", "").replace("_rest", "") obj_name = objects.CUSTOM_ATTRIBUTES factory_cas_for_objs = [CustomAttributeDefinitionsFactory().create( attribute_type=unicode(ca_type), definition_type=unicode(objects.get_singular(fixture_params))) for ca_type in _list_cas_types] new_objs = [ _new_objs_rest(obj_name=obj_name, obj_count=1, factory_params=dict( attribute_type=unicode(ca.attribute_type), definition_type=unicode(ca.definition_type), multi_choice_options=ca.multi_choice_options))[0] for ca in factory_cas_for_objs] else: fixture_params = fixture.replace("new_", "").replace("_rest", "") has_cas = False if "_with_cas" in fixture_params: has_cas = True fixture_params = fixture_params.replace("_with_cas", "") obj_name = fixture_params obj_count = counters.BATCH_COUNT if objects.get_plural(obj_name) in objects.ALL_OBJS: obj_name = objects.get_plural(obj_name) obj_count = 1 new_objs = _new_objs_rest(obj_name=obj_name, obj_count=obj_count, has_cas=has_cas, factory_params=factory_params) return new_objs
def __init__(self, _driver=None): super(ControlModal, self).__init__() self._root = self._browser.element( class_name="modal-header", text="New {}".format( objects.get_singular(objects.CONTROLS, title=True))).parent( class_name="modal-wide") self._fields = ["title", "description", "status", "slug", "assertions"]
def __init__(self, endpoint=""): self.endpoint = endpoint if endpoint == url_module.QUERY else ( objects.get_singular(endpoint)) self.is_api = "" if endpoint == url_module.QUERY else url_module.API self.endpoint_url = urlparse.urljoin( environment.app_url, "/".join([self.is_api, endpoint])) self.session = session_pool.get_session(users.current_user())
def create_objs_rest_used_exta_arrts(name, extra_attrs, factory_params): """Create new objects via REST API according to object name (plural form) and list extra attributes. Return: [lib.entities.entity.*Entity, ...] """ if extra_attrs[0].type == objects.get_singular(objects.CUSTOM_ATTRIBUTES): if name == objects.ASSESSMENT_TEMPLATES: return factory.get_cls_rest_service(object_name=name)().create_objs( count=1, factory_params=factory_params, custom_attribute_definitions=CustomAttributeDefinitionsFactory. generate_ca_defenitions_for_asmt_tmpls( list_ca_definitions=extra_attrs[:len(_list_cas_types)]), audit=extra_attrs[len(_list_cas_types):][0].__dict__) else: cavs = [cav.__dict__ for cav in CustomAttributeDefinitionsFactory.generate_ca_values( cads=extra_attrs)] return factory.get_cls_rest_service(object_name=name)().create_objs( count=1, factory_params=factory_params, custom_attribute_definitions=[cad.__dict__ for cad in extra_attrs], custom_attribute_values=cavs) else: return ([factory.get_cls_rest_service(object_name=name)(). create_objs(count=1, factory_params=factory_params, **{parent_obj.type.lower(): parent_obj.__dict__})[0] for parent_obj in extra_attrs])
def generate_object(obj_id, obj_type): """Return minimal object representation by id and type.""" result = {} result["id"] = obj_id result["href"] = "/".join([url.API, obj_type, str(obj_id)]) result["type"] = objects.get_singular(obj_type) return result
def click_create_and_map_obj(self): """Clicks `Create and map new object` link and returns new modal for object.""" self._browser.element(class_name="modal-header").button( text="Create and map new object").click() return object_modal.get_modal_obj( obj_type=objects.get_singular(self.tree_view.obj_name))
def map_objs(self, src_obj, dest_objs, **attrs_for_template): """Create relationship from source to destination objects and return created. """ return [self.client.create_object( type=objects.get_singular(self.endpoint), source=src_obj.__dict__, destination=dest_obj.__dict__, **attrs_for_template) for dest_obj in help_utils.convert_to_list(dest_objs)]
def get_fields_to_set(object_name): """Get and return of constant DEFAULT_SET_FIELDS (tuple of default visible fields to setup) from lib.constants.element module. """ cls_name = objects.get_singular(object_name) + "ModalSetVisibleFields" base_cls = element.CommonModalSetVisibleFields set_fields_modal_cls = _factory(cls_name=cls_name, parent_cls=base_cls) return set_fields_modal_cls().DEFAULT_SET_FIELDS
def get_headers_and_values_dict_from_cas_scopes(self, is_gcas_not_lcas=True): # noqa: ignore=C901 """Get text of all CAs headers and values elements scopes and convert it to dictionary. If 'is_gcas_not_lcas' then get GCAs, if not 'is_gcas_not_lcas' then get LCAs. Example: :return {'ca_header1': 'ca_value1', 'ca_header2': 'ca_value2', ...} """ # pylint: disable=invalid-name # pylint: disable=too-many-branches selenium_utils.wait_for_js_to_load(self._driver) cas_locator = (self._locators.CAS_HEADERS_AND_VALUES if is_gcas_not_lcas else self._locators.LCAS_HEADERS_AND_VALUES) cas_headers_and_values = self.info_widget_elem.find_elements(*cas_locator) dict_cas_scopes = {} if len(cas_headers_and_values) >= 1: list_text_cas_scopes = [] for scope in cas_headers_and_values: ca_header_text = scope.text.splitlines()[0] if len(scope.text.splitlines()) >= 2: if scope.text.splitlines()[1].strip(): list_text_cas_scopes.append( [ca_header_text, scope.text.splitlines()[1]]) else: list_text_cas_scopes.append([ca_header_text, None]) if len(scope.text.splitlines()) == 1: if (element.AdminWidgetCustomAttributes.CHECKBOX.upper() in ca_header_text): list_text_cas_scopes.append( [ca_header_text, unicode(int(base.Checkbox(self._driver, scope.find_element( *self._locators.CAS_CHECKBOXES)).is_checked_via_js())) ]) else: list_text_cas_scopes.append([ca_header_text, None]) if not is_gcas_not_lcas: self.collect_lcas_attr_name_value( ca_header_text, list_text_cas_scopes, scope) cas_headers, _cas_values = [list(text_cas_scope) for text_cas_scope in zip(*list_text_cas_scopes)] # conversion cas_values = [] for ca_val in _cas_values: if ca_val is None: cas_values.append(None) elif ca_val == users.SUPERUSER_EMAIL: # Example User cas_values.append( unicode(objects.get_singular(objects.PEOPLE).title())) elif "/" in ca_val and len(ca_val) == 10: # Date _date = ca_val.split("/") cas_values.append(unicode("{y}-{m}-{d}".format( y=_date[2], m=_date[0], d=_date[1]))) else: # Other cas_values.append(ca_val) dict_cas_scopes = dict(zip(cas_headers, cas_values)) return dict_cas_scopes
def __init__(self, driver, obj_name, is_versions_widget): super(SnapshotsWebUiService, self).__init__(driver, obj_name) self.is_versions_widget = is_versions_widget self.snapshot_obj_type = objects.get_singular( objects.SNAPSHOTS, title=True) if self.is_versions_widget: self.url_mapped_objs = ( "{src_obj_url}" + url.Utils.get_widget_name_of_mapped_objs( self.obj_name, self.is_versions_widget))
def get_cls_obj_entity(object_name): """Get and return class of object factory.""" from lib.entities import entity cls_name = ( objects.get_singular(object_name, title=True) + constants.cls_name.ENTITY) base_cls = entity.Representation return _factory(cls_name=cls_name, parent_cls=base_cls, search_nested_subclasses=True)
def _create_random_ca(cls): """Create CustomAttribute entity with randomly filled fields.""" random_ca = CustomAttributeEntity() random_ca.type = cls.obj_ca random_ca.attribute_type = unicode(random.choice( AdminWidgetCustomAttributes.ALL_CA_TYPES)) random_ca.title = cls.generate_string(random_ca.attribute_type) if random_ca.attribute_type == AdminWidgetCustomAttributes.DROPDOWN: random_ca.multi_choice_options = random_list_strings() random_ca.definition_type = unicode(objects.get_singular( random.choice(objects.ALL_CA_OBJS))) random_ca.mandatory = False return random_ca
def test_user_cannot_map_control_via_unified_mapper(self, control, dashboard_controls_tab, selenium): """Tests that user cannot map Control to Scope Objects/Directives via Unified Mapper (existent new scope/directive object)""" dashboard_controls_tab.get_control(control).select_map_to_this_object() modal = webui_facade.map_object_via_unified_mapper( selenium=selenium, obj_name=objects.CONTROLS, dest_objs_type=objects.get_singular(plural=objects.PRODUCTS, title=True), return_tree_items=False, open_in_new_frontend=True) browsers.get_browser().windows()[1].use() ui_facade.verify_modal_obj_not_present(modal_obj=modal)
def _set_custom_attributes_list(self): """Set custom attributes list with Custom Attribute objects from current opened content item. """ for row in selenium_utils.get_when_all_visible(self._driver, self._locators.ROW): attrs = [i.text for i in row.find_elements(*self._locators.CELL_IN_ROW)] self.custom_attributes_list.append( CustomAttributeEntity( title=attrs[0], type=objects.get_singular(objects.CUSTOM_ATTRIBUTES), attribute_type=attrs[1], mandatory=get_bool_value_from_arg(attrs[2]), definition_type=self._item_name))
def __init__(self, driver, obj_name): self.driver = driver self.obj_name = obj_name self.obj_type = objects.get_singular(self.obj_name, title=True) self.snapshot_obj_type = None self.generic_widget_cls = factory.get_cls_widget(object_name=self.obj_name) self.info_widget_cls = factory.get_cls_widget( object_name=self.obj_name, is_info=True) self.entities_factory_cls = factory.get_cls_entity_factory( object_name=self.obj_name) self.url_mapped_objs = ( "{src_obj_url}" + url.Utils.get_widget_name_of_mapped_objs(self.obj_name)) self.url_obj_info_page = "{obj_url}" + url.Widget.INFO self._unified_mapper = None
def is_info_page(self): """Check is the current page is Info Page and not Info Panel according to checking existing of element by locator and URL's logic.""" is_info_page = False if selenium_utils.is_element_exist( self._driver, (By.XPATH, constants.locator.Common.INFO_PAGE_XPATH) ): if ((self.widget_name_from_url in url.Widget.INFO) or ((objects.get_singular(self.source_obj_from_url) == self.mapped_obj_from_url) and (self.source_obj_id_from_url == self.mapped_obj_id_from_url)) or (self.widget_name_from_url == self.mapped_obj_from_url == self.mapped_obj_id_from_url == "")): is_info_page = True return is_info_page
def mapped_objs(self): """Returns objects mapped to the cycle task.""" # HACK: it's not possible to determine by looking at DOM whether # the list of mapped objects was fully loaded or not. time.sleep(1) objs = [] row_els = self._browser.element(text="Mapped objects").next_sibling().lis() for obj_row in row_els: # link to the obj is for example 'http://localhost:8080/controls/1' # last number is obj id obj_id = int(obj_row.link().href.split("/")[-1]) entity_obj_name = objects.get_singular( obj_row.link().href.split("/")[-2]) obj_title = obj_row.text factory = entity_factory_common.get_factory_by_obj_name( entity_obj_name)() objs.append(factory.create_empty(obj_id=obj_id, title=obj_title)) return objs
def _create_random_obj(self, is_add_rest_attrs): """Create Custom Attribute entity with randomly and predictably filled fields, if 'is_add_rest_attrs' then add attributes for REST.""" ca_obj_attr_type = unicode(random.choice( AdminWidgetCustomAttributes.ALL_CA_TYPES)) ca_obj = self.obj_inst().update_attrs( title=self.generate_ca_title(ca_obj_attr_type), attribute_type=ca_obj_attr_type, multi_choice_options=( StringMethods.random_list_strings() if ca_obj_attr_type == AdminWidgetCustomAttributes.DROPDOWN else None), definition_type=unicode(objects.get_singular( random.choice(objects.ALL_CA_OBJS))), mandatory=False) if is_add_rest_attrs: ca_obj.update_attrs( modal_title="Add Attribute to type {}".format( ca_obj.definition_type.title())) return ca_obj
def __init__(self, _driver=None): super(InfoWidget, self).__init__() self.child_cls_name = self.__class__.__name__ self.obj_name = objects.get_singular(self.child_cls_name) self.is_asmts_info_widget = ( self.child_cls_name.lower() == objects.ASSESSMENTS) self.list_all_headers_txt = [] self.list_all_values_txt = [] self.inline_edit_controls = self._browser.elements( class_name="set-editable-group") self.tabs = tab_element.Tabs(self._browser, tab_element.Tabs.INTERNAL) self.add_tab_btn = self._browser.element( data_test_id="button_widget_add_2c925d94") self._attributes_tab_name = "Attributes" self._changelog_tab_name = "Change Log" # for overridable methods if (self.__class__ in [Controls, Programs, Regulations, Objectives, Contracts, Policies, Risks, Standards, Threats, Requirements]): if self.is_info_page: self.tabs.ensure_tab(self._attributes_tab_name) self.comment_area = self._comment_area() self.edit_popup = object_modal.get_modal_obj(self.obj_name, self._driver)
def create(self, is_add_rest_attrs=False, **attrs): """Create random Custom Attribute object's instance, if 'is_add_rest_attrs' then add attributes for REST, if 'attrs' then update attributes accordingly. """ attrs = copy.deepcopy(attrs) attrs.setdefault("attribute_type", random.choice(AdminWidgetCustomAttributes.ALL_CA_TYPES)) attrs.setdefault("definition_type", objects.get_singular(random.choice(objects.ALL_CA_OBJS))) attrs.setdefault("title", self.generate_ca_title(attrs["attribute_type"])) if attrs["attribute_type"] == AdminWidgetCustomAttributes.DROPDOWN: attrs.setdefault("multi_choice_options", StringMethods.random_list_strings()) else: attrs["multi_choice_options"] = None attrs.setdefault("mandatory", False) obj = self.obj_inst() obj.update_attrs(is_allow_none=False, **attrs) if is_add_rest_attrs: obj.modal_title = "Add Attribute to type {}".format( obj.definition_type.title()) return obj
class EntitiesFactory(object): """Common factory class for entities.""" # pylint: disable=too-few-public-methods obj_person = unicode(objects.get_singular(objects.PEOPLE, title=True)) obj_program = unicode(objects.get_singular(objects.PROGRAMS, title=True)) obj_control = unicode(objects.get_singular(objects.CONTROLS, title=True)) obj_objective = unicode( objects.get_singular(objects.OBJECTIVES, title=True)) obj_audit = unicode(objects.get_singular(objects.AUDITS, title=True)) obj_asmt_tmpl = unicode( objects.get_singular(objects.ASSESSMENT_TEMPLATES, title=True)) obj_asmt = unicode(objects.get_singular(objects.ASSESSMENTS, title=True)) obj_issue = unicode(objects.get_singular(objects.ISSUES, title=True)) obj_ca = unicode(objects.get_singular(objects.CUSTOM_ATTRIBUTES)) obj_comment = unicode(objects.get_singular(objects.COMMENTS, title=True)) obj_snapshot = unicode(objects.get_singular(objects.SNAPSHOTS, title=True)) @classmethod def generate_string(cls, first_part): """Generate string in unicode format according object type and random data. """ special_chars = string_utils.SPECIAL return unicode("{first_part}_{uuid}_{rand_str}".format( first_part=first_part, uuid=random_uuid(), rand_str=random_string(size=len(special_chars), chars=special_chars))) @classmethod def generate_slug(cls): """Generate slug in unicode format according str part and random data.""" return unicode("{slug}".format(slug=random_uuid())) @classmethod def generate_email(cls, domain=const_url.DEFAULT_EMAIL_DOMAIN): """Generate email in unicode format according to domain.""" return unicode("{mail_name}@{domain}".format(mail_name=random_uuid(), domain=domain))
def custom_asmt_read_role(): """Returns custom access control role with 'Read' rights for Assessment.""" return custom_read_role( objects.get_singular(objects.ASSESSMENTS, title=True))
from urlparse import urldefrag from lib import environment from lib.constants import objects from lib.constants.objects import * # noqa; the names are later exported from lib.entities import entity_operations # URL's parts for work with objects and REST API queries API = "api" LOGIN = "******" DASHBOARD = "dashboard" ADMIN_DASHBOARD = "admin" PEOPLE_TAB = "#!people_list_widget" CONTROLS_TAB = "#!{}".format(objects.get_singular(objects.CONTROLS)) AUDIT = AUDITS + "/{0}" RELATIONSHIPS = "relationships" USER_ROLES = "user_roles" CONTACTS = "contacts" QUERY = "query" ACCESS_CONTROL_ROLES = "access_control_roles" REVIEWS = "reviews" class Widget(object): """URL's constants parts for widgets.""" # pylint: disable=too-few-public-methods # admin dashboard page CUSTOM_ATTRIBUTES = "#!custom_attribute" EVENTS = "#!events_list"
class WidgetControls(BaseWidgetGeneric): """Locators for Controls generic widgets.""" _object_name = objects.get_singular(objects.CONTROLS)
class WidgetAudits(BaseWidgetGeneric): """Locators for Audits generic widgets.""" _object_name = objects.get_singular(objects.AUDITS)
class WidgetPrograms(BaseWidgetGeneric): """Locators for Programs generic widgets""" _object_name = objects.get_singular(objects.PROGRAMS)
class WidgetProcesses(BaseWidgetGeneric): """Locators for Processes generic widgets.""" _object_name = objects.get_singular(objects.PROCESSES)
def __init__(self, _driver=None): super(InfoWidget, self).__init__() self.child_cls_name = self.__class__.__name__ self.obj_name = objects.get_singular(self.child_cls_name) self.is_asmts_info_widget = ( self.child_cls_name.lower() == objects.ASSESSMENTS) self.list_all_headers_txt = [] self.list_all_values_txt = [] self.info_widget_locator = (self._locators.INFO_PAGE_ELEM if self.is_info_page else self._locators.INFO_PANEL_ELEM) self.info_widget_elem = selenium_utils.get_when_visible( self._driver, self.info_widget_locator) # common for all objects self.state_lbl_txt = self._elements.STATE.upper() self._extend_list_all_scopes( ["TITLE", self.state_lbl_txt], [self.title(), self.status()]) self.info_3bbs_btn = self._browser.element( xpath=self._locators.BUTTON_3BBS_XPATH) self.inline_edit_controls = self._browser.elements( class_name="set-editable-group") # for Info Page if self.is_info_page: self._extend_list_all_scopes([ self._elements.CREATED_AT.upper(), self._elements.MODIFIED_BY.upper(), self._elements.UPDATED_AT.upper() ], [self.created_at(), self.modified_by(), self.updated_at()]) # for Info Panel else: self.panel = ( SnapshotedInfoPanel(self._driver, self.info_widget_elem) if (self.child_cls_name.lower() in objects.ALL_SNAPSHOTABLE_OBJS and self.is_snapshoted_panel) else InfoPanel( self._driver, self.info_widget_elem)) # for tab controller if not self.is_snapshoted_panel: self.tab_container_elem = self.info_widget_elem.find_element( *self._locators.TAB_CONTAINER_CSS) self.tab_container = (tab_containers.AssessmentsTabContainer( self._driver, self.tab_container_elem) if self.is_asmts_info_widget else tab_containers.TabContainer( self._driver, self.tab_container_elem)) self.tab_container.tab_controller.active_tab = ( self.tab_container._elements.OBJ_TAB) # core element to find sub elements self.core_elem = (self.info_widget_elem if self.is_snapshoted_panel else self.tab_container.active_tab_elem) # for overridable methods if (self.__class__ in [ Controls, Programs, Regulations, Objectives, Contracts, Policies, Risks, Standards, Threats, Requirements ]): self._extend_list_all_scopes_by_review_state() self.comment_area = self._comment_area() self.edit_popup = object_modal.get_modal_obj(self.obj_name, self._driver) self.tabs = page_tab.Tabs(self._browser, page_tab.Tabs.INTERNAL)
class CommonAsmt(object): """Common elements' labels and properties for the Assessment object.""" ASMT = objects.get_normal_form(objects.get_singular(objects.ASSESSMENTS))
class CommonIssue(Common): """Common elements' labels and properties for Issues objects.""" ISSUE = objects.get_normal_form(objects.get_singular(objects.ISSUES)) STATE = Base.STATE
class CommonAssessmentTemplate(Common): """Common elements' labels and properties for Assessment Templates objects. """ ASMT_TMPL = objects.get_normal_form( objects.get_singular(objects.ASSESSMENT_TEMPLATES))
class WidgetAssessments(BaseWidgetGeneric): """Locators for assessment widget""" _object_name = objects.get_singular(objects.ASSESSMENTS) widget_name = url.Widget.ASSESSMENTS
def get_headers_and_values_text_from_cas_scopes(self): # flake8: noqa """Get and convert to entities form all headers and values elements text from CAs scopes elements. Example: :return [['ca_header1', 'ca_header2'], ['ca_value1', 'ca_value2']] """ # pylint: disable=invalid-name # pylint: disable=too-many-branches if not self.cas_headers_and_values: selenium_utils.wait_for_js_to_load(self._driver) self.cas_headers_and_values = self._driver.find_elements( *self._locators.CAS_HEADERS_AND_VALUES) if len(self.cas_headers_and_values) > 1: list_text_cas_scopes = [] for scope in self.cas_headers_and_values: ca_header_text = scope.text.splitlines()[0] if any( unicode(ca_type.upper()) in ca_header_text for ca_type in element.AdminWidgetCustomAttributes.ALL_CA_TYPES): if len(scope.text.splitlines()) >= 2: if scope.text.splitlines()[1].strip(): list_text_cas_scopes.append( [ca_header_text, scope.text.splitlines()[1]]) else: list_text_cas_scopes.append([ca_header_text, None]) if len(scope.text.splitlines()) == 1: if (element.AdminWidgetCustomAttributes.CHECKBOX.upper( ) in ca_header_text): list_text_cas_scopes.append([ ca_header_text, unicode( int( base.Checkbox( self._driver, scope.find_element( *self._locators.CAS_CHECKBOXES) ).is_element_checked())) ]) else: list_text_cas_scopes.append([ca_header_text, None]) cas_headers, _cas_values = zip(*list_text_cas_scopes) # convertation cas_values = [] for ca_val in _cas_values: if ca_val is None: cas_values.append(None) elif ca_val == roles.DEFAULT_USER: # Example User cas_values.append( unicode(objects.get_singular(objects.PEOPLE).title())) elif "/" in ca_val and len(ca_val) == 10: # Date _date = ca_val.split("/") cas_values.append( unicode("{y}-{m}-{d}".format(y=_date[2], m=_date[0], d=_date[1]))) else: # Other cas_values.append(ca_val) return cas_headers, cas_values else: return [None, None]
class WidgetDataAssets(BaseWidgetGeneric): """Locators for DataAssets generic widgets.""" _object_name = objects.get_singular(objects.PROJECTS)
class CommonControl(object): """Common elements' labels and properties for the Control object.""" CONTROL = objects.get_normal_form(objects.get_singular(objects.CONTROLS))
class WidgetIssues(BaseWidgetGeneric): """Locators for Issues generic widgets""" _object_name = objects.get_singular(objects.ISSUES)
def _new_objs_rest( obj_name, obj_count, # noqa: ignore=C901 has_cas=False, factory_params=None): """Create new objects via REST API according to object name (plural form), objects count and requirements for presence of Custom Attributes. Return: [lib.entities.entity.*Entity, ...] """ # pylint: disable=unused-argument global dict_executed_fixtures _list_cas_types = element.AdminWidgetCustomAttributes.ALL_CA_TYPES def create_objs_rest(name, count, factory_params): """Create new objects via REST API according to object name (plural form) and objects count. Return: [lib.entities.entity.*Entity, ...] """ return factory.get_cls_rest_service(object_name=name)().create_objs( count=count, factory_params=factory_params) def create_objs_rest_used_exta_arrts(name, extra_attrs, factory_params): """Create new objects via REST API according to object name (plural form) and list extra attributes. Return: [lib.entities.entity.*Entity, ...] """ if extra_attrs[0].type == objects.get_singular( objects.CUSTOM_ATTRIBUTES): if name == objects.ASSESSMENT_TEMPLATES: return factory.get_cls_rest_service( object_name=name)().create_objs( count=1, factory_params=factory_params, custom_attribute_definitions= CustomAttributeDefinitionsFactory. generate_cads_for_asmt_tmpls( cads=extra_attrs[:len(_list_cas_types)]), audit=extra_attrs[len(_list_cas_types):][0].__dict__) else: cavs = [ cav.__dict__ for cav in CustomAttributeDefinitionsFactory.generate_cavs( cads=extra_attrs) ] return factory.get_cls_rest_service( object_name=name)().create_objs( count=1, factory_params=factory_params, custom_attribute_definitions=[ cad.__dict__ for cad in extra_attrs ], custom_attribute_values=cavs) else: return ([ factory.get_cls_rest_service(object_name=name)().create_objs( count=1, factory_params=factory_params, **{parent_obj.type.lower(): parent_obj.__dict__})[0] for parent_obj in extra_attrs ]) parent_obj_name = None if obj_name == objects.AUDITS: parent_obj_name = objects.get_singular(objects.PROGRAMS) if obj_name in (objects.ASSESSMENT_TEMPLATES, objects.ASSESSMENTS): parent_obj_name = objects.get_singular(objects.AUDITS) if (has_cas and obj_name in objects.ALL_OBJS and obj_name not in objects.ASSESSMENT_TEMPLATES): parent_obj_name = "cas_for_" + obj_name if parent_obj_name: parent_objs = get_fixture_from_dict_fixtures( fixture="new_{}_rest".format(parent_obj_name)) if "new_{}_rest".format(parent_obj_name) == "new_audit_rest": parent_objs *= obj_count if has_cas and obj_name in objects.ASSESSMENT_TEMPLATES: parent_objs = ([ CustomAttributeDefinitionsFactory().create( attribute_type=unicode(ca_type), definition_type=unicode("")) for ca_type in _list_cas_types ] + parent_objs) objs = create_objs_rest_used_exta_arrts(name=obj_name, factory_params=factory_params, extra_attrs=parent_objs) else: objs = create_objs_rest(name=obj_name, count=obj_count, factory_params=factory_params) return objs
class WidgetAssessmentTemplates(BaseWidgetGeneric): """Locators for Assessment Templates generic widgets.""" _object_name = objects.get_singular(objects.ASSESSMENT_TEMPLATES)
def custom_audit_read_role(): """Returns custom access control role with 'Read' rights for Audit.""" return custom_read_role(objects.get_singular(objects.AUDITS, title=True))
class WidgetAssessments(BaseWidgetGeneric): """Locators for Assessments generic widgets.""" _object_name = objects.get_singular(objects.ASSESSMENTS)
def assign_owner_to_objs(self, objs, owner=ObjectPersonsFactory().default()): """Assign of an owner to objects.""" return [self.client.create_object( type=objects.get_singular(self.endpoint), ownable=obj.__dict__, person=owner.__dict__) for obj in help_utils.convert_to_list(objs)]
class WidgetObjectives(BaseWidgetGeneric): """Locators for Controls generic widgets.""" _object_name = objects.get_singular(objects.OBJECTIVES)
def is_relationship_types_external(self, obj_dict): """Check if source or destination objects type is external.""" return (self.endpoint == objects.get_singular(objects.RELATIONSHIPS) and (any(x for x in objects.SINGULAR_TITLE_DISABLED_OBJS if x in (obj_dict["source"]["type"], obj_dict["destination"]["type"]))))
def create_threat(threat): """Creates a threat `threat`.""" selenium_utils.open_url(url.dashboard()) dashboard.Dashboard().open_create_obj_modal(objects.get_singular( objects.THREATS, title=True)) internal_ui_operations.submit_obj(threat)
# pylint: disable=unused-wildcard-import from urlparse import urldefrag from lib import environment from lib.constants import objects from lib.constants.objects import * # noqa; the names are later exported from lib.entities import entity_operations # URL's parts for work with objects and REST API queries API = "api" LOGIN = "******" DASHBOARD = "dashboard" ADMIN_DASHBOARD = "admin" PEOPLE_TAB = "#!people_list_widget" CONTROLS_TAB = "#!{}".format(objects.get_singular(objects.CONTROLS)) AUDIT = AUDITS + "/{0}" RELATIONSHIPS = "relationships" USER_ROLES = "user_roles" CONTACTS = "contacts" QUERY = "query" ACCESS_CONTROL_ROLES = "access_control_roles" REVIEWS = "reviews" NOTIFICATIONS = "_notifications" class Widget(object): """URL's constants parts for widgets.""" # pylint: disable=too-few-public-methods # admin dashboard page CUSTOM_ATTRIBUTES = "#!custom_attribute"
class EntitiesFactory(object): """Common factory class for entities.""" # pylint: disable=too-few-public-methods obj_person = unicode(objects.get_singular(objects.PEOPLE, title=True)) obj_program = unicode(objects.get_singular(objects.PROGRAMS, title=True)) obj_control = unicode(objects.get_singular(objects.CONTROLS, title=True)) obj_objective = unicode( objects.get_singular(objects.OBJECTIVES, title=True)) obj_audit = unicode(objects.get_singular(objects.AUDITS, title=True)) obj_asmt_tmpl = unicode( objects.get_singular(objects.ASSESSMENT_TEMPLATES, title=True)) obj_asmt = unicode(objects.get_singular(objects.ASSESSMENTS, title=True)) obj_issue = unicode(objects.get_singular(objects.ISSUES, title=True)) obj_ca = unicode(objects.get_singular(objects.CUSTOM_ATTRIBUTES)) obj_comment = unicode(objects.get_singular(objects.COMMENTS, title=True)) types_of_values_ui_like_attrs = (str, unicode, int) all_objs_attrs_names = Entity().get_attrs_names_for_entities() @classmethod def convert_obj_repr_from_obj_to_dict(cls, obj): """Convert object or list of objects from object representation 'obj.attr_name' = 'attr_value' to dictionary or list of dictionaries with items {'attr_name': 'attr_value'}. """ if obj: if isinstance(obj, list): if (all(not isinstance(_, dict) and not isinstance( _, cls.types_of_values_ui_like_attrs) and _ for _ in obj)): obj = [_.__dict__ for _ in obj] else: if (not isinstance(obj, dict) and not isinstance( obj, cls.types_of_values_ui_like_attrs)): obj = obj.__dict__ return obj @classmethod # noqa: ignore=C901 def convert_obj_repr_from_rest_to_ui(cls, obj): """Convert object's attributes values from REST like (dict or list of dict) representation to UI like with unicode. Examples: None to None, u'Ex' to u'Ex', [u'Ex1', u'Ex2', ...] to u'Ex1, Ex2', {'name': u'Ex', ...} to u'Ex', [{'name': u'Ex1', ...}, {'name': u'Ex2', ...}] to u'Ex1, Ex2' """ # pylint: disable=too-many-locals # pylint: disable=undefined-loop-variable def convert_attr_value_from_dict_to_unicode(attr_name, attr_value): """Convert attribute value from dictionary to unicode representation (get value by key from dictionary 'attr_value' where key determine according to 'attr_name'). """ if isinstance(attr_value, dict): converted_attr_value = attr_value if attr_name in [ "contact", "manager", "owners", "assessor", "creator", "verifier", "created_by", "modified_by", "Assessor", "Creator", "Verifier" ]: converted_attr_value = unicode(attr_value.get("name")) if attr_name in [ "custom_attribute_definitions", "program", "audit", "objects_under_assessment" ]: converted_attr_value = ( unicode(attr_value.get("title")) if attr_name != "custom_attribute_definitions" else { attr_value.get("id"): attr_value.get("title").upper() }) if attr_name in ["custom_attribute_values"]: converted_attr_value = { attr_value.get("custom_attribute_id"): attr_value.get("attribute_value") } if obj_attr_name == "comments": converted_attr_value = { k: (string_utils.convert_str_to_datetime(v) if k == "created_at" and isinstance(v, unicode) else v) for k, v in attr_value.iteritems() if k in ["modified_by", "created_at", "description"] } return converted_attr_value origin_obj = copy.deepcopy(obj) for obj_attr_name in obj.__dict__.keys(): # 'Ex', u'Ex', 1, None to 'Ex', u'Ex', 1, None obj_attr_value = (obj.assignees.get(obj_attr_name.title()) if ( obj_attr_name in ["assessor", "creator", "verifier"] and "assignees" in obj.__dict__.keys()) else getattr( obj, obj_attr_name)) # u'2017-06-07T16:50:16' and u'2017-06-07 16:50:16' to datetime if (obj_attr_name in ["updated_at", "created_at"] and isinstance(obj_attr_value, unicode)): obj_attr_value = string_utils.convert_str_to_datetime( obj_attr_value) if isinstance(obj_attr_value, dict) and obj_attr_value: # to "assignees" = {"Assessor": [], "Creator": [], "Verifier": []} if obj_attr_name == "assignees": obj_attr_value = { k: ([ convert_attr_value_from_dict_to_unicode(k, _v) for _v in v ] if isinstance(v, list) else convert_attr_value_from_dict_to_unicode(k, v)) for k, v in obj_attr_value.iteritems() if k in ["Assessor", "Creator", "Verifier"] } # {'name': u'Ex1', 'type': u'Ex2', ...} to u'Ex1' else: obj_attr_value = convert_attr_value_from_dict_to_unicode( obj_attr_name, obj_attr_value) # [el1, el2, ...] or [{item1}, {item2}, ...] to [u'Ex1, u'Ex2', ...] if (isinstance(obj_attr_value, list) and all(isinstance(item, dict) for item in obj_attr_value)): obj_attr_value = [ convert_attr_value_from_dict_to_unicode( obj_attr_name, item) for item in obj_attr_value ] setattr(obj, obj_attr_name, obj_attr_value) # merge "custom_attribute_definitions" and "custom_attribute_values" obj_cas_attrs_names = [ "custom_attributes", "custom_attribute_definitions", "custom_attribute_values" ] if set(obj_cas_attrs_names).issubset(obj.__dict__.keys()): cas_def = obj.custom_attribute_definitions cas_val = obj.custom_attribute_values # form CAs values of CAs definitions exist but CAs values not, or if CAs # definitions have different then CAs values lengths if cas_def and (not cas_val or (isinstance(cas_def and cas_val, list) and len(cas_def) != len(cas_val))): cas_val_dicts_keys = ([_.keys()[0] for _ in cas_val] if isinstance(cas_val, list) else [None]) _cas_val = [{ k: v } for k, v in CustomAttributeDefinitionsFactory( ).generate_ca_values( list_ca_def_objs=origin_obj.custom_attribute_definitions, is_none_values=True).iteritems() if k not in cas_val_dicts_keys] cas_val = _cas_val if not cas_val else cas_val + _cas_val cas_def_dict = (dict([_def.iteritems().next() for _def in cas_def]) if (isinstance(cas_def, list) and all( isinstance(_def, dict) for _def in cas_def)) else { None: None }) cas_val_dict = (dict([_val.iteritems().next() for _val in cas_val]) if (isinstance(cas_def, list) and all( isinstance(_def, dict) for _def in cas_def)) else { None: None }) cas = string_utils.merge_dicts_by_same_key(cas_def_dict, cas_val_dict) setattr(obj, "custom_attributes", cas) return obj @classmethod def convert_objs_repr_from_rest_to_ui(cls, objs): """Convert objects's attributes values from REST like (dict or list of dict) representation to UI like with unicode. 'objs' can be list of objects to convert or one object. """ return ([cls.convert_obj_repr_from_rest_to_ui(obj) for obj in objs] if isinstance(objs, list) else cls.convert_obj_repr_from_rest_to_ui(objs)) @classmethod def update_objs_attrs_values_by_entered_data( cls, objs, is_replace_attrs_values=True, is_allow_none_values=True, is_replace_values_of_dicts=False, **arguments): """Update object or list of objects ('objs') attributes values by manually entered data if attribute name exist in 'attrs_names' witch equal to 'all_objs_attrs_names' according to dictionary of attributes and values '**arguments'. If 'is_replace_attrs_values' then replace attributes values, if not 'is_replace_attrs_values' then update (merge) attributes values witch should be lists. If 'is_allow_none_values' then allow to set None object's attributes values, and vice versa. If 'is_replace_values_of_dicts' then update values of dicts in list which is value of particular object's attribute name: (**arguments is attr={'key1': 'new_value2', 'key2': 'new_value2'}). """ # pylint: disable=expression-not-assigned def update_obj_attrs_values(obj, is_replace_attrs_values, is_allow_none_values, **arguments): """Update object's attributes values.""" for obj_attr_name in arguments: if (obj_attr_name in Entity().get_attrs_names_for_entities( obj.__class__)): _obj_attr_value = arguments.get(obj_attr_name) condition = (True if is_allow_none_values else _obj_attr_value) if condition and not is_replace_values_of_dicts: # convert repr from objects to dicts exclude datetime objects obj_attr_value = ( cls.convert_obj_repr_from_obj_to_dict( _obj_attr_value) if not isinstance(_obj_attr_value, datetime) else _obj_attr_value) if not is_replace_attrs_values: origin_obj_attr_value = getattr(obj, obj_attr_name) obj_attr_value = ( dict(origin_obj_attr_value.items() + obj_attr_value.items()) if obj_attr_name == "custom_attributes" else string_utils. convert_to_list(origin_obj_attr_value) + string_utils.convert_to_list(obj_attr_value)) setattr(obj, obj_attr_name, obj_attr_value) if is_replace_values_of_dicts and isinstance( _obj_attr_value, dict): obj_attr_value = string_utils.exchange_dicts_items( transform_dict=_obj_attr_value, dicts=string_utils.convert_to_list( getattr(obj, obj_attr_name)), is_keys_not_values=False) obj_attr_value = (obj_attr_value if isinstance( getattr(obj, obj_attr_name), list) else obj_attr_value[0]) setattr(obj, obj_attr_name, obj_attr_value) return obj if objs and arguments: return [ update_obj_attrs_values(obj, is_replace_attrs_values, is_allow_none_values, **arguments) for obj in objs ] if isinstance(objs, list) else update_obj_attrs_values( objs, is_replace_attrs_values, is_allow_none_values, ** arguments) @classmethod def filter_objs_attrs(cls, objs, attrs_to_include): """Make objects's copy and filter objects's attributes (delete attributes from objects witch not in list'attrs_to_include'). 'objs' can be list of objects or object. """ # pylint: disable=expression-not-assigned def filter_obj_attrs(obj, attrs_to_include): """Filter one object's attributes.""" obj = copy.deepcopy(obj) [ delattr(obj, obj_attr) for obj_attr in obj.__dict__.keys() if obj_attr not in attrs_to_include ] return obj return ([filter_obj_attrs(obj, attrs_to_include) for obj in objs] if isinstance(objs, list) else filter_obj_attrs(objs, attrs_to_include)) @classmethod def generate_string(cls, first_part): """Generate string in unicode format according object type and random data. """ special_chars = string_utils.SPECIAL return unicode("{first_part}_{uuid}_{rand_str}".format( first_part=first_part, uuid=random_uuid(), rand_str=random_string(size=len(special_chars), chars=special_chars))) @classmethod def generate_slug(cls): """Generate slug in unicode format according str part and random data.""" return unicode("{slug}".format(slug=random_uuid())) @classmethod def generate_email(cls, domain=const_url.DEFAULT_EMAIL_DOMAIN): """Generate email in unicode format according to domain.""" return unicode("{mail_name}@{domain}".format(mail_name=random_uuid(), domain=domain))
class WidgetProducts(BaseWidgetGeneric): """Locators for Products generic widgets.""" _object_name = objects.get_singular(objects.PRODUCTS)
class WidgetSystems(BaseWidgetGeneric): """Locators for Systems generic widgets.""" _object_name = objects.get_singular(objects.SYSTEMS)
def assessment_type(self): """Returns Assessment type.""" self.tabs.ensure_tab(self._assessment_tab_name) return objects.get_singular(self._browser.element( class_name="action-toolbar__content-item").text, title=True)
def __init__(self): self.client = RestClient(self.ENDPOINT) self._relationship = objects.get_singular(url.RELATIONSHIPS) self._object_owner = objects.get_singular(url.OBJECT_OWNERS) self._count = objects.COUNT
def _new_objs_rest(obj_name, obj_count, # noqa: ignore=C901 has_cas=False, factory_params=None): """Create new objects via REST API according to object name (plural form), objects count and requirements for presence of Custom Attributes. Return: [lib.entities.entity.*Entity, ...] """ # pylint: disable=unused-argument global dict_executed_fixtures _list_cas_types = element.AdminWidgetCustomAttributes.ALL_CA_TYPES def create_objs_rest(name, count, factory_params): """Create new objects via REST API according to object name (plural form) and objects count. Return: [lib.entities.entity.*Entity, ...] """ return factory.get_cls_rest_service( object_name=name)().create_objs(count=count, factory_params=factory_params) def create_objs_rest_used_exta_arrts(name, extra_attrs, factory_params): """Create new objects via REST API according to object name (plural form) and list extra attributes. Return: [lib.entities.entity.*Entity, ...] """ if extra_attrs[0].type == objects.get_singular(objects.CUSTOM_ATTRIBUTES): if name == objects.ASSESSMENT_TEMPLATES: return factory.get_cls_rest_service(object_name=name)().create_objs( count=1, factory_params=factory_params, custom_attribute_definitions=CustomAttributeDefinitionsFactory. generate_ca_defenitions_for_asmt_tmpls( list_ca_definitions=extra_attrs[:len(_list_cas_types)]), audit=extra_attrs[len(_list_cas_types):][0].__dict__) else: return factory.get_cls_rest_service(object_name=name)().create_objs( count=1, factory_params=factory_params, custom_attributes=CustomAttributeDefinitionsFactory(). generate_ca_values(list_ca_def_objs=extra_attrs)) else: return ([factory.get_cls_rest_service(object_name=name)(). create_objs(count=1, factory_params=factory_params, **{parent_obj.type.lower(): parent_obj.__dict__})[0] for parent_obj in extra_attrs]) parent_obj_name = None if obj_name == objects.AUDITS: parent_obj_name = objects.get_singular(objects.PROGRAMS) if obj_name in (objects.ASSESSMENT_TEMPLATES, objects.ASSESSMENTS): parent_obj_name = objects.get_singular(objects.AUDITS) if (has_cas and obj_name in objects.ALL_OBJS and obj_name not in objects.ASSESSMENT_TEMPLATES): parent_obj_name = "cas_for_" + obj_name if parent_obj_name: parent_objs = get_fixture_from_dict_fixtures( fixture="new_{}_rest".format(parent_obj_name)) if "new_{}_rest".format(parent_obj_name) == "new_audit_rest": parent_objs *= obj_count if has_cas and obj_name in objects.ASSESSMENT_TEMPLATES: parent_objs = ( [CustomAttributeDefinitionsFactory().create( attribute_type=unicode(ca_type), definition_type=unicode("")) for ca_type in _list_cas_types] + parent_objs) objs = create_objs_rest_used_exta_arrts( name=obj_name, factory_params=factory_params, extra_attrs=parent_objs) else: objs = create_objs_rest( name=obj_name, count=obj_count, factory_params=factory_params) return objs
def get_headers_and_values_dict_from_cas_scopes(self, is_gcas_not_lcas=True ): # noqa: ignore=C901 """Get text of all CAs headers and values elements scopes and convert it to dictionary. If 'is_gcas_not_lcas' then get GCAs, if not 'is_gcas_not_lcas' then get LCAs. Example: :return {'ca_header1': 'ca_value1', 'ca_header2': 'ca_value2', ...} """ # pylint: disable=invalid-name # pylint: disable=too-many-branches selenium_utils.wait_for_js_to_load(self._driver) cas_locator = (self._locators.CAS_HEADERS_AND_VALUES if is_gcas_not_lcas else self._locators.LCAS_HEADERS_AND_VALUES) cas_headers_and_values = self.info_widget_elem.find_elements( *cas_locator) dict_cas_scopes = {} if len(cas_headers_and_values) >= 1: list_text_cas_scopes = [] for scope in cas_headers_and_values: ca_header_text = scope.text.splitlines()[0] if len(scope.text.splitlines()) >= 2: if scope.text.splitlines()[1].strip(): list_text_cas_scopes.append( [ca_header_text, scope.text.splitlines()[1]]) else: list_text_cas_scopes.append([ca_header_text, None]) if len(scope.text.splitlines()) == 1: if (element.AdminWidgetCustomAttributes.CHECKBOX.upper() in ca_header_text): list_text_cas_scopes.append([ ca_header_text, unicode( int( base.Checkbox( self._driver, scope.find_element( *self._locators.CAS_CHECKBOXES)). is_checked_via_js())) ]) else: list_text_cas_scopes.append([ca_header_text, None]) cas_headers, _cas_values = [ list(text_cas_scope) for text_cas_scope in zip(*list_text_cas_scopes) ] # conversion cas_values = [] for ca_val in _cas_values: if ca_val is None: cas_values.append(None) elif ca_val == roles.DEFAULT_USER: # Example User cas_values.append( unicode(objects.get_singular(objects.PEOPLE).title())) elif "/" in ca_val and len(ca_val) == 10: # Date _date = ca_val.split("/") cas_values.append( unicode("{y}-{m}-{d}".format(y=_date[2], m=_date[0], d=_date[1]))) else: # Other cas_values.append(ca_val) dict_cas_scopes = dict(zip(cas_headers, cas_values)) return dict_cas_scopes