Ejemplo n.º 1
0
 def get_filter_exprs_by_ca(self, ca_title, ca_val, ca_type, operator):
     """Return all possible filter expressions for CA according to CA type"""
     if ca_type == AdminWidgetCustomAttributes.CHECKBOX:
         values_to_filter = (StringMethods.get_list_of_all_cases(
             alias.YES_VAL) if StringMethods.get_bool_value_from_arg(ca_val)
                             else StringMethods.get_list_of_all_cases(
                                 alias.NO_VAL))
     elif ca_type == AdminWidgetCustomAttributes.PERSON:
         from lib.service import rest_service
         person = rest_service.ObjectsInfoService().get_obj(
             obj=Representation.repr_dict_to_obj(
                 dict(zip(["type", "id"], ca_val.split(":")))))
         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(ca_val).date()
         values_to_filter = [
             date.strftime(_format) for _format in date_formats
         ]
     else:
         values_to_filter = [ca_val]
     return [
         self.get_filter_exp(ca_title, operator, [val])
         for val in values_to_filter
     ]
Ejemplo n.º 2
0
 def wrapper(*args, **kwargs):
     "Wrapper."
     from lib.service import rest_service
     result = fun(*args, **kwargs)
     # need to wait when creation background job is finished
     rest_service.ObjectsInfoService().get_obj(result)
     return result
Ejemplo n.º 3
0
 def convert_obj_repr_to_snapshot(origin_obj, parent_obj):
   """Convert object's attributes to Snapshot representation."""
   from lib.service import rest_service
   origin_obj = copy.deepcopy(origin_obj)
   snapshoted_obj = (
       rest_service.ObjectsInfoService().get_snapshoted_obj(
           origin_obj=origin_obj, paren_obj=parent_obj))
   origin_obj.__dict__.update(
       {k: v for k, v in snapshoted_obj.__dict__.iteritems()})
   return origin_obj
Ejemplo n.º 4
0
 def tree_item_representation(self):
     """Make object's copy and convert it to the view of tree item."""
     obj = copy.deepcopy(self)
     for attr in obj.tree_view_attrs_to_exclude:
         setattr(obj, attr, None)
     from lib.service import rest_service
     new_modified_by_value = getattr(
         rest_service.ObjectsInfoService().get_obj(
             obj=obj.repr_dict_to_obj(obj.modified_by)), "email")
     obj.modified_by = new_modified_by_value
     return obj
Ejemplo n.º 5
0
def _assert_title_editable(obj, ui_service, info_page):
  """Assert that user can edit object's title"""
  new_title = "[EDITED]" + obj.title
  info_page.open_info_3bbs().select_edit().edit_minimal_data(
      title=new_title).save_and_close()
  obj.update_attrs(
      title=new_title, modified_by=users.current_user().email,
      updated_at=rest_service.ObjectsInfoService().get_obj(
          obj=obj).updated_at)
  new_ui_obj = ui_service.get_obj_from_info_page(obj)
  base.Test.general_equal_assert(
      obj.repr_ui(), new_ui_obj, "custom_attributes")
Ejemplo n.º 6
0
def _assert_title_editable(obj, selenium, info_page):
    """Assert that user can edit object's title"""
    new_title = "[EDITED]" + obj.title
    info_page.three_bbs.select_edit()
    modal = object_modal.get_modal_obj(obj.type, selenium)
    modal.fill_form(title=new_title)
    modal.save_and_close()
    obj.update_attrs(title=new_title,
                     modified_by=users.current_user().email,
                     updated_at=rest_service.ObjectsInfoService().get_obj(
                         obj=obj).updated_at)
    new_ui_obj = _get_ui_service(selenium, obj).get_obj_from_info_page(obj)
    base.Test.general_equal_assert(obj.repr_ui(), new_ui_obj, "audit",
                                   "custom_attributes")
Ejemplo n.º 7
0
def submit_obj_for_review(selenium, obj, reviewer):
    """Submit object for review scenario.
  Returns obj with assigned review."""
    review_comment = string_utils.StringMethods.random_string()
    _get_ui_service(selenium, obj).submit_for_review(obj, reviewer.email,
                                                     review_comment)
    obj.update_attrs(review=entities_factory.ReviewsFactory().create(
        reviewers=reviewer))
    exp_comment = entities_factory.CommentsFactory(
    ).create(description=element.Common.REVIEW_COMMENT_PATTERN.format(
        # reviewers emails in review comment message need to be sorted
        # as they are displayed in UI in random order
        emails=', '.join(sorted(obj.review["reviewers"])),
        comment=review_comment))
    exp_comment.created_at = rest_service.ObjectsInfoService().get_comment_obj(
        paren_obj=obj, comment_description=review_comment).created_at
    obj.comments = [exp_comment.repr_ui()]
    return obj
