当前位置: 首页>>代码示例>>Python>>正文


Python string_utils.StringMethods类代码示例

本文整理汇总了Python中lib.utils.string_utils.StringMethods的典型用法代码示例。如果您正苦于以下问题:Python StringMethods类的具体用法?Python StringMethods怎么用?Python StringMethods使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了StringMethods类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _check_assessments_filtration

 def _check_assessments_filtration(assessment, cavs, operator,
                                   audit, selenium):
   """Check that filtration of assessments works."""
   cads = [Representation.repr_dict_to_obj(cad)
           for cad in assessment.custom_attribute_definitions]
   filter_exprs = FilterUtils().get_filter_exprs_by_cavs(
       cads, cavs, operator)
   assessment = Representation.extract_objs_wo_excluded_attrs(
       [assessment.repr_ui()],
       *(Representation.tree_view_attrs_to_exclude + (
         "audit", "assessment_type", "modified_by"))
   )[0]
   expected_results = [{"filter": filter_expr, "objs": [assessment]}
                       for filter_expr in filter_exprs]
   actual_results = []
   for filter_expr in filter_exprs:
     result = {
         "filter": filter_expr,
         "objs": webui_service.AssessmentsService(selenium)
         .filter_and_get_list_objs_from_tree_view(audit, filter_expr)
     }
     actual_results.append(result)
   error_message = messages.AssertionMessages.format_err_msg_equal(
       [{exp_res["filter"]: [exp_obj.title for exp_obj in exp_res["objs"]]}
        for exp_res in expected_results],
       [{act_res["filter"]: [act_obj.title for act_obj in act_res["objs"]]}
        for act_res in actual_results]
   ) + messages.AssertionMessages.format_err_msg_equal(
       StringMethods.convert_list_elements_to_list(
           [exp_res["objs"] for exp_res in expected_results]),
       StringMethods.convert_list_elements_to_list(
           [act_res["objs"] for act_res in actual_results]))
   assert expected_results == actual_results, error_message
开发者ID:egorhm,项目名称:ggrc-core,代码行数:33,代码来源:test_asmts_workflow.py

示例2: generate_string

 def generate_string(cls, first_part,
                     allowed_chars=StringMethods.ALLOWED_CHARS):
   """Generate random string in unicode format according to object type.
   Symbols allowed in random part may be specified by
   `allowed_chars` argument.
   """
   return unicode("{first_part}_{uuid}_{rand_str}".format(
       first_part=first_part, uuid=StringMethods.random_uuid(),
       rand_str=StringMethods.random_string(chars=allowed_chars)))
开发者ID:egorhm,项目名称:ggrc-core,代码行数:9,代码来源:entities_factory.py

