Пример #1
0
    def _create_snapshotable_objects():
        """Create original objects that will be snapshotted."""
        text_cad = factories.CustomAttributeDefinitionFactory(
            title="text cad",
            definition_type="market",
        )
        date_cad = factories.CustomAttributeDefinitionFactory(
            title="date cad",
            definition_type="market",
            attribute_type="Date",
        )

        for i in range(5):
            factories.ControlFactory(title="Control {}".format(i + 1))
            factories.OrgGroupFactory()
            market = factories.MarketFactory(title="Market {}".format(i + 1))
            factories.CustomAttributeValueFactory(
                custom_attribute=date_cad,
                attributable=market,
                attribute_value="2016-11-0{}".format(i + 3),
            )
            factories.CustomAttributeValueFactory(
                custom_attribute=text_cad,
                attributable=market,
                attribute_value="2016-11-0{}".format(i + 1),
            )
    def test_total_count_with_ca(self, limit, expected_count):
        """Test total related assessments count for assessments with ca.

    The left outer join in our eager query on custom attribute values breaks
    the total count if on sa.func.count, but works if we use query.count()
    """
        cad = factories.CustomAttributeDefinitionFactory
        cads = [cad(definition_type="assessment") for _ in range(3)]

        for cad in cads:
            factories.CustomAttributeValueFactory(
                attributable=self.assessment1,
                custom_attribute=cad,
            )
            factories.CustomAttributeValueFactory(
                attributable=self.assessment2,
                custom_attribute=cad,
            )

        with mock.patch("ggrc.views.start_compute_attributes"):
            views.do_full_reindex()

        response_json = self._get_related_assessments(self.control,
                                                      **limit).json
        self.assertEqual(response_json["total"], expected_count)
Пример #3
0
    def test_person_ca(self):
        """Control Snapshots are filtered and sorted by Person CA."""
        program = factories.ProgramFactory()
        person1 = factories.PersonFactory(name="Ann",
                                          email="*****@*****.**")
        person2 = factories.PersonFactory(name="Bob",
                                          email="*****@*****.**")
        control1 = factories.ControlFactory()
        control2 = factories.ControlFactory()
        cad = factories.CustomAttributeDefinitionFactory(
            definition_type="control",
            definition_id=None,
            attribute_type="Map:Person",
            title="Global Person CA",
        )
        factories.CustomAttributeValueFactory(attributable=control1,
                                              custom_attribute=cad,
                                              attribute_value="Person",
                                              attribute_object_id=person2.id)
        factories.CustomAttributeValueFactory(attributable=control2,
                                              custom_attribute=cad,
                                              attribute_value="Person",
                                              attribute_object_id=person1.id)
        control1_id = control1.id
        control2_id = control2.id

        factories.RelationshipFactory(source=program, destination=control1)
        factories.RelationshipFactory(source=program, destination=control2)

        self._create_audit(program=program, title="test_person_ca")

        controls_user1 = self._get_first_result_set(
            self._make_snapshot_query_dict(
                "Control", expression=["Global Person CA", "=", "Ann"]),
            "Snapshot",
            "values",
        )
        self.assertSetEqual({c["child_id"]
                             for c in controls_user1}, {control2_id})

        controls_user2 = self._get_first_result_set(
            self._make_snapshot_query_dict(
                "Control",
                expression=["Global Person CA", "=", "*****@*****.**"]),
            "Snapshot",
            "values",
        )
        self.assertSetEqual({c["child_id"]
                             for c in controls_user2}, {control1_id})

        order_by_person_ca_result = self._get_first_result_set(
            self._make_snapshot_query_dict("Control",
                                           order_by=[{
                                               "name": "Global Person CA"
                                           }]), "Snapshot")
        self.assertEqual(order_by_person_ca_result["count"], 2)
        self.assertListEqual(
            [snap["child_id"] for snap in order_by_person_ca_result["values"]],
            [control2_id, control1_id])