Ejemplo n.º 8
0
class TestAssessmentsWorkflow(base.Test):
  """Tests for Assessments Workflow functionality."""
  info_service = rest_service.ObjectsInfoService()

  @pytest.mark.smoke_tests
  def test_add_comment_to_asmt_via_info_panel(
      self, new_program_rest, new_audit_rest, new_assessment_rest, selenium
  ):
    """Check via UI of possibility to correctly add comment to Assessment via
    Info Panel.
    Preconditions:
    - Program created via REST API.
    - Audit created under Program via REST API.
    - Assessment created under Audit via REST API.
    Test parameters: None
    """
    expected_asmt_comments = [entities_factory.CommentsFactory().create()]
    expected_asmt = new_assessment_rest
    asmts_ui_service = webui_service.AssessmentsService(selenium)
    asmt_comments_panel = asmts_ui_service.add_comments(
        src_obj=new_audit_rest, obj=expected_asmt,
        comment_objs=expected_asmt_comments)
    assert asmt_comments_panel.is_input_empty is True
    # 'expected_asmt_comments': created_at (None) *factory
    expected_asmt_comments = [expected_comment.update_attrs(
        created_at=self.info_service.get_comment_obj(
            paren_obj=expected_asmt,
            comment_description=expected_comment.description).created_at
    ).repr_ui() for expected_comment in expected_asmt_comments]
    # 'expected_asmt': updated_at (outdated)
    expected_asmt = expected_asmt.update_attrs(
        updated_at=self.info_service.get_obj(obj=expected_asmt).updated_at,
        comments=expected_asmt_comments).repr_ui()
    actual_asmt = asmts_ui_service.get_obj_from_info_page(obj=expected_asmt)
    self.general_equal_assert(expected_asmt, actual_asmt, "comments")
    self.xfail_equal_assert(
        expected_asmt, actual_asmt, "Issue in app GGRC-3094", "comments")

  @pytest.mark.smoke_tests
  def test_asmt_logs(
      self, new_program_rest, new_audit_rest, new_assessment_rest, selenium
  ):
    """Test for validation of Assessment log pane.
    Acceptance criteria:
      1) 3 log items at the log pane
      2) all items return 'True' for all attrs.
    """
    log_items_validation = webui_service.AssessmentsService(
        selenium).get_log_pane_validation_result(obj=new_assessment_rest)
    log_validation_results = [all(item_result.values()) for item_result in
                              log_items_validation]
    assert ([True] * 3) == log_validation_results, str(log_items_validation)

  @pytest.mark.smoke_tests
  def test_asmt_related_asmts(
      self, new_program_rest, new_control_rest,
      map_new_program_rest_to_new_control_rest, new_audit_rest,
      new_assessments_rest, selenium
  ):
    """Test for checking Related Assessments. Map two Assessments to one
    snapshot of control. And check second Assessment contains in "Related
    Assessments" Tab of first Assessment. 3 Titles will be compared:
    Assessment, Audit of Assessment, generic Control.
    """
    expected_titles = [(new_assessments_rest[1].title,
                        new_control_rest.title,
                        new_audit_rest.title)]
    asmts_ui_service = webui_service.AssessmentsService(selenium)
    asmts_ui_service.map_objs_via_tree_view_item(
        src_obj=new_audit_rest, dest_objs=[new_control_rest])
    related_asmts_objs_titles = (
        asmts_ui_service.get_related_asmts_titles(
            obj=new_assessments_rest[0]))
    assert expected_titles == related_asmts_objs_titles

  @pytest.mark.smoke_tests
  def test_raise_issue(
      self, new_program_rest, new_audit_rest, new_assessment_rest, selenium
  ):
    """Test for checking raising Issues in Related Issues Tab. Open
    Related Issues tab on Assessments Info page. Raise Issue with pre-defined
    attributes via "raise issue" button. Compare expected Issue title and
    actual issue_titles.
    """
    expected_issue = (entities_factory.IssuesFactory().create().repr_ui())
    asmts_ui_service = webui_service.AssessmentsService(selenium)
    asmts_ui_service.raise_issue(new_assessment_rest, expected_issue)
    related_issues_titles = asmts_ui_service.get_related_issues_titles(
        obj=new_assessment_rest)
    assert related_issues_titles == [expected_issue.title]

  @pytest.mark.smoke_tests
  @pytest.mark.parametrize(
      ("dynamic_objects_w_factory_params", "action",
       "expected_initial_state", "expected_final_state", "expected_verified"),
      [(("new_assessment_rest", {"status":
                                 AssessmentStates.NOT_STARTED}),
        "edit_obj_via_edit_modal_from_info_page",
        None, AssessmentStates.IN_PROGRESS, False),
       (("new_assessment_rest", {"status": AssessmentStates.NOT_STARTED,
                                 "verifier": [roles.DEFAULT_USER]}),
        "edit_obj_via_edit_modal_from_info_page",
        None, AssessmentStates.IN_PROGRESS, False),
       (("new_assessment_rest", {"status": AssessmentStates.IN_PROGRESS}),
        "edit_obj_via_edit_modal_from_info_page",
        None, AssessmentStates.IN_PROGRESS, False),
       (("new_assessment_rest", {"status": AssessmentStates.IN_PROGRESS,
                                 "verifier": [roles.DEFAULT_USER]}),
        "edit_obj_via_edit_modal_from_info_page",
        None, AssessmentStates.IN_PROGRESS, False),
       (("new_assessment_rest", {"status": AssessmentStates.IN_PROGRESS}),
        "edit_obj_via_edit_modal_from_info_page",
        AssessmentStates.COMPLETED, AssessmentStates.IN_PROGRESS, False),
       (("new_assessment_rest", {"status": AssessmentStates.IN_PROGRESS,
                                 "verifier": [roles.DEFAULT_USER]}),
        "edit_obj_via_edit_modal_from_info_page",
        AssessmentStates.COMPLETED, AssessmentStates.IN_PROGRESS, False),
       (("new_assessment_rest", {"status": AssessmentStates.NOT_STARTED}),
        "complete_assessment", None, AssessmentStates.COMPLETED, False),
       (("new_assessment_rest", {"status": AssessmentStates.NOT_STARTED,
                                 "verifier": [roles.DEFAULT_USER]}),
        "complete_assessment", None, AssessmentStates.READY_FOR_REVIEW, False),
       (("new_assessment_rest", {"status": AssessmentStates.IN_PROGRESS}),
        "complete_assessment", None, AssessmentStates.COMPLETED, False),
       (("new_assessment_rest", {"status": AssessmentStates.IN_PROGRESS,
                                 "verifier": [roles.DEFAULT_USER]}),
        "complete_assessment", None, AssessmentStates.READY_FOR_REVIEW, False),
       (("new_assessment_rest", {"status": AssessmentStates.IN_PROGRESS,
                                 "verifier": [roles.DEFAULT_USER]}),
        "verify_assessment",
        AssessmentStates.READY_FOR_REVIEW, AssessmentStates.COMPLETED, True),
       (("new_assessment_rest", {"status": AssessmentStates.IN_PROGRESS,
                                 "verifier": [roles.DEFAULT_USER]}),
        "reject_assessment",
        AssessmentStates.READY_FOR_REVIEW, AssessmentStates.IN_PROGRESS, False)
       ],
      ids=["Edit asmt w'o verifier 'Not Started' - 'In Progress'",
           "Edit asmt w' verifier 'Not Started' - 'In Progress'",
           "Edit asmt w'o verifier 'In Progress' - 'In Progress'",
           "Edit asmt w' verifier 'In Progress' - 'In Progress'",
           "Edit asmt w'o verifier 'Completed' - 'In Progress'",
           "Edit asmt w' verifier 'Completed' - 'In Progress'",
           "Complete asmt w'o verifier 'Not Started' - 'Completed'",
           "Complete asmt w' verifier 'Not Started' - 'In Review'",
           "Complete asmt w'o verifier 'In Progress' - 'Completed'",
           "Complete asmt w' verifier 'In Progress' - 'In Review'",
           "Verify asmt w' verifier 'In Review' - 'Completed'",
           "Reject asmt w' verifier 'In Review' - 'In Progress'"],
      indirect=["dynamic_objects_w_factory_params"])
  def test_check_asmt_state_change(
      self, new_program_rest, new_audit_rest, dynamic_objects_w_factory_params,
      action, expected_initial_state, expected_final_state, expected_verified,
      selenium
  ):
    """Check Assessment workflow status change to correct state.
    Preconditions:
    - Program created via REST API.
    - Audit created under Program via REST API.
    - Assessment created and updated under Audit via REST API.
    """
    expected_asmt = dynamic_objects_w_factory_params
    if expected_initial_state:
      (rest_service.AssessmentsService().
       update_obj(expected_asmt, status=expected_initial_state))
    asmts_ui_service = webui_service.AssessmentsService(selenium)
    getattr(asmts_ui_service, action)(expected_asmt)
    # 'expected_asmt': updated_at (outdated)
    expected_asmt = (expected_asmt.update_attrs(
        title=(element.AssessmentInfoWidget.TITLE_EDITED_PART +
               expected_asmt.title if "edit" in action
               else expected_asmt.title),
        status=expected_final_state.title(), verified=expected_verified,
        updated_at=self.info_service.get_obj(
            obj=expected_asmt).updated_at).repr_ui())
    actual_asmt = asmts_ui_service.get_obj_from_info_page(expected_asmt)
    self.general_equal_assert(expected_asmt, actual_asmt)

  @pytest.mark.smoke_tests
  @pytest.mark.parametrize("operator", [alias.EQUAL_OP, alias.CONTAINS_OP])
  def test_asmts_gcas_filtering(
      self, new_program_rest, new_audit_rest, new_cas_for_assessments_rest,
      new_assessments_rest, operator, selenium
  ):
    """Test for checking filtering of Assessment by Custom Attributes in
    audit scope.
    Preconditions:
    - Program created via REST API.
    - Audit created via REST API.
    - Assessments created via REST API.
    - Global Custom Attributes for Assessment created via REST API.
    - Set revers value of GCA with Checkbox type for second Assessment.
    """
    # pylint: disable=too-many-locals
    custom_attr_values = (
        CustomAttributeDefinitionsFactory().generate_ca_values(
            list_ca_def_objs=new_cas_for_assessments_rest))
    checkbox_id = entity.Entity.filter_objs_by_attrs(
        objs=new_cas_for_assessments_rest,
        attribute_type=element.AdminWidgetCustomAttributes.CHECKBOX).id
    expected_asmt = new_assessments_rest[0]
    asmts_rest_service = rest_service.AssessmentsService()
    asmts_rest_service.update_obj(
        obj=expected_asmt, custom_attributes=custom_attr_values)
    asmts_rest_service.update_obj(
        obj=new_assessments_rest[1],
        custom_attributes={checkbox_id: not custom_attr_values[checkbox_id]})
    filter_exprs = FilterUtils().get_filter_exprs_by_cas(
        expected_asmt.custom_attribute_definitions, custom_attr_values,
        operator)
    # 'expected_asmt': updated_at (outdated)
    # 'actual_asmts': created_at, updated_at, custom_attributes (None)
    expected_asmt = entity.Entity.extract_objs_wo_excluded_attrs(
        [expected_asmt.update_attrs(
            status=AssessmentStates.IN_PROGRESS).repr_ui()],
        *Representation.tree_view_attrs_to_exclude)[0]
    expected_results = [{"filter": filter_expr,
                         "objs": [expected_asmt]}
                        for filter_expr in filter_exprs]
    actual_results = [
        {"filter": filter_expr,
         "objs": entity.Entity.extract_objs_wo_excluded_attrs(
             webui_service.AssessmentsService(
                 selenium).filter_and_get_list_objs_from_tree_view(
                 new_audit_rest, filter_expr),
             *("updated_at", "custom_attributes"))
         } for filter_expr in filter_exprs]
    assert expected_results == actual_results, (
        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(
            string_utils.convert_list_elements_to_list(
                [exp_res["objs"] for exp_res in expected_results]),
            string_utils.convert_list_elements_to_list(
                [act_res["objs"] for act_res in actual_results])))

  @pytest.mark.smoke_tests
  @pytest.mark.parametrize(
      "dynamic_objects, dynamic_relationships",
      [("new_objective_rest", "map_new_program_rest_to_new_objective_rest"),
       ("new_control_rest", "map_new_program_rest_to_new_control_rest")],
      indirect=True)
  def test_map_snapsots_to_asmt_via_edit_modal(
      self, new_program_rest, dynamic_objects, dynamic_relationships,
      new_audit_rest, new_assessment_rest, selenium
  ):
    """Check Assessment can be mapped with snapshot via Modal Edit
    on Assessments Info Page. Additional check existing of mapped obj Titles
    on Modal Edit.
    Preconditions:
    - Program, dynamic_objects created via REST API.
    - dynamic_objects mapped to Program via REST API.
    - Audit created under Program via REST API.
    - Assessment created under audit via REST API.
    Test parameters:
    - 'dynamic_objects'.
    - 'dynamic_relationships'.
    """
    expected_asmt = (new_assessment_rest.update_attrs(
        objects_under_assessment=[dynamic_objects],
        status=AssessmentStates.IN_PROGRESS))
    expected_titles = [dynamic_objects.title]
    asmts_ui_service = webui_service.AssessmentsService(selenium)
    actual_titles = (
        asmts_ui_service.map_objs_and_get_mapped_titles_from_edit_modal(
            expected_asmt, expected_asmt.objects_under_assessment))
    assert expected_titles == actual_titles
    # 'expected_asmt': updated_at (outdated)
    expected_asmt = (
        expected_asmt.update_attrs(updated_at=self.info_service.get_obj(
            obj=expected_asmt).updated_at).repr_ui())
    actual_asmt = asmts_ui_service.get_obj_from_info_page(expected_asmt)
    self.general_equal_assert(expected_asmt, actual_asmt)