示例3: _create_list_objs

 def _create_list_objs(self, entity_factory, list_scopes):
   """Create and return list of objects used entity factory and UI data
   (list of scopes UI text elements {"header": "item", ...} remapped to
   list of dicts {"attr": "value", ...}).
   Return list of created objects.
   """
   list_factory_objs = [
       entity_factory().obj_inst() for _ in xrange(len(list_scopes))]
   list_scopes_with_upper_keys = [
       StringMethods.dict_keys_to_upper_case(scope) for scope in list_scopes]
   list_scopes_to_convert = StringMethods.exchange_dicts_items(
       transform_dict=Representation.remap_collection(),
       dicts=list_scopes_with_upper_keys, is_keys_not_values=True)
   # convert and represent values in scopes
   for scope in list_scopes_to_convert:
     # convert u'None', u'No person' to None type
     StringMethods.update_dicts_values(scope, ["None", "No person"], None)
     for key, val in scope.iteritems():
       if val:
         if key in ["mandatory", "verified"]:
           # convert u'false', u'true' like to Boolean
           scope[key] = StringMethods.get_bool_value_from_arg(val)
         if key in ["updated_at", "created_at"]:
           # UI like u'08/20/2017' to date=2017-08-20, timetz=00:00:00
           datetime_val = parser.parse(val)
           if str(datetime_val.time()) != "00:00:00":
             # UI like u'08/20/2017 07:30:45 AM +03:00' to date=2017-08-20,
             # timetz=04:30:45+00:00 if 'tzinfo', else:
             # CSV like u'08-20-2017 04:30:45' to date=2017-08-20,
             # timetz=04:30:45+00:00
             datetime_val = (
                 datetime_val.astimezone(tz=tz.tzutc()) if datetime_val.tzinfo
                 else datetime_val.replace(tzinfo=tz.tzutc()))
           scope[key] = datetime_val
         if (key == "comments" and isinstance(val, list) and
                 all(isinstance(comment, dict) for comment in val)):
           # extract datetime from u'(Creator) 08/20/2017 07:30:45 AM +03:00'
           scope[key] = [
               {k: (parser.parse(re.sub(regex.TEXT_W_PARENTHESES,
                                        Symbols.BLANK, v)
                                 ).astimezone(tz=tz.tzutc())
                    if k == "created_at" else v)
                for k, v in comment.iteritems()} for comment in val]
         # convert multiple values to list of strings and split if need it
         if (key in Representation.people_attrs_names and
            not isinstance(val, list)):
           # split Tree View values if need 'Ex1, Ex2 F' to ['Ex1', 'Ex2 F']
           # Info Widget values will be represent by internal methods
           scope[key] = val.split(", ")
         # convert 'slug' from CSV for snapshoted objects u'*23eb72ac-4d9d'
         if (key == "slug" and
                 (self.obj_name in objects.ALL_SNAPSHOTABLE_OBJS) and
                 Symbols.STAR in val):
           scope[key] = val.replace(Symbols.STAR, Symbols.BLANK)
   return [
       factory_obj.update_attrs(is_allow_none=True, **scope) for
       scope, factory_obj in zip(list_scopes_to_convert, list_factory_objs)]
开发者ID:egorhm,项目名称:ggrc-core,代码行数:57,代码来源:webui_service.py

示例4: test_dashboard_gca

 def test_dashboard_gca(self, new_control_rest, selenium):
   # pylint: disable=anomalous-backslash-in-string
   """Check Dashboard Tab is exist if 'Dashboard' GCA filled
   with right value. Possible values match to regexp r"^https?://[^\s]+$".
   Steps:
     - Create 'Dashboard' gcas for object.
     - Fill with values
     - Check if 'Dashboard' tab exist.
     - Navigate to 'Dashboard' tab.
     - Check only GCAs filled with right values displayed on the tab.
   """
   urls = ["https://gmail.by/", "https://www.google.com/",
           environment.app_url, StringMethods.random_string(),
           "ftp://something.com/"]
   cads_rest_service = rest_service.CustomAttributeDefinitionsService()
   gca_defs = (cads_rest_service.create_dashboard_gcas(
       new_control_rest.type, count=len(urls)))
   control_rest_service = rest_service.ControlsService()
   control_rest_service.update_obj(
       obj=new_control_rest, custom_attributes=dict(
           zip([gca_def.id for gca_def in gca_defs], urls)))
   expected_dashboards_items = dict(zip(
       [gca_def.title.replace(aliases.DASHBOARD + "_", "")
        for gca_def in gca_defs], urls[:3]))
   controls_ui_service = webui_service.ControlsService(selenium)
   is_dashboard_tab_exist = (
       controls_ui_service.is_dashboard_tab_exist(new_control_rest))
   assert is_dashboard_tab_exist
   actual_dashboards_items = (
       controls_ui_service.get_items_from_dashboard_widget(new_control_rest))
   assert expected_dashboards_items == actual_dashboards_items
   cads_rest_service.delete_objs(gca_defs)
开发者ID:egorhm,项目名称:ggrc-core,代码行数:32,代码来源:test_audit_page.py