Пример #4
0
    def setUp(self):
        super(TestAssessmentNotification, self).setUp()
        self.client.get("/login")
        self.api = api_helper.Api()
        self.auditor = Person.query.filter_by(email="*****@*****.**").one()
        self.api.set_user(self.auditor)
        audit = factories.AuditFactory()
        assignee_acr = all_models.AccessControlRole.query.filter_by(
            object_type="Assessment",
            name="Assignees",
        ).first()

        self.api.post(
            Assessment, {
                "assessment": {
                    "title":
                    "Assessment1",
                    "context":
                    None,
                    "audit": {
                        "id": audit.id,
                        "type": "Audit",
                    },
                    "access_control_list": [
                        acl_helper.get_acl_json(self.primary_role_id,
                                                self.auditor.id),
                        acl_helper.get_acl_json(assignee_acr.id,
                                                self.auditor.id),
                    ],
                    "status":
                    "In Progress",
                }
            })

        self.assessment = Assessment.query.filter_by(title="Assessment1").one()

        self.cad1 = factories.CustomAttributeDefinitionFactory(
            definition_type="assessment",
            title="ca1",
        )
        factories.CustomAttributeValueFactory(custom_attribute=self.cad1,
                                              attributable=self.assessment)

        self.cad3 = factories.CustomAttributeDefinitionFactory(
            definition_type="assessment",
            attribute_type="Checkbox",
            title="ca3",
        )
        factories.CustomAttributeValueFactory(custom_attribute=self.cad3,
                                              attributable=self.assessment)

        db.engine.execute("""
            UPDATE notifications
               SET sent_at = NOW()
        """)
    def test_generation_with_template_ids_given_0(self):
        """
      Test generation of csv file with filtered IDs
      ids of related assessment templates.

      0 - test that only assessment templates with given
      ids are used while gathering local custom attribute
      definitions
    """

        included_template_ids = []

        with factories.single_commit():
            included_template = factories.AssessmentTemplateFactory()
            excluded_template = factories.AssessmentTemplateFactory()

            assessment = factories.AssessmentFactory()
            assessment.audit = included_template.audit

            cad = factories.CustomAttributeDefinitionFactory(
                definition_type="assessment_template",
                title="Included LCAD",
                definition_id=included_template.id,
            )

            included_template_ids.append(included_template.id)

            factories.CustomAttributeValueFactory(
                custom_attribute=cad,
                attributable=assessment,
                attribute_value="Test CAD 0",
            )

            cad = factories.CustomAttributeDefinitionFactory(
                definition_type="assessment_template",
                title="Excluded LCAD",
                definition_id=excluded_template.id)

            factories.CustomAttributeValueFactory(
                custom_attribute=cad,
                attributable=assessment,
                attribute_value="Test CAD 1",
            )

        objects = [{
            "object_name": "Assessment",
            "template_ids": included_template_ids,
        }]

        response = self.export_csv_template(objects)

        self.assertIn('Included LCAD', response.data)
        self.assertNotIn("Excluded LCAD", response.data)
    def test_generation_without_template_ids_given(self):
        """
      Test generation of csv file without filtering by ids
    """

        with factories.single_commit():
            included_template_0 = factories.AssessmentTemplateFactory()
            included_template_1 = factories.AssessmentTemplateFactory()

            assessment = factories.AssessmentFactory()
            assessment.audit = included_template_0.audit

            cad = factories.CustomAttributeDefinitionFactory(
                definition_type="assessment_template",
                title="Excluded LCAD 0",
                definition_id=included_template_0.id,
            )

            factories.CustomAttributeValueFactory(
                custom_attribute=cad,
                attributable=assessment,
                attribute_value="Test CAD 0",
            )

            cad = factories.CustomAttributeDefinitionFactory(
                definition_type="assessment_template",
                title="Excluded LCAD 1",
                definition_id=included_template_1.id)

            factories.CustomAttributeValueFactory(
                custom_attribute=cad,
                attributable=assessment,
                attribute_value="Test CAD 1",
            )

            cad = factories.CustomAttributeDefinitionFactory(
                definition_type="assessment",
                title="Included GCAD",
                definition_id=None)

            factories.CustomAttributeValueFactory(
                custom_attribute=cad,
                attributable=assessment,
                attribute_value="Test CAD 1",
            )

        objects = [{"object_name": "Assessment"}]

        response = self.export_csv_template(objects)

        self.assertIn("Included GCAD", response.data)
        self.assertNotIn("Excluded LCAD 0", response.data)
        self.assertNotIn("Excluded LCAD 1", response.data)
    def test_generation_with_template_ids_given_1(self):
        """
      Test that GCA are not filtered out by template_ids.

      1 - test that global custom attribute definitions
      are not filtered out by template_ids related filter.
    """

        included_template_ids = []

        with factories.single_commit():
            included_template = factories.AssessmentTemplateFactory()

            assessment = factories.AssessmentFactory()
            assessment.audit = included_template.audit

            cad = factories.CustomAttributeDefinitionFactory(
                definition_type="assessment_template",
                title="Included LCAD",
                definition_id=included_template.id,
            )

            included_template_ids.append(included_template.id)

            factories.CustomAttributeValueFactory(
                custom_attribute=cad,
                attributable=assessment,
                attribute_value="Test CAD 0",
            )

            cad = factories.CustomAttributeDefinitionFactory(
                definition_type="assessment",
                title="Included GCAD",
                definition_id=None)

            factories.CustomAttributeValueFactory(
                custom_attribute=cad,
                attributable=assessment,
                attribute_value="Test CAD 1",
            )

        objects = [{
            "object_name": "Assessment",
            "template_ids": included_template_ids,
        }]

        response = self.export_csv_template(objects)

        self.assertIn('Included LCAD', response.data)
        self.assertIn("Included GCAD", response.data)