Ejemplo n.º 9
0
 def external_app_user(cls):
     """Return Person instance for default system external app user."""
     from lib.service import rest_service
     return rest_service.ObjectsInfoService().get_person(
         users.EXTERNAL_APP_USER.email)
Ejemplo n.º 10
0
 def superuser(cls):
     """Return Person instance for default system superuser."""
     from lib.service import rest_service
     return rest_service.ObjectsInfoService().get_person(
         users.FAKE_SUPER_USER.email)
Ejemplo n.º 11
0
 def convert_obj_repr_from_rest_to_ui(obj):
   """Convert object's attributes from REST to UI like representation."""
   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", "assignee", "creator",
           "verifier", "created_by", "modified_by", "Assignee", "Creator",
           "Verifier"
       ]:
         converted_attr_value = unicode(attr_value.get("email"))
       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: (parser.parse(v).replace(tzinfo=tz.tzutc()) 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 ["assignee", "creator", "verifier"] and
         "assignees" in obj.__dict__.keys())
         else getattr(obj, obj_attr_name))
     # REST like u'08-20-2017T04:30:45' to date=2017-08-20,
     # timetz=04:30:45+00:00
     if (obj_attr_name in ["updated_at", "created_at"] and
             isinstance(obj_attr_value, unicode)):
       obj_attr_value = (parser.parse(obj_attr_value).
                         replace(tzinfo=tz.tzutc()))
     if isinstance(obj_attr_value, dict) and obj_attr_value:
       # to "assignees" = {"Assignee": [], "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 ["Assignee", "Creator", "Verifier"]}
       # "modified_by" {"type": "Person", "id": x} to u'*****@*****.**'
       if obj_attr_name == "modified_by":
         from lib.service import rest_service
         obj_attr_value = getattr(rest_service.ObjectsInfoService().get_obj(
             obj=Entity.convert_dict_to_obj_repr(obj_attr_value)), "email")
       # {'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 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))):
       from lib.entities.entities_factory import (
           CustomAttributeDefinitionsFactory)
       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 = StringMethods.merge_dicts_by_same_key(cas_def_dict, cas_val_dict)
     setattr(obj, "custom_attributes", cas)
   return obj
