Beispiel #1
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])
Beispiel #2
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()
Beispiel #3
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"
    }]
Beispiel #4
0
    def test_asmnt_cads_update_completed(self):
        """Test update of completed assessment with local and global cads."""
        global_cad_name = "Global CAD fox sox"
        local_cad_name = "Local CAD for sox"
        exp_errors = {
            'Assessment': {
                'row_warnings': {
                    "Line 3: The system is in a read-only mode and "
                    "is dedicated for SOX needs. The following "
                    "columns will be ignored: {}.".format(global_cad_name),
                    "Line 3: The system is in a read-only mode and "
                    "is dedicated for SOX needs. The following "
                    "columns will be ignored: {}.".format(local_cad_name),
                },
            }
        }
        with factories.single_commit():
            user = self.generate_person()
            person_id = user.id
            asmnt = factories.AssessmentFactory(sox_302_enabled=True,
                                                status="Completed")
            self.assign_person(asmnt, "Assignees", user.id)
            assmnt_slug = asmnt.slug
            factories.CustomAttributeDefinitionFactory(
                title=local_cad_name,
                definition_type="assessment",
                definition_id=asmnt.id,
                attribute_type="Text",
            )
            factories.CustomAttributeDefinitionFactory(
                title=global_cad_name,
                definition_type="assessment",
                attribute_type="Text",
            )

        self.set_current_person(user)
        response = self.import_data(
            collections.OrderedDict([
                ("object_type", "Assessment"),
                ("Code*", assmnt_slug),
                (global_cad_name, "Some value 1"),
                (local_cad_name, "Some value 2"),
            ]),
            person=all_models.Person.query.get(person_id))
        self._check_csv_response(response, exp_errors)
Beispiel #5
0
  def test_setting_ca_values(self):
    """Test normal setting of custom attribute values."""
    with factories.single_commit():
      prog = factories.ProgramFactory()
      cad1 = factories.CustomAttributeDefinitionFactory(
          definition_type="program", title="CA 1", )
      cad2 = factories.CustomAttributeDefinitionFactory(
          definition_type="program", title="CA 2", )

    prog = prog.__class__.query.get(prog.id)

    val1 = models.CustomAttributeValue(
        attribute_value="55",
        custom_attribute=cad1,
    )
    val2 = models.CustomAttributeValue(
        attribute_value="129aaaaaa",
        custom_attribute=cad2,
    )

    prog.custom_attribute_values = [val1, val1, val1]
    db.session.commit()
    prog = prog.__class__.query.get(prog.id)
    self.assertEqual(len(prog.custom_attribute_values), 1)

    prog = factories.ProgramFactory()
    prog.custom_attribute_values.append(val1)
    db.session.commit()
    prog = prog.__class__.query.get(prog.id)
    self.assertEqual(len(prog.custom_attribute_values), 1)
    self.assertEqual(
        {"55"},
        set(v.attribute_value for v in prog.custom_attribute_values),
    )

    prog = factories.ProgramFactory()
    prog.custom_attribute_values = [val1, val2]
    db.session.commit()
    prog = prog.__class__.query.get(prog.id)

    self.assertEqual(
        {"55", "129aaaaaa"},
        set(v.attribute_value for v in prog.custom_attribute_values),
    )
    self.assertEqual(len(prog.custom_attribute_values), 2)
Beispiel #6
0
  def test_validate_rich_text_ca(self):
    """Test validator for Rich Text CA value."""
    generator = ObjectGenerator()
    with factories.single_commit():
      prog = factories.ProgramFactory()
      cad1 = factories.CustomAttributeDefinitionFactory(
          definition_type="program",
          definition_id=prog.id,
          attribute_type="Rich Text",
          title="CA 1",
      )
      cad2 = factories.CustomAttributeDefinitionFactory(
          definition_type="program",
          definition_id=prog.id,
          attribute_type="Rich Text",
          title="CA 2",
      )

    generator.api.modify_object(
        prog,
        {
            "custom_attribute_values": [
                {
                    "attribute_value": " http://www.some.url",
                    "attributable_id": prog.id,
                    "attributable_type": "program",
                    "custom_attribute_id": cad1.id,
                },
                {
                    "attribute_value": "<a>http://www.some.url</a>",
                    "attributable_id": prog.id,
                    "attributable_type": "program",
                    "custom_attribute_id": cad2.id,
                }
            ],
        },
    )

    prog = prog.__class__.query.get(prog.id)
    self.assertEqual(prog.custom_attribute_values[0].attribute_value,
                     (' <a href="http://www.some.url">'
                      'http://www.some.url</a>'))
    self.assertEqual(prog.custom_attribute_values[1].attribute_value,
                     '<a>http://www.some.url</a>')