Пример #8
0
 def test_custom_comment_import(self):
   """Test success import LCA comment for Dropdown CAD"""
   with factories.single_commit():
     cad = factories.CustomAttributeDefinitionFactory(
         attribute_type="Dropdown",
         definition_type="assessment",
         definition_id=self.asmt.id,
         multi_choice_options="comment_required",
         multi_choice_mandatory="1,2,3",
         mandatory=True,
     )
     factories.CustomAttributeValueFactory(
         custom_attribute=cad,
         attributable=self.asmt,
         attribute_value="comment_required",
     )
   self.assertEqual(self.asmt.status, "In Progress")
   response = self.import_data(OrderedDict([
       ("object_type", "LCA Comment"),
       ("description", "test description"),
       ("custom_attribute_definition", cad.id),
   ]))
   self._check_csv_response(response, {})
   response = self.api.put(self.asmt, {
       "status": "Completed",
   })
   self.assertEqual(response.status_code, 200)
   new_comment = Comment.query.first()
   self.assertEqual(new_comment.description, "test description")
   self.assertEqual(new_comment.custom_attribute_definition_id, cad.id)
Пример #9
0
 def test_filter_by_checkbox_cad(self, value, search_value):
   """Test index by Checkdoxed cad."""
   checkbox_type = all_models.CustomAttributeDefinition.ValidTypes.CHECKBOX
   cad_title = "Checkbox"
   with factories.single_commit():
     cad = factories.CustomAttributeDefinitionFactory(
         attribute_type=checkbox_type,
         definition_type="control",
         title=cad_title,
     )
     control = factories.ControlFactory()
     factories.CustomAttributeValueFactory(
         custom_attribute=cad,
         attributable=control,
         attribute_value=value,
     )
   revision = all_models.Revision.query.filter(
       all_models.Revision.resource_id == control.id,
       all_models.Revision.resource_type == control.type,
   ).first()
   revision.content = control.log_json()
   db.session.add(revision)
   with factories.single_commit():
     snapshot = factories.SnapshotFactory(
         child_id=control.id,
         child_type=control.type,
         revision=revision)
   db.session.expire_all()
   do_reindex()
   self.assert_indexed_fields(snapshot, cad_title, {"": search_value})
Пример #10
0
 def test_change_cad_oldstile(self):
   """Test create CAVs proposal in old style."""
   with factories.single_commit():
     control = factories.ControlFactory(title="1")
     cad = factories.CustomAttributeDefinitionFactory(
         definition_type="control")
     factories.CustomAttributeValueFactory(
         custom_attribute=cad,
         attributable=control,
         attribute_value="123")
   control_id = control.id
   cad_id = cad.id
   data = control.log_json()
   data["custom_attributes"] = {cad.id: "321"}
   resp = self.api.post(
       all_models.Proposal,
       {"proposal": {
           "instance": {
               "id": control.id,
               "type": control.type,
           },
           # "content": {"123": 123},
           "full_instance_content": data,
           "agenda": "update cav",
           "context": None,
       }})
   self.assertEqual(201, resp.status_code)
   control = all_models.Control.query.get(control_id)
   self.assertEqual(1, len(control.proposals))
   self.assertIn("custom_attribute_values", control.proposals[0].content)
   self.assertEqual({unicode(cad_id): {"attribute_value": u"321",
                                       "attribute_object": None,
                                       "remove_cav": True}},
                    control.proposals[0].content["custom_attribute_values"])
   self.assertEqual(1, len(control.comments))