示例5: update_obj_attrs_values

 def update_obj_attrs_values(obj, is_replace_attrs_values,
                             is_allow_none_values, **attrs):
   """Update object's attributes values."""
   for obj_attr_name in attrs:
     obj_attr_value = None
     if obj_attr_name in Representation.all_attrs_names():
       _obj_attr_value = attrs.get(obj_attr_name)
       if not is_replace_values_of_dicts:
         # convert repr from objects to dicts exclude datetime objects
         obj_attr_value = (
             cls.repr_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
               help_utils.convert_to_list(origin_obj_attr_value) +
               help_utils.convert_to_list(obj_attr_value))
       if is_replace_values_of_dicts and isinstance(_obj_attr_value, dict):
         obj_attr_value = StringMethods.exchange_dicts_items(
             transform_dict=_obj_attr_value,
             dicts=help_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])
       if (is_allow_none_values is True or
               (is_allow_none_values is False and
                obj_attr_value is not None)):
         setattr(obj, obj_attr_name, obj_attr_value)
   return obj
开发者ID:,项目名称:,代码行数:33,代码来源:

示例6: _update_ca_attrs_values

 def _update_ca_attrs_values(self, obj, **attrs):
   """Update CA's (obj) attributes values according to dictionary of
   arguments (key = value). Restrictions: 'multi_choice_options' is a
   mandatory attribute for Dropdown CA and 'placeholder' is a attribute that
   exists only for Text and Rich Text CA.
   Generated data - 'obj', entered data - '**arguments'.
   """
   # fix generated data
   if attrs.get("attribute_type"):
     obj.title = self.generate_ca_title(attrs["attribute_type"])
   if (obj.multi_choice_options and
           obj.attribute_type == AdminWidgetCustomAttributes.DROPDOWN and
           attrs.get("attribute_type") !=
           AdminWidgetCustomAttributes.DROPDOWN):
     obj.multi_choice_options = None
   # fix entered data
   if (attrs.get("multi_choice_options") and
           attrs.get("attribute_type") !=
           AdminWidgetCustomAttributes.DROPDOWN):
     attrs["multi_choice_options"] = None
   if (attrs.get("placeholder") and attrs.get("attribute_type") not in
       (AdminWidgetCustomAttributes.TEXT,
        AdminWidgetCustomAttributes.RICH_TEXT)):
     attrs["placeholder"] = None
   # extend entered data
   if (attrs.get("attribute_type") ==
           AdminWidgetCustomAttributes.DROPDOWN and not
           obj.multi_choice_options):
     obj.multi_choice_options = StringMethods.random_list_strings()
   return obj.update_attrs(**attrs)
开发者ID:egorhm,项目名称:ggrc-core,代码行数:30,代码来源:entities_factory.py

示例7: test_asmt_from_template_w_dropdown_url

 def test_asmt_from_template_w_dropdown_url(
     self, program, control_mapped_to_program, audit, selenium
 ):
   """Check evidence url could be filled in
   via Assessment dropdown.
   Objects structure:
   Program.
   -> Control mapped to program.
   -> Audit.
     -> Asmt template with evidence url dropdown.
       -> Autogenerated asmt.
   """
   asmt_template_w_dropdown = rest_facade.create_asmt_template_w_dropdown(
       audit, ["url"])
   expected_asmt = rest_facade.create_asmt_from_template_rest(
       audit, control_mapped_to_program, asmt_template_w_dropdown)
   dropdown = CustomAttributeDefinitionsFactory().create(
       **expected_asmt.cads_from_template()[0])
   asmt_service = webui_service.AssessmentsService(selenium)
   exp_url = StringMethods.random_string(
       size=StringMethods.RANDOM_STR_LENGTH)
   expected_asmt = asmt_service.choose_and_fill_dropdown_lca(
       expected_asmt, dropdown, url=exp_url)
   expected_asmt_urls = [exp_url]
   expected_asmt.update_attrs(
       updated_at=self.info_service().get_obj(obj=expected_asmt).updated_at,
       evidence_urls=expected_asmt_urls,
       mapped_objects=[control_mapped_to_program.title],
       status=object_states.IN_PROGRESS).repr_ui()
   actual_asmt = asmt_service.get_obj_from_info_page(obj=expected_asmt)
   self.general_equal_assert(expected_asmt, actual_asmt, "audit")