Beispiel #7
0
    def test_adding_mapping_ca_dict(self):
        """Test adding mapping custom attribute values with a dict."""
        with factories.single_commit():
            person = factories.PersonFactory()
            prog = factories.ProgramFactory()
            cad1 = factories.CustomAttributeDefinitionFactory(
                definition_type="program",
                definition_id=prog.id,
                attribute_type="Map:Person",
                title="CA 1",
            )
            cad2 = factories.CustomAttributeDefinitionFactory(
                definition_type="program",
                definition_id=prog.id,
                attribute_type="Map:Person",
                title="CA 2",
            )
            person = factories.PersonFactory()
            prog = factories.ProgramFactory()

        prog.custom_attribute_values = [{
            "attribute_value":
            "Person:%s" % person.id,
            "custom_attribute_id":
            cad1.id,
        }, {
            "attribute_value": "Person",
            "attribute_object_id": str(person.id),
            "custom_attribute_id": cad2.id,
        }]
        prog.validate_custom_attributes()
        prog = prog.__class__.query.get(prog.id)

        self.assertEqual(
            {str(person.id)},
            set(v.attribute_object_id for v in prog.custom_attribute_values),
        )
        self.assertEqual(
            {"Person"},
            set(v.attribute_value for v in prog.custom_attribute_values),
        )
        self.assertEqual(len(prog.custom_attribute_values), 2)
Beispiel #8
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)
Beispiel #9
0
 def _create_cas():
     """Create custom attribute definitions."""
     for type_ in ["facility", "control", "market", "section"]:
         with app.app_context():
             factories.CustomAttributeDefinitionFactory(
                 title="CA dropdown",
                 definition_type=type_,
                 attribute_type="Dropdown",
                 multi_choice_options="one,two,three,four,five",
             )
             factories.CustomAttributeDefinitionFactory(
                 title="CA text",
                 definition_type=type_,
                 attribute_type="Text",
             )
             factories.CustomAttributeDefinitionFactory(
                 title="CA date",
                 definition_type=type_,
                 attribute_type="Date",
             )
 def test_global_ca_admin_add_not_change_status(self, from_status):
     """Assessment in '{0}' NOT changed when adding 'global custom attribute'"""
     with factories.single_commit():
         assessment = factories.AssessmentFactory(status=from_status)
         factories.CustomAttributeDefinitionFactory(
             definition_type='assessment',
             attribute_type='Rich Text',
             title='rich_test_gca',
             multi_choice_options='')
     assessment = self.refresh_object(assessment)
     self.assertEqual(from_status, assessment.status)
Beispiel #11
0
    def test_ca_order(self):
        """Test LCA/GCA order in Assessment"""
        template = factories.AssessmentTemplateFactory(
            test_plan_procedure=False,
            procedure_description="Assessment Template Test Plan")

        custom_attribute_definitions = [
            # Global CAs
            {
                "definition_type": "assessment",
                "title": "rich_test_gca",
                "attribute_type": "Rich Text",
                "multi_choice_options": ""
            },
            {
                "definition_type": "assessment",
                "title": "checkbox1_gca",
                "attribute_type": "Checkbox",
                "multi_choice_options": "test checkbox label"
            },
            # Local CAs
            {
                "definition_type": "assessment_template",
                "definition_id": template.id,
                "title": "test text field",
                "attribute_type": "Text",
                "multi_choice_options": ""
            },
            {
                "definition_type": "assessment_template",
                "definition_id": template.id,
                "title": "test RTF",
                "attribute_type": "Rich Text",
                "multi_choice_options": ""
            },
            {
                "definition_type": "assessment_template",
                "definition_id": template.id,
                "title": "test checkbox",
                "attribute_type": "Checkbox",
                "multi_choice_options": "test checkbox label"
            },
        ]

        for attribute in custom_attribute_definitions:
            factories.CustomAttributeDefinitionFactory(**attribute)
        response = self.assessment_post(template)
        self.assertListEqual([
            u'test text field', u'test RTF', u'test checkbox',
            u'rich_test_gca', u'checkbox1_gca'
        ], [
            cad['title'] for cad in response.json["assessment"]
            ["custom_attribute_definitions"]
        ])