Пример #11
0
  def test_checkbox_fulltext(self, value, search_value):
    """Test filter by checkbox value."""

    title = "checkbox"
    checkbox_type = all_models.CustomAttributeDefinition.ValidTypes.CHECKBOX
    with factories.single_commit():
      market = factories.MarketFactory()
      cad = factories.CustomAttributeDefinitionFactory(
          title=title,
          definition_type="market",
          attribute_type=checkbox_type)
      factories.CustomAttributeValueFactory(
          custom_attribute=cad,
          attributable=market,
          attribute_value=value)

    views.do_reindex()

    contents = [
        i.content
        for i in mysql.MysqlRecordProperty.query.filter(
            mysql.MysqlRecordProperty.property == title,
            mysql.MysqlRecordProperty.type == market.type,
            mysql.MysqlRecordProperty.key == market.id,
        )
    ]
    self.assertEqual([search_value], contents)
Пример #12
0
 def test_change_cad(self):
     """Test create proposal with change CAVs."""
     with factories.single_commit():
         control = factories.ControlFactory(title="1")
         cad = factories.CustomAttributeDefinitionFactory(
             definition_type="control")
         factories.CustomAttributeValueFactory(custom_attribute=cad,
                                               attributable=control,
                                               attribute_value="123")
     control_id = control.id
     cad_id = cad.id
     data = control.log_json()
     del data["custom_attributes"]
     data["custom_attribute_values"][0]["attribute_value"] = "321"
     self.create_proposal(control,
                          full_instance_content=data,
                          agenda="update cav",
                          context=None)
     control = all_models.Control.query.get(control_id)
     self.assertEqual(1, len(control.proposals))
     self.assertIn("custom_attribute_values", control.proposals[0].content)
     self.assertEqual(
         {
             unicode(cad_id): {
                 "attribute_value": u"321",
                 "attribute_object": None,
                 "remove_cav": False
             }
         }, control.proposals[0].content["custom_attribute_values"])
     self.assertEqual(1, len(control.comments))
Пример #13
0
    def _create_external_object():
        """Populate external model object that could not be imported."""
        with factories.single_commit():
            objects = [
                factories.ControlFactory(directive=None),
                factories.RiskFactory()
            ]

            ca_definitions = {
                cad.title: cad
                for object in objects
                for cad in object.get_custom_attribute_definitions([
                    "CA text", "CA rich text", "CA date", "CA checkbox",
                    "CA multiselect", "CA dropdown"
                ])
            }
            ca_values = {
                "CA text": "Control ca text",
                "CA rich text": "control<br><br>\nrich text",
                "CA date": "22/02/2022",
                "CA checkbox": "yes",
                "CA multiselect": "yes",
                "CA dropdown": "one"
            }

            for title, value in ca_values.items():
                for obj in objects:
                    factories.CustomAttributeValueFactory(
                        custom_attribute=ca_definitions[title],
                        attributable=obj,
                        attribute_value=value)
Пример #14
0
 def test_revision_cads_ordering(self):
     """Test revisions CADs ordering by id"""
     with factories.single_commit():
         asmnt = factories.AssessmentFactory()
         for i in range(5):
             cad_params = {
                 "title":
                 "test_cad {}".format(5 - i),  # test not sorting by title
                 "definition_type": "assessment",
                 "attribute_type": "Text"
             }
             cad = factories.CustomAttributeDefinitionFactory(**cad_params)
             factories.CustomAttributeValueFactory(
                 custom_attribute=cad,
                 attributable=asmnt,
                 attribute_value="text",
             )
     revisions = ggrc.models.Revision.query.filter(
         ggrc.models.Revision.resource_id == asmnt.id,
         ggrc.models.Revision.resource_type == "Assessment",
     ).order_by(ggrc.models.Revision.id.desc()).all()
     self.assertEqual(6, len(revisions))
     for revision in revisions:
         self.assertIn("custom_attribute_definitions", revision.content)
         self.assertEqual(
             revision.content["custom_attribute_definitions"],
             sorted(revision.content["custom_attribute_definitions"],
                    key=lambda x: x['id']))