开发者ID:egorhm,项目名称:ggrc-core,代码行数:31,代码来源:test_asmts_workflow.py

示例8: remap_collection

 def remap_collection():
   """Get transformation dictionary {'OLD KEY': 'NEW KEY'}, where
   'OLD KEY' - UI elements and CSV fields correspond to
   'NEW KEY' - objects attributes.
   """
   from lib.constants import element, files
   els = element.TransformationElements
   csv = files.TransformationCSVFields
   # common for UI and CSV
   result_remap_items = {
       els.TITLE: "title", els.ADMIN: "admins",
       els.CODE: "slug", els.REVIEW_STATE: "os_state",
       els.OBJECT_REVIEW: "os_state",
       els.STATE: "status"
   }
   ui_remap_items = {
       els.MANAGER: "managers", els.VERIFIED: "verified",
       els.STATUS: "status", els.LAST_UPDATED: "updated_at",
       els.AUDIT_CAPTAINS: "audit_captains", els.CAS: "custom_attributes",
       els.MAPPED_OBJECTS: "mapped_objects", els.ASSIGNEES: "assignees",
       els.CREATORS: "creators", els.VERIFIERS: "verifiers",
       els.COMMENTS_HEADER: "comments", els.CREATED_AT: "created_at",
       els.MODIFIED_BY: "modified_by", els.LAST_UPDATED_BY: "modified_by",
       els.UPDATED_AT: "updated_at", els.ASMT_TYPE: "assessment_type"
   }
   csv_remap_items = {
       csv.REVISION_DATE: "updated_at"
   }
   result_remap_items.update(ui_remap_items)
   result_remap_items.update(csv_remap_items)
   return StringMethods.dict_keys_to_upper_case(result_remap_items)
开发者ID:,项目名称:,代码行数:31,代码来源:

示例9: get_attrs_names

 def get_attrs_names(cls, entity=None):
   """Get list unique entities attributes' names. If 'entity' then get
   attributes of one entered entity, else get attributes of all entities.
   """
   all_entities_cls = (help_utils.convert_to_list(entity) if entity
                       else list(Entity.all_entities_classes()))
   all_entities_attrs_names = StringMethods.convert_list_elements_to_list(
       [entity_cls().__dict__.keys() for entity_cls in all_entities_cls])
   return list(set(all_entities_attrs_names))
开发者ID:,项目名称:,代码行数:9,代码来源:

示例10: get_filter_exprs_by_ca

 def get_filter_exprs_by_ca(self, cad, cav, operator):
   """Return all possible filter expressions for CA according to CA type"""
   ca_type = cad.attribute_type
   if ca_type == AdminWidgetCustomAttributes.CHECKBOX:
     value = alias.YES_VAL if StringMethods.get_bool_value_from_arg(
         cav.attribute_value) else alias.NO_VAL
     values_to_filter = StringMethods.get_list_of_all_cases(value)
   elif ca_type == AdminWidgetCustomAttributes.PERSON:
     from lib.service import rest_service
     person = rest_service.ObjectsInfoService().get_obj(
         obj=Representation.repr_dict_to_obj(cav.attribute_object))
     values_to_filter = [person.name, person.email]
   elif ca_type == AdminWidgetCustomAttributes.DATE:
     date_formats = ["%m/%d/%Y", "%m/%Y", "%Y-%m-%d", "%Y-%m", "%Y"]
     date = parser.parse(cav.attribute_value).date()
     values_to_filter = [date.strftime(_format) for _format in date_formats]
   else:
     values_to_filter = [cav.attribute_value]
   return [self.get_filter_exp(cad.title, operator, [val])
           for val in values_to_filter]
开发者ID:egorhm,项目名称:ggrc-core,代码行数:20,代码来源:filter_utils.py