Beispiel #12
0
 def _generate_cad():
   """Generate custom attribute definitions."""
   factories.CustomAttributeDefinitionFactory(
       title="CA dropdown",
       definition_type="program",
       multi_choice_options="one,two,three,four,five",
   )
   factories.CustomAttributeDefinitionFactory(
       title="CA text",
       definition_type="program",
   )
   factories.CustomAttributeDefinitionFactory(
       title="CA date",
       definition_type="program",
       attribute_type="Date",
   )
   factories.CustomAttributeDefinitionFactory(
       title="CA person",
       definition_type="program",
       attribute_type="Map:Person",
   )
 def _generate_cad(self):
   """Generate custom attribute definitions."""
   factories.CustomAttributeDefinitionFactory(
       title="CA dropdown",
       definition_type="program",
       multi_choice_options="one,two,three,four,five",
   )
   factories.CustomAttributeDefinitionFactory(
       title="CA text",
       definition_type="program",
   )
   factories.CustomAttributeDefinitionFactory(
       title="CA date",
       definition_type="program",
       attribute_type="Date",
   )
   factories.CustomAttributeDefinitionFactory(
       title="CA person",
       definition_type="program",
       attribute_type="Map:Person",
   )
   # local CADs for the Assessments
   for title in ["Date or arbitrary text", "Date or text styled as date"]:
     factories.CustomAttributeDefinitionFactory(
         title=title,
         definition_type="assessment",
         definition_id=self._assessment_with_date.id,
         attribute_type="Date",
     )
     factories.CustomAttributeDefinitionFactory(
         title=title,
         definition_type="assessment",
         definition_id=self._assessment_with_text.id,
         attribute_type="Text",
     )
Beispiel #14
0
 def test_multiselect_cad(self):
     """Test for the multiselect CADs"""
     with factories.single_commit():
         asmt = factories.AssessmentFactory(assessment_type="Control")
         cad_obj = factories.CustomAttributeDefinitionFactory(
             title="multiselect_LCA",
             definition_type="assessment",
             definition_id=asmt.id,
             attribute_type="Multiselect",
             multi_choice_options="1,2,3",
             mandatory=True)
         factories.CustomAttributeValueFactory(
             custom_attribute=cad_obj,
             attributable=asmt,
             attribute_value="1,2",
         )
     data = {"ids": [asmt.id]}
     expected_response = [{
         "attribute": {
             "attribute_type": "Multiselect",
             "title": "multiselect_LCA",
             "default_value": "",
             "multi_choice_options": "1,2,3",
             "multi_choice_mandatory": None,
             "mandatory": True,
             "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": "1,2",
             "attribute_person_id": None,
         }]
     }]
     response = self.client.post(self.ENDPOINT_URL,
                                 data=json.dumps(data),
                                 headers=self.headers)
     self.assert200(response)
     self.assertEqual(expected_response, response.json)