Пример #15
0
    def _create_external_object(self):
        """Populate external model object that could not be imported."""
        with factories.single_commit():
            ca_person = factories.PersonFactory(email="*****@*****.**")
            control = factories.ControlFactory(slug="Control code",
                                               directive=None)

            ca_definitions = {
                cad.title: cad
                for cad in control.get_custom_attribute_definitions([
                    "CA text", "CA rich text", "CA date", "CA checkbox",
                    "CA person", "CA dropdown"
                ])
            }
            ca_values = {
                "CA text": "Control ca text",
                "CA rich text": "control<br><br>\nrich text",
                "CA date": "22/02/2022",
                "CA checkbox": "yes",
                "CA person": ca_person,
                "CA dropdown": "one"
            }

            for title, value in ca_values.items():
                factories.CustomAttributeValueFactory(
                    custom_attribute=ca_definitions[title],
                    attributable=control,
                    attribute_value=value)
    def test_cav(self):
        """Test that cav with type "Map:Person" contain attribute_object"""

        with factories.single_commit():
            person = factories.PersonFactory()
            person_id = person.id

            cad = factories.CustomAttributeDefinitionFactory(
                definition_type="assessment",
                definition_id=self.assessment1.id,
                attribute_type="Map:Person")
            cav = factories.CustomAttributeValueFactory(
                custom_attribute=cad,
                attributable=self.assessment1,
                attribute_value="Person")
            cav.attribute_object = person

        response_json = self._get_related_assessments(self.assessment2).json
        data_json = response_json["data"]

        self.assertEqual(len(data_json), 1)

        related_assessment_json = data_json[0]
        cavs_json = related_assessment_json["custom_attribute_values"]

        self.assertEqual(len(cavs_json), 1)

        cav_json = cavs_json[0]

        attribute_object_json = cav_json["attribute_object"]

        self.assertEqual(attribute_object_json, {
            u"type": u"Person",
            u"id": person_id
        })
Пример #17
0
 def test_filter_by_checkbox_cad(self, value, search_value):
   """Test index by Checkdoxed cad {0} value and search_value {1}."""
   checkbox_type = all_models.CustomAttributeDefinition.ValidTypes.CHECKBOX
   cad_title = "Checkbox"
   with factories.single_commit():
     cad = factories.CustomAttributeDefinitionFactory(
         attribute_type=checkbox_type,
         definition_type="objective",
         title=cad_title,
     )
     objective = factories.ObjectiveFactory()
     factories.CustomAttributeValueFactory(
         custom_attribute=cad,
         attributable=objective,
         attribute_value=value,
     )
   revision = all_models.Revision.query.filter(
       all_models.Revision.resource_id == objective.id,
       all_models.Revision.resource_type == objective.type,
   ).first()
   revision.content = objective.log_json()
   db.session.add(revision)
   with factories.single_commit():
     snapshot = factories.SnapshotFactory(
         child_id=objective.id,
         child_type=objective.type,
         revision=revision)
   db.session.expire_all()
   snapshot_id = snapshot.id
   self.client.post("/admin/full_reindex")
   snapshot = all_models.Snapshot.query.get(snapshot_id)
   self.assert_indexed_fields(snapshot, cad_title, {"": search_value})
Пример #18
0
 def test_change_cad(self):
     """Test create proposal with change CAVs."""
     with factories.single_commit():
         program = factories.ProgramFactory(title="1")
         cad = factories.CustomAttributeDefinitionFactory(
             definition_type="program")
         factories.CustomAttributeValueFactory(custom_attribute=cad,
                                               attributable=program,
                                               attribute_value="123")
     program_id = program.id
     cad_id = cad.id
     data = program.log_json()
     data["custom_attribute_values"][0]["attribute_value"] = "321"
     self.create_proposal(program,
                          full_instance_content=data,
                          agenda="update cav",
                          context=None)
     program = all_models.Program.query.get(program_id)
     self.assertEqual(1, len(program.proposals))
     self.assertIn("custom_attribute_values", program.proposals[0].content)
     self.assertEqual(
         {
             unicode(cad_id): {
                 "attribute_value": u"321",
                 "attribute_object": None
             }
         }, program.proposals[0].content["custom_attribute_values"])
     self.assertEqual(1, len(program.comments))
Пример #19
0
    def test_revision_after_del_cad(self, is_add_cav):
        """Test creating new revision after deleting CAD.

    In case of deleting CAD, new revision must be created for object,
    which had this CAD.
    """
        with factories.single_commit():
            control = factories.ControlFactory()

            cad = factories.CustomAttributeDefinitionFactory(
                title="test_name",
                definition_type="control",
            )
            if is_add_cav:
                factories.CustomAttributeValueFactory(
                    custom_attribute=cad,
                    attributable=control,
                    attribute_value="text",
                )

            revision_id = ggrc.models.Revision.query.filter(
                ggrc.models.Revision.resource_id == control.id,
                ggrc.models.Revision.resource_type == control.type,
            ).order_by(ggrc.models.Revision.id.desc()).first().id

        self.api_helper.delete(cad)

        control = ggrc.models.Control.query.first()

        last_revision_id = ggrc.models.Revision.query.filter(
            ggrc.models.Revision.resource_id == control.id,
            ggrc.models.Revision.resource_type == control.type,
        ).order_by(ggrc.models.Revision.id.desc()).first().id

        self.assertGreater(last_revision_id, revision_id)