Ejemplo n.º 12
0
def get_snapshot(obj, parent_obj):
    """Get (or create) a snapshot of `obj` in `parent_obj`"""
    return rest_service.ObjectsInfoService().get_snapshoted_obj(
        origin_obj=obj, paren_obj=parent_obj)
Ejemplo n.º 13
0
def get_obj(obj):
    """Get an object"""
    return rest_service.ObjectsInfoService().get_obj(obj)
Ejemplo n.º 14
0
 def default_user(cls):
     """Return Person instance for default system superuser."""
     from lib.service import rest_service
     return rest_service.ObjectsInfoService().get_person(
         users.DEFAULT_USER_EMAIL)
class TestAssessmentsWorkflow(base.Test):
    """Tests for Assessments Workflow functionality."""
    info_service = rest_service.ObjectsInfoService()

    @pytest.mark.smoke_tests
    def test_add_comment_to_asmt_via_info_panel(self, new_program_rest,
                                                new_audit_rest,
                                                new_assessment_rest, selenium):
        """Check via UI of possibility to correctly add comment to Assessment via
    Info Panel.
    Preconditions:
    - Program created via REST API.
    - Audit created under Program via REST API.
    - Assessment created under Audit via REST API.
    Test parameters: None
    """
        expected_asmt_comments = [entities_factory.CommentsFactory().create()]
        expected_asmt = new_assessment_rest
        asmts_ui_service = webui_service.AssessmentsService(selenium)
        asmt_comments_panel = asmts_ui_service.add_comments(
            src_obj=new_audit_rest,
            obj=expected_asmt,
            comment_objs=expected_asmt_comments)
        assert asmt_comments_panel.is_input_empty is True
        # 'expected_asmt_comments': created_at (None) *factory
        expected_asmt_comments = [
            expected_comment.update_attrs(
                created_at=self.info_service.get_comment_obj(
                    paren_obj=expected_asmt,
                    comment_description=expected_comment.description).
                created_at).repr_ui()
            for expected_comment in expected_asmt_comments
        ]
        # 'expected_asmt': updated_at (outdated)
        expected_asmt.update_attrs(
            updated_at=self.info_service.get_obj(obj=expected_asmt).updated_at,
            comments=expected_asmt_comments,
            status=AssessmentStates.IN_PROGRESS).repr_ui()
        actual_asmt = asmts_ui_service.get_obj_from_info_page(
            obj=expected_asmt)
        # 'actual_asmt': audit (None)
        self.general_equal_assert(expected_asmt, actual_asmt, "audit",
                                  "comments")
        self.xfail_equal_assert(expected_asmt, actual_asmt,
                                "Issue in app GGRC-3094", "comments")

    @pytest.mark.smoke_tests
    def test_asmt_logs(self, new_program_rest, new_audit_rest,
                       new_assessment_rest, selenium):
        """Test for validation of Assessment log pane.
    Acceptance criteria:
      1) 3 log items at the log pane
      2) all items return 'True' for all attrs.
    """
        log_items_validation = webui_service.AssessmentsService(
            selenium).get_log_pane_validation_result(obj=new_assessment_rest)
        log_validation_results = [
            all(item_result.values()) for item_result in log_items_validation
        ]
        assert ([True] *
                2) == log_validation_results, str(log_items_validation)

    @pytest.mark.smoke_tests
    def test_asmt_related_asmts(self, new_program_rest, new_control_rest,
                                map_new_program_rest_to_new_control_rest,
                                new_audit_rest, new_assessments_rest,
                                selenium):
        """Test for checking Related Assessments. Map two Assessments to one
    snapshot of control. And check second Assessment contains in "Related
    Assessments" Tab of first Assessment. 3 Titles will be compared:
    Assessment, Audit of Assessment, generic Control.
    """
        expected_titles = [(new_assessments_rest[1].title,
                            new_control_rest.title, new_audit_rest.title)]
        asmts_ui_service = webui_service.AssessmentsService(selenium)
        asmts_ui_service.map_objs_via_tree_view_item(
            src_obj=new_audit_rest, dest_objs=[new_control_rest])
        related_asmts_objs_titles = (asmts_ui_service.get_related_asmts_titles(
            obj=new_assessments_rest[0]))
        assert expected_titles == related_asmts_objs_titles

    @pytest.mark.smoke_tests
    def test_raise_issue(self, new_program_rest, new_audit_rest,
                         new_assessment_rest, selenium):
        """Test for checking raising Issues in Related Issues Tab. Open
    Related Issues tab on Assessments Info page. Raise Issue with pre-defined
    attributes via "raise issue" button. Compare expected Issue title and
    actual issue_titles.
    """
        expected_issue = (entities_factory.IssuesFactory().create().repr_ui())
        asmts_ui_service = webui_service.AssessmentsService(selenium)
        asmts_ui_service.raise_issue(new_assessment_rest, expected_issue)
        related_issues_titles = asmts_ui_service.get_related_issues_titles(
            obj=new_assessment_rest)
        assert related_issues_titles == [expected_issue.title]

    @pytest.mark.smoke_tests
    @pytest.mark.parametrize(
        ("dynamic_objects_w_factory_params", "action", "expected_final_state",
         "expected_verified"),
        [(("new_assessment_rest", {
            "status": AssessmentStates.NOT_STARTED
        }), "edit_obj_via_edit_modal_from_info_page",
          AssessmentStates.NOT_STARTED, False),
         (("new_assessment_rest", {
             "status": AssessmentStates.NOT_STARTED,
             "verifiers": [PeopleFactory().default_user]
         }), "edit_obj_via_edit_modal_from_info_page",
          AssessmentStates.NOT_STARTED, False),
         (("new_assessment_rest", {
             "status": AssessmentStates.IN_PROGRESS
         }), "edit_obj_via_edit_modal_from_info_page",
          AssessmentStates.IN_PROGRESS, False),
         (("new_assessment_rest", {
             "status": AssessmentStates.IN_PROGRESS,
             "verifiers": [PeopleFactory().default_user]
         }), "edit_obj_via_edit_modal_from_info_page",
          AssessmentStates.IN_PROGRESS, False),
         (("new_assessment_rest", {
             "status": AssessmentStates.COMPLETED
         }), "edit_obj_via_edit_modal_from_info_page",
          AssessmentStates.IN_PROGRESS, False),
         (("new_assessment_rest", {
             "status": AssessmentStates.COMPLETED,
             "verifiers": [PeopleFactory().default_user]
         }), "edit_obj_via_edit_modal_from_info_page",
          AssessmentStates.IN_PROGRESS, False),
         (("new_assessment_rest", {
             "status": AssessmentStates.NOT_STARTED
         }), "complete_assessment", AssessmentStates.COMPLETED, False),
         (("new_assessment_rest", {
             "status": AssessmentStates.NOT_STARTED,
             "verifiers": [PeopleFactory().default_user]
         }), "complete_assessment", AssessmentStates.READY_FOR_REVIEW, False),
         (("new_assessment_rest", {
             "status": AssessmentStates.IN_PROGRESS
         }), "complete_assessment", AssessmentStates.COMPLETED, False),
         (("new_assessment_rest", {
             "status": AssessmentStates.IN_PROGRESS,
             "verifiers": [PeopleFactory().default_user]
         }), "complete_assessment", AssessmentStates.READY_FOR_REVIEW, False),
         (("new_assessment_rest", {
             "status": AssessmentStates.NOT_STARTED,
             "verifiers": [PeopleFactory().default_user]
         }), "verify_assessment", AssessmentStates.COMPLETED, True),
         (("new_assessment_rest", {
             "status": AssessmentStates.NOT_STARTED,
             "verifiers": [PeopleFactory().default_user]
         }), "reject_assessment", AssessmentStates.REWORK_NEEDED, False)],
        ids=[
            "Edit asmt's title w'o verifier 'Not Started' - 'Not Started'",
            "Edit asmt's title w' verifier 'Not Started' - 'Not Started'",
            "Edit asmt's title w'o verifier 'In Progress' - 'In Progress'",
            "Edit asmt's title w' verifier 'In Progress' - 'In Progress'",
            "Edit asmt's title w'o verifier 'Completed' - 'In Progress'",
            "Edit asmt's title w' verifier 'Completed' - 'In Progress'",
            "Complete asmt w'o verifier 'Not Started' - 'Completed'",
            "Complete asmt w' verifier 'Not Started' - 'In Review'",
            "Complete asmt w'o verifier 'In Progress' - 'Completed'",
            "Complete asmt w' verifier 'In Progress' - 'In Review'",
            "Verify asmt w' verifier 'In Review' - 'Completed'",
            "Reject asmt w' verifier 'In Review' - 'Rework Needed'"
        ],
        indirect=["dynamic_objects_w_factory_params"])
    def test_check_asmt_state_change(self, new_program_rest, new_audit_rest,
                                     dynamic_objects_w_factory_params, action,
                                     expected_final_state, expected_verified,
                                     selenium):
        """Check Assessment workflow status change to correct state.
    Preconditions:
    - Program created via REST API.
    - Audit created under Program via REST API.
    - Assessment created and updated under Audit via REST API.
    """
        expected_asmt = dynamic_objects_w_factory_params
        asmts_ui_service = webui_service.AssessmentsService(selenium)
        # UI part of preparing pre-requirements (due to REST doesn't allow it)
        if action in ("verify_assessment", "reject_assessment"):
            getattr(asmts_ui_service, "complete_assessment")(expected_asmt)
        getattr(asmts_ui_service, action)(expected_asmt)
        # 'expected_asmt': updated_at (outdated)
        expected_asmt.update_attrs(
            title=(element.AssessmentInfoWidget.TITLE_EDITED_PART +
                   expected_asmt.title
                   if "edit" in action else expected_asmt.title),
            status=expected_final_state.title(),
            verified=expected_verified,
            updated_at=self.info_service.get_obj(
                obj=expected_asmt).updated_at).repr_ui()
        actual_asmt = asmts_ui_service.get_obj_from_info_page(expected_asmt)
        # 'actual_asmt': audit (None)
        self.general_equal_assert(expected_asmt, actual_asmt, "audit")

    @pytest.mark.smoke_tests
    @pytest.mark.parametrize("operator", [alias.EQUAL_OP, alias.CONTAINS_OP])
    def test_asmts_gcas_filtering(self, new_program_rest, new_audit_rest,
                                  new_cas_for_assessments_rest,
                                  new_assessments_rest, operator, selenium):
        """Test for checking filtering of Assessment by Global Custom Attributes
    in audit scope.
    Preconditions:
    - Program created via REST API.
    - Audit created via REST API.
    - Global Custom Attributes for Assessment created via REST API.
    - Assessments created via REST API.
    """
        custom_attr_values = (
            CustomAttributeDefinitionsFactory().generate_ca_values(
                list_ca_def_objs=new_cas_for_assessments_rest))
        checkbox_id = Representation.filter_objs_by_attrs(
            objs=new_cas_for_assessments_rest,
            attribute_type=element.AdminWidgetCustomAttributes.CHECKBOX).id
        expected_asmt = new_assessments_rest[0]
        asmts_rest_service = rest_service.AssessmentsService()
        asmts_rest_service.update_obj(obj=expected_asmt,
                                      custom_attributes=custom_attr_values)
        asmts_rest_service.update_obj(obj=new_assessments_rest[1],
                                      custom_attributes={
                                          checkbox_id:
                                          not custom_attr_values[checkbox_id]
                                      })
        self._check_assessments_filtration(expected_asmt, custom_attr_values,
                                           operator, new_audit_rest, selenium)

    @pytest.mark.smoke_tests
    @pytest.mark.parametrize("operator", [alias.EQUAL_OP])
    def test_asmts_lcas_filtering(self, new_program_rest, new_controls_rest,
                                  map_new_program_rest_to_new_controls_rest,
                                  new_audit_rest,
                                  new_assessment_template_with_cas_rest,
                                  new_assessments_from_template_rest, operator,
                                  selenium):
        """Test for checking filtering of Assessment by Local Custom Attributes
    in audit scope.
    Preconditions:
    - Program created via REST API.
    - Controls created via REST API and mapped to program.
    - Audit created via REST API.
    - Assessment template with LCA created via REST API.
    - Assessments for assessment template created via REST API.
    """
        def set_values_for_assessment(assessment, only_checkbox,
                                      checkbox_value):
            """Set LCA values for assessment"""
            custom_attr_definitions = [
                CustomAttributeDefinitionsFactory().create(**definition)
                for definition in assessment.cads_from_template()
            ]
            checkbox_id = Representation.filter_objs_by_attrs(
                objs=custom_attr_definitions,
                attribute_type=element.AdminWidgetCustomAttributes.CHECKBOX).id
            if only_checkbox:
                attr_values = {}
            else:
                attr_values = CustomAttributeDefinitionsFactory(
                ).generate_ca_values(list_ca_def_objs=custom_attr_definitions)
                attr_values[checkbox_id] = checkbox_value
            rest_service.AssessmentsService().update_obj(
                obj=assessment, custom_attributes=attr_values)
            return attr_values

        unchecked_asmt = new_assessments_from_template_rest[0]
        checked_asmt = new_assessments_from_template_rest[1]

        set_values_for_assessment(unchecked_asmt,
                                  only_checkbox=True,
                                  checkbox_value=False)
        set_attr_values = set_values_for_assessment(checked_asmt,
                                                    only_checkbox=False,
                                                    checkbox_value=True)

        self._check_assessments_filtration(checked_asmt, set_attr_values,
                                           operator, new_audit_rest, selenium)

    @staticmethod
    def _check_assessments_filtration(assessment, attr_values, operator, audit,
                                      selenium):
        """Check that filtration of assessments works."""
        filter_exprs = FilterUtils().get_filter_exprs_by_cas(
            assessment.custom_attribute_definitions, attr_values, 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

    @pytest.mark.smoke_tests
    @pytest.mark.parametrize(
        "dynamic_objects, dynamic_relationships",
        [("new_objective_rest", "map_new_program_rest_to_new_objective_rest"),
         ("new_control_rest", "map_new_program_rest_to_new_control_rest")],
        indirect=True)
    def test_map_snapsots_to_asmt_via_edit_modal(
            self, new_program_rest, dynamic_objects, dynamic_relationships,
            new_audit_rest, new_assessment_rest, selenium):
        """Check Assessment can be mapped with snapshot via Modal Edit
    on Assessments Info Page. Additional check existing of mapped obj Titles
    on Modal Edit.
    Preconditions:
    - Program, dynamic_objects created via REST API.
    - dynamic_objects mapped to Program via REST API.
    - Audit created under Program via REST API.
    - Assessment created under audit via REST API.
    Test parameters:
    - 'dynamic_objects'.
    - 'dynamic_relationships'.
    """
        expected_asmt = (new_assessment_rest.update_attrs(
            mapped_objects=[dynamic_objects]))
        expected_titles = [dynamic_objects.title]
        asmts_ui_service = webui_service.AssessmentsService(selenium)
        actual_titles = (
            asmts_ui_service.map_objs_and_get_mapped_titles_from_edit_modal(
                expected_asmt, expected_asmt.mapped_objects))
        assert expected_titles == actual_titles
        # 'expected_asmt': updated_at (outdated)
        expected_asmt.update_attrs(updated_at=self.info_service.get_obj(
            obj=expected_asmt).updated_at).repr_ui()
        actual_asmt = asmts_ui_service.get_obj_from_info_page(expected_asmt)
        # 'actual_asmts': audit (None)
        self.general_equal_assert(expected_asmt, actual_asmt, "audit")