Beispiel #15
0
  def test_latest_revision_delete_cad(self, is_add_cav):
    """Test creating new revision after deleting CAD.

    In case of deleting CAD, snapshot attribute is_latest_revision
    must be False
    """
    with factories.single_commit():
      control = factories.ControlFactory()
      program = factories.ProgramFactory()
      factories.RelationshipFactory(
          source=program,
          destination=control,
      )

      audit = factories.AuditFactory()

      factories.RelationshipFactory(
          source=audit,
          destination=control
      )
      cad = factories.CustomAttributeDefinitionFactory(
          title="test_name",
          definition_type="control",
          attribute_type="Text",
      )

      if is_add_cav:
        factories.CustomAttributeValueFactory(
            custom_attribute=cad,
            attributable=control,
            attribute_value="test",
        )

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

      snapshot = factories.SnapshotFactory(
          parent=audit,
          child_id=control.id,
          child_type=control.type,
          revision=last_revision,
      )

    self.assertTrue(snapshot.is_latest_revision)

    self.api_helper.delete(cad)

    snapshot = models.Snapshot.query.filter().first()

    self.assertEqual(snapshot.is_latest_revision, False)
  def test_assmt_with_multiselect_gca(self):
    """Import of assessment with multiselect CAD shouldn't add assmt.CAV"""
    assess_slug = "TestAssessment"
    with factories.single_commit():
      # create 2 GCA's
      cad_text = factories.CustomAttributeDefinitionFactory(
          title="text_GCA",
          definition_type="assessment",
          attribute_type="Text",
      )
      factories.CustomAttributeDefinitionFactory(
          title="multiselect_GCA",
          definition_type="assessment",
          attribute_type="Multiselect",
          multi_choice_options="1,2,3"
      )

      # create assessment with 1 CAV
      assessment = factories.AssessmentFactory(
          slug=assess_slug,
      )
      factories.CustomAttributeValueFactory(
          custom_attribute=cad_text,
          attributable=assessment,
          attribute_value="text",
      )
      assessment_id = assessment.id
    # update given assessment with empty GCA multiselect type
    response = self.import_data(OrderedDict([
        ("object_type", "Assessment"),
        ("Code", assess_slug),
        ("multiselect_GCA", ""),
    ]))
    self._check_csv_response(response, {})
    assessment = all_models.Assessment.query.get(assessment_id)
    self.assertEquals(1, len(assessment.custom_attribute_values))
    self.assertEquals(
        "text", assessment.custom_attribute_values[0].attribute_value
    )
 def make_definition(self):
     """Generate a custom attribute definition."""
     definition = factories.CustomAttributeDefinitionFactory(
         attribute_type=self.attribute_type,
         definition_type=self.attributable.__class__.__name__,
         definition_id=None if self.global_ else self.attributable.id,
         mandatory=self.mandatory,
         multi_choice_options=(self.dropdown_parameters[0]
                               if self.dropdown_parameters else None),
         multi_choice_mandatory=(self.dropdown_parameters[1]
                                 if self.dropdown_parameters else None),
     )
     return definition
Beispiel #18
0
    def test_custom_comment_value(self):
        """Test add custom attribute value comment action."""
        assessment = factories.AssessmentFactory()
        ca_def_title = "def1"
        ca_def = factories.CustomAttributeDefinitionFactory(
            title=ca_def_title,
            definition_type="assessment",
            definition_id=assessment.id,
            attribute_type="Dropdown",
            multi_choice_options="no,yes",
            multi_choice_mandatory="0,3")
        ca_val = factories.CustomAttributeValueFactory(custom_attribute=ca_def,
                                                       attributable=assessment,
                                                       attribute_value="no")
        response = self.api.put(
            assessment, {
                "custom_attribute_values": [{
                    "id": ca_val.id,
                    "custom_attribute_id": ca_def.id,
                    "attribute_value": "yes",
                    "type": "CustomAttributeValue",
                }],
                "actions": {
                    "add_related":
                    [{
                        "id": None,
                        "type": "Comment",
                        "description": "comment1",
                        "custom_attribute_definition_id": ca_def.id,
                    }]
                }
            })
        self.assert200(response)

        relationship = _get_relationship("Assessment", assessment.id)
        self.assertIsNotNone(relationship)

        comment = all_models.Comment.query.get(relationship.destination_id)
        comment.custom_attribute_revision_upd({
            "custom_attribute_revision_upd": {
                "custom_attribute_value": {
                    "id": ca_val.id,
                },
            },
        })
        comment_json = comment.log_json()
        self.assertTrue("custom_attribute_revision" in comment_json.keys())
        self.assertEqual(
            comment_json["custom_attribute_revision"]['custom_attribute']
            ['title'], ca_def_title)