Пример #20
0
 def test_apply_mapping_cad(self):
     """Test apply mapping CAVs proposal."""
     with factories.single_commit():
         program = factories.ProgramFactory(title="1")
         cad = factories.CustomAttributeDefinitionFactory(
             definition_type="program", attribute_type="Text")
         cav = factories.CustomAttributeValueFactory(
             custom_attribute=cad,
             attributable=program,
             attribute_value="Person",
         )
     self.assertEqual("Person",
                      program.custom_attribute_values[0].attribute_value)
     program_id = program.id
     proposal = factories.ProposalFactory(instance=program,
                                          content={
                                              "custom_attribute_values": {
                                                  cad.id: {
                                                      "attribute_value":
                                                      "Person123",
                                                      "attribute_object":
                                                      None,
                                                  },
                                              },
                                          },
                                          agenda="agenda content")
     with self.number_obj_revisions_for(program):
         self.apply_proposal(proposal)
     program = all_models.Program.query.get(program_id)
     cav = program.custom_attribute_values[0]
     self.assertEqual("Person123", cav.attribute_value)
Пример #21
0
    def test_change_modified_by(self, is_add_cav):
        """Test checked correct changing of modified_by_id field.

    User 1 create control, user 2 delete CAD. After the deleting CAD
    test checking that modified_by field contains user 2.
    """
        with factories.single_commit():
            control = factories.ControlFactory()
            cad = factories.CustomAttributeDefinitionFactory(
                title="test_cad",
                definition_type="control",
                attribute_type="Text",
            )
            control_id = control.id
            if is_add_cav:
                factories.CustomAttributeValueFactory(custom_attribute=cad,
                                                      attributable=control,
                                                      attribute_value="test")

        user = self.gen.generate_person(data={"name": "test_admin"},
                                        user_role="Administrator")[1]
        self.api_helper.set_user(user)
        self.client.get("/login")

        control_revisions = ggrc.models.Revision.query.filter(
            ggrc.models.Revision.resource_id == control_id,
            ggrc.models.Revision.resource_type == "Control",
        ).order_by(ggrc.models.Revision.id.desc()).all()
        ids_before_del = set(revision.id for revision in control_revisions)

        cad = ggrc.models.CustomAttributeDefinition.query.filter_by(
            title="test_cad").first()
        resp_delete = self.api_helper.delete(cad)
        self.assert200(resp_delete)
        cad = ggrc.models.CustomAttributeDefinition.query.filter_by(
            title="test_cad").first()
        self.assertIsNone(cad)

        control_revisions_after = ggrc.models.Revision.query.filter(
            ggrc.models.Revision.resource_id == control_id,
            ggrc.models.Revision.resource_type == "Control",
        ).order_by(ggrc.models.Revision.id.desc()).all()
        ids_after_del = set(revision.id
                            for revision in control_revisions_after)

        difference_revision_id = ids_after_del.difference(ids_before_del)

        last_revision = ggrc.models.Revision.query.filter(
            ggrc.models.Revision.resource_id == control_id,
            ggrc.models.Revision.resource_type == "Control",
        ).order_by(ggrc.models.Revision.id.desc()).first()

        self.assertSetEqual(difference_revision_id, {last_revision.id})

        expected_id = ggrc.models.Person.query.filter_by(
            name="test_admin").first().id

        self.assertEquals(last_revision.content["modified_by_id"], expected_id)
        self.assertEquals(last_revision.content["modified_by"]["id"],
                          expected_id)
Пример #22
0
  def test_audit_clone_custom_attributes(self):
    """Test if custom attributes were copied correctly"""
    audit = factories.AuditFactory()
    ca_def_text = factories.CustomAttributeDefinitionFactory(
        title="test audit CA def 1",
        definition_type="audit",
        attribute_type="Text"
    )
    factories.CustomAttributeValueFactory(
        custom_attribute_id=ca_def_text.id,
        attributable_id=audit.id,
        attributable_type="Audit",
        attribute_value="CA 1 value"
    )

    self.clone_object(audit)

    audit_copy = db.session.query(models.Audit).filter(
        models.Audit.title.like("%copy%")).first()

    self.assertEqual(
        models.CustomAttributeValue.query.filter_by(
            attributable_type="Audit",
            attributable_id=audit_copy.id
        ).count(), 1, "Custom Attribute weren't copied.")