示例11: filter_objs_by_attrs

 def filter_objs_by_attrs(objs, **attrs):
   """Filter objects by attributes' items and return matched according to
   plurality.
   'objs' - object or list objects;
   '**attrs' - items of attributes' names and values.
   """
   list_objs = help_utils.convert_to_list(objs)
   matched_objs = [
       obj for obj in list_objs
       if isinstance(obj, Entity.all_entities_classes()) and
       StringMethods.is_subset_of_dicts(dict(**attrs), obj.__dict__)]
   return (help_utils.get_single_obj(matched_objs)
           if not help_utils.is_multiple_objs(matched_objs) else matched_objs)
开发者ID:,项目名称:,代码行数:13,代码来源:

示例12: compare_cas

 def compare_cas(self_cas, other_cas):
   """Compare entities' 'custom_attributes' attributes."""
   if (isinstance(self_cas, (dict, type(None))) and
           isinstance(other_cas, (dict, type(None)))):
     is_equal = False
     if (isinstance(self_cas, dict) and isinstance(other_cas, dict)):
       is_equal = StringMethods.is_subset_of_dicts(self_cas, other_cas)
     else:
       is_equal = self_cas == other_cas
     return is_equal
   else:
     Representation.attrs_values_types_error(
         self_attr=self_cas, other_attr=other_cas,
         expected_types=(dict.__name__, type(None).__name__))
开发者ID:,项目名称:,代码行数:14,代码来源:

示例13: _set_custom_attributes_list

 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_CSS):
     attrs = [i.text for i in row.find_elements(
         *self._locators.CELL_IN_ROW_CSS)]
     # todo: add PO and getting 'multi_choice_options' via 'Edit' btn
     self.custom_attributes_list.append(
         CustomAttributeDefinitionsFactory().create(
             title=attrs[0], attribute_type=attrs[1],
             mandatory=StringMethods.get_bool_value_from_arg(attrs[2]),
             definition_type=self._item_name, multi_choice_options=None))
开发者ID:,项目名称:,代码行数:14,代码来源:

示例14: get_list_objs_from_csv

 def get_list_objs_from_csv(self, path_to_exported_file):
   """Get and return list of objects from CSV file of exported objects in
   test's temporary directory 'path_to_export_dir'.
   """
   # pylint: disable=invalid-name
   dict_list_objs_scopes = file_utils.get_list_objs_scopes_from_csv(
       path_to_csv=path_to_exported_file)
   dict_key = dict_list_objs_scopes.iterkeys().next()
   # 'Control' to 'controls', 'Control Snapshot' to 'controls'
   obj_name_from_dict = objects.get_plural(
       StringMethods.get_first_word_from_str(dict_key))
   if self.obj_name == obj_name_from_dict:
     return self._create_list_objs(
         entity_factory=self.entities_factory_cls,
         list_scopes=dict_list_objs_scopes[dict_key])
   else:
     raise ValueError(messages.ExceptionsMessages.err_csv_format.
                      format(dict_list_objs_scopes))
开发者ID:egorhm,项目名称:ggrc-core,代码行数:18,代码来源:webui_service.py

示例15: generate_cad

 def generate_cad(cls, **attrs):
   """Creates multi-choice dropdown CAD for asmt template."""
   multi_choice_opts = {"file": "2", "url": "4", "comment": "1",
                        "file_url": "6", "url_comment": "5",
                        "file_comment": "3", "file_url_comment": "7",
                        "nothing": "0"}
   dropdown_types_list = attrs["dropdown_types_list"]
   cad_factory = CustomAttributeDefinitionsFactory()
   cad = cad_factory.create(
       attribute_type=AdminWidgetCustomAttributes.DROPDOWN,
       definition_type="",
       multi_choice_mandatory=(",".join(
           multi_choice_opts[dropdown_type]
           for dropdown_type in dropdown_types_list)),
       multi_choice_options=(
           StringMethods.random_list_strings(
               list_len=len(dropdown_types_list))))
   return cad_factory.generate_cads_for_asmt_tmpls([cad])[0]
开发者ID:,项目名称:,代码行数:18,代码来源:


注:本文中的lib.utils.string_utils.StringMethods类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。