Beispiel #19
0
 def test_custom_attr_cb(self, model):
   """Test if  custom attribute checkbox type has hint for {}."""
   with factories.single_commit():
     factories.CustomAttributeDefinitionFactory(
         definition_type=model.lower(),
         attribute_type="Checkbox",
     )
   data = {
       "export_to": "csv",
       "objects": [{"object_name": model, "fields": "all"}]
   }
   response = self.client.post("/_service/export_csv",
                               data=dumps(data), headers=self.headers)
   self.assertIn("Allowed values are:\nyes\nno", response.data)
Beispiel #20
0
 def test_needs_verification_assessment(self):
     """Test assessment needs verification"""
     with factories.single_commit():
         asmt = factories.AssessmentFactory()
         asmt.add_person_with_role_name(factories.PersonFactory(),
                                        "Verifiers")
         cad_text = factories.CustomAttributeDefinitionFactory(
             title="test_LCA",
             definition_type="assessment",
             definition_id=asmt.id,
             attribute_type="Text",
         )
     data = {
         "assessments_ids": [asmt.id],
         "attributes": [{
             "attribute_value":
             "cav_value",
             "attribute_title":
             cad_text.title,
             "attribute_type":
             "Text",
             "extra": {
                 "comment": {},
                 "urls": [],
                 "files": [],
             },
             "bulk_update": [
                 {
                     "assessment_id": asmt.id,
                     "attribute_definition_id": cad_text.id,
                     "slug": asmt.slug,
                 },
             ]
         }]
     }
     builder = csvbuilder.CsvBuilder(data)
     expected_data = {
         asmt.id: {
             "files": [],
             "urls": [],
             "cavs": {
                 "test_LCA": "cav_value"
             },
             "slug": asmt.slug,
             "verification": True,
             "comments": []
         }
     }
     self.assert_assessments(builder, expected_data)
     self.assertEqual(builder.assessment_ids, [asmt.id])
Beispiel #21
0
 def _prepare_mandatory_evidence_cad(self):
     """Prepare mandatory evidence"""
     cad = factories.CustomAttributeDefinitionFactory(
         attribute_type="Dropdown",
         definition_type="assessment",
         definition_id=self.asmt.id,
         multi_choice_options="value_1,value_2",
         multi_choice_mandatory="0,2",
     )
     factories.CustomAttributeValueFactory(
         custom_attribute=cad,
         attributable=self.asmt,
         attribute_value="value_2",
     )
Beispiel #22
0
 def test_cad_title_strip(self, title, validated_title):
     """Test CAD title strip on validation."""
     with factories.single_commit():
         cad = factories.CustomAttributeDefinitionFactory(
             definition_type="control",
             attribute_type=all_models.CustomAttributeDefinition.ValidTypes.
             TEXT,
             title=title,
         )
     cad_resp = self.generator.api.get(cad, cad.id)
     self.assert200(cad_resp)
     self.assertEquals(
         cad_resp.json['custom_attribute_definition']['title'],
         validated_title)
Beispiel #23
0
  def test_evidences_mapped(self, _, get_gdrive_link, process_gdrive_mock):
    """Test files were mapped to assessments and completed successfully"""
    process_gdrive_mock.return_value = {
        "id": "mock_id",
        "webViewLink": "test_mock_link",
        "name": "mock_name",
    }
    get_gdrive_link.return_value = "mock_id"
    assmts = []
    assmts_ids = []
    with factories.single_commit():
      for _ in range(2):
        assmt = factories.AssessmentFactory(status="Not Started")
        factories.CustomAttributeDefinitionFactory(
            definition_id=assmt.id,
            title="lca_title",
            definition_type="assessment",
            attribute_type="Dropdown",
            multi_choice_options="one,two",
            multi_choice_mandatory="2,2",
        )
        assmts.append(assmt)
        assmts_ids.append(assmt.id)

    bulk_update = [{"assessment_id": asmt.id,
                    "attribute_definition_id": None,
                    "slug": asmt.slug} for asmt in assmts]
    data = {
        "assessments_ids": assmts_ids,
        "attributes": [{
            "attribute_value": "one",
            "attribute_title": "lca_title",
            "attribute_type": "Dropdown",
            "extra": {"comment": None,
                      "urls": [],
                      "files": [{"source_gdrive_id": "mock_id"}]},
            "bulk_update": bulk_update,
        }],
    }

    response = self.client.post("/api/bulk_operations/complete",
                                data=json.dumps(data),
                                headers=self.headers)
    self.assert200(response)
    assmts = models.Assessment.query.all()
    for assmt in assmts:
      urls = {ev_file.gdrive_id for ev_file in assmt.evidences_file}
      self.assertEqual(urls, {u"mock_id"})
      self.assertEqual(assmt.status, "Completed")