Пример #23
0
 def test_apply_mapping_cad(self):
     """Test apply mapping CAVs proposal."""
     with factories.single_commit():
         risk = factories.RiskFactory(title="1")
         cad = factories.CustomAttributeDefinitionFactory(
             definition_type="risk", attribute_type="Map:Person")
         person = factories.PersonFactory()
         cav = factories.CustomAttributeValueFactory(
             custom_attribute=cad,
             attributable=risk,
             attribute_object_id=person.id,
             attribute_value="Person",
         )
     self.assertEqual(person,
                      risk.custom_attribute_values[0].attribute_object)
     risk_id = risk.id
     proposal = factories.ProposalFactory(instance=risk,
                                          content={
                                              "custom_attribute_values": {
                                                  cad.id: {
                                                      "attribute_value":
                                                      "Person",
                                                      "attribute_object":
                                                      None,
                                                  },
                                              },
                                          },
                                          agenda="agenda content")
     with self.number_obj_revisions_for(risk):
         self.apply_proposal(proposal)
     risk = all_models.Risk.query.get(risk_id)
     cav = risk.custom_attribute_values[0]
     self.assertEqual("Person", cav.attribute_value)
     self.assertIsNone(cav.attribute_object_id)
Пример #24
0
    def setUp(self):
        super(TestProgramVersionHistory, self).setUp()
        self.api = api_helper.Api()

        with factories.single_commit():
            self.program = factories.ProgramFactory(
                title="Test Program",
                description="Program Description",
                slug="PROGRAM-2346",
                start_date=datetime.date(2019, 6, 1),
                end_date=datetime.date(2019, 6, 2),
                updated_at=datetime.date(2019, 6, 2),
                folder="Program Folder",
                notes="Program Notes",
                status="Draft",
            )
            self.cad = factories.CustomAttributeDefinitionFactory(
                title="test cad",
                definition_type="program",
                definition_id=self.program.id,
                attribute_type="Text",
                mandatory=True,
            )
            self.cav = factories.CustomAttributeValueFactory(
                custom_attribute=self.cad,
                attributable=self.program,
                attribute_value="Text",
            )
Пример #25
0
  def _setup_objects():
    """Create and reindex objects needed for tests"""
    text_cad = factories.CustomAttributeDefinitionFactory(
        title="text cad",
        definition_type="market",
    )
    date_cad = factories.CustomAttributeDefinitionFactory(
        title="date cad",
        definition_type="market",
        attribute_type="Date",
    )

    audit = factories.AuditFactory()

    for i in range(5):
      factories.OrgGroupFactory()
      market = factories.MarketFactory()
      factories.CustomAttributeValueFactory(
          custom_attribute=date_cad,
          attributable=market,
          attribute_value="2016-11-0{}".format(i + 3),
      )
      factories.CustomAttributeValueFactory(
          custom_attribute=text_cad,
          attributable=market,
          attribute_value="2016-11-0{}".format(i + 1),
      )

    revisions = models.Revision.query.filter(
        models.Revision.resource_type.in_(["OrgGroup", "Market"]),
        models.Revision.id.in_(
            db.session.query(func.max(models.Revision.id)).group_by(
                models.Revision.resource_type,
                models.Revision.resource_id,
            )
        ),
    )

    for revision in revisions:
      factories.SnapshotFactory(
          child_id=revision.resource_id,
          child_type=revision.resource_type,
          revision=revision,
          parent=audit,
      )
    views.do_reindex()
Пример #26
0
  def setUp(self):
    """Set up for CA export date test cases."""
    super(TestCustomAttributeExportDate, self).setUp()
    self.client.get("/login")

    with factories.single_commit():
      cad1 = factories.CustomAttributeDefinitionFactory(
          title="Test Date",
          definition_type="control",
          attribute_type="Date"
      )
      cad2 = factories.CustomAttributeDefinitionFactory(
          title="Test Invalid Date",
          definition_type="control",
          attribute_type="Date"
      )

      control = factories.ControlFactory()

      factories.CustomAttributeValueFactory(
          attributable=control,
          custom_attribute=cad1,
          attribute_value=u"2018-01-19"
      )

      factories.CustomAttributeValueFactory(
          attributable=control,
          custom_attribute=cad2,
          attribute_value=u"Test Value"
      )

      admin = factories.PersonFactory(email="*****@*****.**", name='test')

      factories.AccessControlPersonFactory(
          ac_list=control.acr_name_acl_map["Admin"],
          person=admin
      )

    self.search_request = [{
        "object_name": "Control",
        "filters": {
            "expression": {},
        },
        "fields": "all"
    }]