Beispiel #24
0
  def _create_int_and_ext_cads(custom_attributable):
    """Create internal and external CAD differing in title case.

    Args:
      custom_attributable (db.Model): Instance of custom attributable model
        for which internal and external CADs should be created.
    """
    factories.CustomAttributeDefinitionFactory(
        definition_type=custom_attributable._inflector.table_singular,
        title="custom attribute",
    )
    factories.ExternalCustomAttributeDefinitionFactory(
        definition_type=custom_attributable._inflector.table_singular,
        title="custom attribute".title(),
    )
 def setUp(self):
     """Set up audit and cad for test cases."""
     super(TestAssessmentComplete, self).setUp()
     self.api = ggrc.api_helper.Api()
     with factories.single_commit():
         self.audit = factories.AuditFactory()
         self.asmt = factories.AssessmentFactory(audit=self.audit,
                                                 status="In Progress")
         self.cad = factories.CustomAttributeDefinitionFactory(
             title="test cad",
             definition_type="assessment",
             definition_id=self.asmt.id,
             attribute_type="Text",
             mandatory=True,
         )
Beispiel #26
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",
    )
    person_cad = factories.CustomAttributeDefinitionFactory(
        title="CA person",
        definition_type="market",
        attribute_type="Map:Person",
    )

    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),
      )
      factories.CustomAttributeValueFactory(
          custom_attribute=person_cad,
          attributable=market,
          attribute_value="user{}@example.com".format(i + 1),
      )
Beispiel #27
0
    def test_attributes_failed(self):
        """Test notification if bulk couldn't fill attributes"""
        assessments = []
        with factories.single_commit():
            for _ in range(3):
                assessment = factories.AssessmentFactory()
                assessments.append(assessment)
                factories.CustomAttributeDefinitionFactory(
                    definition_type="assessment",
                    definition_id=assessment.id,
                    attribute_type="Dropdown",
                    title="lca_title",
                )
            assessments_ids = [assmt.id for assmt in assessments]
            assessments_titles = [assmt.title for assmt in assessments]

        bulk_update = [{
            "assessment_id": assmt.id,
            "attribute_definition_id": None,
            "slug": assmt.slug
        } for assmt in assessments]
        data = {
            "assessments_ids":
            assessments_ids,
            "attributes": [{
                "attribute_value": "lcavalue",
                "attribute_title": "lca_title",
                "attribute_type": "Dropdown",
                "extra": None,
                "bulk_update": bulk_update
            }],
        }
        with mock.patch("ggrc.notifications.common.send_email") as send_mock:
            response = self.client.post("/api/bulk_operations/complete",
                                        data=json.dumps(data),
                                        headers=self.headers)
        self.assert200(response)
        send_mock.assert_called_once()
        _, mail_title, body = send_mock.call_args[0]
        self.assertEqual(mail_title, "Bulk update of Assessments is finished")
        self.assertNotIn("Bulk Assesments update is finished successfully",
                         body)
        self.assertNotIn("Bulk Assesments update is finished partitially",
                         body)
        self.assertIn("Bulk Assesments update has failed", body)
        for asmt_title in assessments_titles:
            self.assertIn(asmt_title, body)