Пример #27
0
    def test_export_with_missing_lca_correct_values(self):  # noqa pylint: disable=invalid-name
        """Check correct values in export if assessment lacks some exported LCAs.

    When exporting objects, user can specify list of attributes (local or
    global) that should be present in exported CSV. Export result should have
    CSV columns filled with appropriate values even if exported assessment
    lacks some of specified attributes.
    """
        with factories.single_commit():
            assessment1 = factories.AssessmentFactory()
            factories.CustomAttributeDefinitionFactory(
                title="Test LCAD1",
                definition_type="assessment",
                definition_id=assessment1.id,
                attribute_type="Text",
            )

            assessment2 = factories.AssessmentFactory()
            assessment2_slug = assessment2.slug
            assesmsent2_lca = factories.CustomAttributeDefinitionFactory(
                title="Test LCAD2",
                definition_type="assessment",
                definition_id=assessment2.id,
                attribute_type="Text",
            )
            factories.CustomAttributeValueFactory(
                custom_attribute=assesmsent2_lca,
                attributable=assessment2,
                attribute_value="Test LCAD2 value",
            )
            factories.CustomAttributeDefinitionFactory(
                title="Test GCA",
                definition_type="assessment",
                attribute_type="Text",
            )

        export_query = self._make_query_dict(
            "Assessment",
            expression=[
                "code",
                "=",
                assessment2_slug,
            ],
            fields=[
                'slug',
                '__object_custom__:test lcad1',
                '__object_custom__:test lcad2',
                '__custom__:test gca',
            ])

        response = self.export_parsed_csv([export_query])

        assessment2_data = response["Assessment"][0]
        self.assertEqual(assessment2_data["Code*"], assessment2_slug)
        self.assertNotIn("Test LCAD1", assessment2_data)
        self.assertEqual(assessment2_data["Test LCAD2"], "Test LCAD2 value")
        self.assertEqual(assessment2_data["Test GCA"], "")
 def make_value(self):
     """Generate a custom attribute value."""
     if self.attribute_value is not None:
         value = factories.CustomAttributeValueFactory(
             custom_attribute=self.definition,
             attributable=self.attributable,
             attribute_value=self.attribute_value,
         )
     else:
         value = None
     return value
Пример #29
0
    def test_map_person_type(self):
        """Test CAD Map:Person type has attribute_person_id"""
        with factories.single_commit():
            person = factories.PersonFactory()
            asmt = factories.AssessmentFactory(assessment_type="Control")
            cad_obj = factories.CustomAttributeDefinitionFactory(
                definition_type="assessment",
                definition_id=asmt.id,
                attribute_type="Map:Person",
                title="Person LCA",
            )
            factories.CustomAttributeValueFactory(
                custom_attribute=cad_obj,
                attributable=asmt,
                attribute_value=person.type,
                attribute_object_id=str(person.id),
            )

        data = {"ids": [asmt.id]}
        expected_response = [{
            "attribute": {
                "attribute_type": "Map:Person",
                "title": "Person LCA",
                "default_value": None,
                "multi_choice_options": None,
                "multi_choice_mandatory": None,
                "mandatory": False,
                "placeholder": None,
            },
            "related_assessments": {
                "count":
                1,
                "values": [{
                    "assessments_type":
                    "Control",
                    "assessments": [{
                        "id": asmt.id,
                        "attribute_definition_id": cad_obj.id,
                        "slug": asmt.slug,
                    }],
                }],
            },
            "assessments_with_values": [{
                "id": asmt.id,
                "title": asmt.title,
                "attribute_value": "Person",
                "attribute_person_id": person.id
            }]
        }]
        response = self.client.post(self.ENDPOINT_URL,
                                    data=json.dumps(data),
                                    headers=self.headers)
        self.assert200(response)
        self.assertEqual(expected_response, response.json)
 def test_cad_service_import(self):
     """Test double insert by /_service/import_csv"""
     cav = factories.CustomAttributeValueFactory(
         custom_attribute=self.cad,
         attributable=self.asmt,
         attribute_value="Text",
     )
     response = self.import_data(
         OrderedDict([("object_type", "Assessment"),
                      ("Code", self.asmt.slug),
                      (self.cad.title, cav.attribute_value)]))
     self.assertItemsEqual(response[0]['row_errors'], [])