Beispiel #28
0
 def _create_cas(self):
   """Create custom attribute definitions."""
   self._ca_objects = {}
   external_ca_model_names = [
       "control",
   ]
   ca_model_names = [
       "facility",
       "market",
       "requirement",
       "threat",
       "access_group",
       "data_asset"
   ]
   external_ca_args = [
       {"title": "CA text", "attribute_type": "Text"},
       {"title": "CA rich text", "attribute_type": "Rich Text"},
       {"title": "CA date", "attribute_type": "Date"},
       {"title": "CA multiselect", "attribute_type": "Multiselect",
        "multi_choice_options": "yes,no"},
       {"title": "CA dropdown", "attribute_type": "Dropdown",
        "multi_choice_options": "one,two,three,four,five"},
   ]
   ca_args = [
       {"title": "CA text", "attribute_type": "Text"},
       {"title": "CA rich text", "attribute_type": "Rich Text"},
       {"title": "CA date", "attribute_type": "Date"},
       {"title": "CA checkbox", "attribute_type": "Checkbox"},
       {"title": "CA multiselect", "attribute_type": "Multiselect",
        "multi_choice_options": "yes,no"},
       {"title": "CA dropdown", "attribute_type": "Dropdown",
        "multi_choice_options": "one,two,three,four,five"},
   ]
   for type_ in ca_model_names:
     with app.app_context():
       for args in ca_args:
         factories.CustomAttributeDefinitionFactory(
             definition_type=type_,
             **args
         )
   for type_ in external_ca_model_names:
     with app.app_context():
       for args in external_ca_args:
         factories.ExternalCustomAttributeDefinitionFactory(
             definition_type=type_,
             **args
         )
Beispiel #29
0
  def test_attributes_select_values(self, attribute_type, options,
                                    value, expected_value):
    """Test complete asmts select cavs with attribute_type {0}."""
    # pylint: disable=too-many-locals
    asmts = []
    asmts_ids = []
    cads_ids = []
    with factories.single_commit():
      for _ in range(2):
        assmt = factories.AssessmentFactory(status="Not Started")
        cad = factories.CustomAttributeDefinitionFactory(
            definition_id=assmt.id,
            title="test_lca",
            definition_type="assessment",
            attribute_type=attribute_type,
            multi_choice_options=options,
        )
        asmts.append(assmt)
        asmts_ids.append(assmt.id)
        cads_ids.append(cad.id)

    bulk_update = [{
        "assessment_id": asmt.id,
        "attribute_definition_id": cad_id,
        "slug": asmt.slug} for cad_id, asmt in zip(cads_ids, asmts)]
    data = {
        "assessments_ids": asmts_ids,
        "attributes": [{
            "attribute_value": value,
            "attribute_title": "test_lca",
            "attribute_type": attribute_type,
            "extra": {},
            "bulk_update": bulk_update,
        }],
    }
    response = self.client.post("/api/bulk_operations/complete",
                                data=json.dumps(data),
                                headers=self.headers)
    self.assert200(response)
    asmts = models.Assessment.query.all()
    cavs = models.CustomAttributeValue.query.filter(
        models.CustomAttributeValue.custom_attribute_id.in_(cads_ids)
    ).all()
    for asmt in asmts:
      self.assertEqual(asmt.status, "Completed")
    for cav in cavs:
      self.assertEqual(cav.attribute_value, expected_value)
 def test_get_mandatory_cads(self, mandatory):
     """CAD and mandatory meta info if mandatory flag is {0}."""
     control_id = self.control.id
     cad = factories.CustomAttributeDefinitionFactory(
         title="test_name", definition_type="control", mandatory=mandatory)
     cad_id = cad.id
     resp = self.api.client.get(
         "/api/revisions"
         "?resource_type=Control&resource_id={}".format(control_id))
     collection = resp.json["revisions_collection"]["revisions"]
     self.assertTrue(collection)
     self.assertIn("meta", collection[0])
     self.assertIn("mandatory", collection[0]["meta"])
     mandatory_meta = collection[0]["meta"]["mandatory"]
     self.assertIn("custom_attribute_definitions", mandatory_meta)
     mandatory_cads = mandatory_meta["custom_attribute_definitions"]
     self.assertEqual(mandatory, cad_id in mandatory_cads)