def test_import_verification_flag(self, flag, import_value): """Create wf with need verification flag.""" person = factories.PersonFactory(email="*****@*****.**") slug = "SomeCode" resp = self.import_data( collections.OrderedDict([ ("object_type", "Workflow"), ("code", slug), ("title", "SomeTitle"), ("Need Verification", import_value), ("force real-time email updates", "no"), ("Admin", person.email), ])) self.assertEqual(1, resp[0]['created']) workflow = Workflow.query.filter(Workflow.slug == slug).first() self.assertEqual(flag, workflow.is_verification_needed)
def test_put_acl_null_evidence(self, kind): """Test put acl null of evidence data assessment status changed""" expected_status = models.Assessment.PROGRESS_STATE with factories.single_commit(): evidence = factories.EvidenceFactory(kind=kind) factories.RelationshipFactory(destination=self.assessment, source=evidence) person = factories.PersonFactory() role = models.AccessControlRole.query.filter( models.AccessControlRole.object_type == "Evidence", models.AccessControlRole.name == 'Admin', ).one() evidence.add_person_with_role(person, role) self.api.put(evidence, {"access_control_list": []}) assessment = self.refresh_object(self.assessment, self.assessment_id) self.assertEqual(assessment.status, expected_status)
def setup_person_task_event(end_date): """Setup task with person and event.""" with factories.single_commit(): person = factories.PersonFactory() task = wf_factories.CycleTaskGroupObjectTaskFactory( end_date=end_date, ) event = factories.CalendarEventFactory( due_date=end_date, attendee_id=person.id, ) # pylint: disable=protected-access for acl in task._access_control_list: factories.AccessControlPersonFactory(ac_list=acl, person=person) factories.RelationshipFactory(source=task, destination=event) return person, task, event
def test_reviewer_notification_on_create_review(self, _): """Reviewer should receive email notification""" reviewer = factories.PersonFactory() reviewer_role_id = all_models.AccessControlRole.query.filter_by( name="Reviewer", object_type="Review", ).one().id control = factories.ControlFactory() email_message = "email email_message" self.generator.generate_object( all_models.Review, { "reviewable": { "type": control.type, "id": control.id, }, "context": None, "notification_type": all_models.Review.NotificationTypes.EMAIL_TYPE, "status": all_models.Review.STATES.UNREVIEWED, "email_message": email_message, "access_control_list": [{ "ac_role_id": reviewer_role_id, "person": { "id": reviewer.id }, }], }, ) with mock.patch.object( fast_digest.DIGEST_TMPL, "render" ) as bodybuilder_mock: fast_digest.send_notification() template_args = bodybuilder_mock.call_args[1] self.assertListEqual([], template_args["proposals"]) self.assertListEqual([], template_args["review_owners"]) self.assertEqual(1, len(template_args["review_reviewers"])) self.assertEqual( control.id, template_args["review_reviewers"][0].reviewable.id ) self.assertEqual( email_message, template_args["review_reviewers"][0].email_message )
def test_acl_filter(self, test_role_name): """Control Snapshots are filtered and sorted by ACL Role.""" with factories.single_commit(): program = factories.ProgramFactory() person1 = factories.PersonFactory(name="Ann", email="*****@*****.**") control1 = factories.ControlFactory() control2 = factories.ControlFactory() program_id = program.id control1_id = control1.id control2_id = control2.id factories.RelationshipFactory(source=program, destination=control1) factories.RelationshipFactory(source=program, destination=control2) factories.AccessControlListFactory( ac_role=factories.AccessControlRoleFactory( name=test_role_name, object_type="Control" ), person=person1, object_id=control1_id, object_type="Control", ) revision = all_models.Revision.query.filter( all_models.Revision.resource_type == "Control", all_models.Revision.resource_id == control1_id ).order_by(all_models.Revision.updated_at.desc()).first() revision.content = control1.log_json() db.session.add(revision) db.session.commit() program = models.Program.query.filter_by(id=program_id).one() self._create_audit(program=program, title="some title") control_user1_result = self._get_first_result_set( self._make_snapshot_query_dict( "Control", expression=['{}'.format(test_role_name), "=", "Ann"] ), "Snapshot", ) self.assertEqual(control_user1_result["count"], 1) snaps_dict = dict( all_models.Snapshot.query.filter( all_models.Snapshot.child_type == "Control" ).values("child_id", "id") ) self.assertIn(snaps_dict[control1_id], [i["id"] for i in control_user1_result["values"]]) self.assertNotIn(snaps_dict[control2_id], [i["id"] for i in control_user1_result["values"]])
def test_profile_put_corrupted_data(self, data): """Test person_profiles PUT method fails via incorrect request data If request doesn't have "last_seen_whats_new" key or date is incorrect, response is code 400 "Bad Request" """ with factories.single_commit(): user = factories.PersonFactory() self._create_users_names_rbac([user]) self.api.set_user(person=user) response = self.api.client.put("/api/people/{}/profile".format(user.id), content_type='application/json', data=json.dumps(data), headers=[('X-Requested-By', 'Tests')]) # missed key in request self.assert400(response)
def test_profile_put_successful(self, new_date, expected_date): """Test person_profile PUT method for setting data and correct response""" with factories.single_commit(): user = factories.PersonFactory() self._create_users_names_rbac([user]) self.api.set_user(person=user) data = {"last_seen_whats_new": new_date} correct_response = {"Person": {"id": user.id, "profile": data}} response = self.api.client.put("/api/people/{}/profile".format(user.id), content_type='application/json', data=json.dumps(data), headers=[('X-Requested-By', 'Tests')]) self.assert_profile_put_successful(response, correct_response, user, expected_date)
def test_proposal_apply_review_status(self, notification_type, num_notifications_expected): """Change via proposal with ignorable attrs review status not change""" with factories.single_commit(): risk = factories.RiskFactory() review = factories.ReviewFactory( status=all_models.Review.STATES.REVIEWED, reviewable=risk, notification_type=notification_type ) review_id = review.id user = factories.PersonFactory() acl = factories.AccessControlListFactory( ac_role=factories.AccessControlRoleFactory(object_type="Risk"), object=risk ) proposal_content = { "access_control_list": { acl.ac_role_id: { "added": [{"id": user.id, "email": user.email}], "deleted": [] } } } proposal = factories.ProposalFactory( instance=risk, content=proposal_content, agenda="agenda content" ) self.api.modify_object(proposal, {"status": proposal.STATES.APPLIED}) review = all_models.Review.query.get(review_id) self.assertEqual(review.status, all_models.Review.STATES.REVIEWED) review_notif_types = all_models.Review.NotificationObjectTypes notif_unreviewed_type = all_models.Notification.query.join( all_models.NotificationType ).filter( all_models.NotificationType.name == review_notif_types.STATUS_UNREVIEWED ).all() self.assertEqual(num_notifications_expected, len(notif_unreviewed_type))
def test_create_with_wrong_acl(self): """Test creation of object with wrong ACR in ACL.""" response = self.api.post(all_models.Control, { "control": { "title": "Control title", "context": None, "access_control_list": [{ "ac_role_id": self.objective_admin_acr_id, "person": { "type": "Person", "id": factories.PersonFactory().id, } }], }, }) self.assert400(response) self.assertEqual(all_models.Control.query.count(), 0)
def setUp(self): with factories.single_commit(): super(TestExportControls, self).setUp() self.client.get("/login") self.headers = { 'Content-Type': 'application/json', "X-Requested-By": "GGRC", "X-export-view": "blocks", } self.basic_owner = factories.PersonFactory(name="basic owner") self.control = factories.ControlFactory() self.acr_id = all_models.AccessControlRole.query.filter_by( object_type=self.control.type, name="Admin").first().id self.owner_object = factories.AccessControlListFactory( person=self.basic_owner, object=self.control, ac_role_id=self.acr_id)
def generate_tasks_for_cycle(task_count): """generate number of task groups and task for current task group""" results = [] with ggrc_factories.single_commit(): for idx in range(task_count): person = ggrc_factories.PersonFactory( name="user for group {}".format(idx) ) task = factories.CycleTaskFactory() role = all_models.AccessControlRole.query.filter( all_models.AccessControlRole.name == "Task Assignees", all_models.AccessControlRole.object_type == task.type, ).one() ggrc_factories.AccessControlListFactory( ac_role=role, object=task, person=person) results.append(task.id) return results
def setup_person(self, g_rname, m_rname): """Generate Person with Global Role using Factories. Args: g_rname: Global Role name for user. m_rname: Model related ACR name. If user should not have role in scope of Model, it can be any other string. Returns: Generated person. """ email = self._gen_email(g_rname, m_rname) name = email.split("@")[0] person = factories.PersonFactory(email=email, name=name) bp_factories.UserRoleFactory(person=person, role=rbac_helper.G_ROLES[g_rname]) return person
def generate_control_mappings(self, control): """Map Control to several Assessments""" acr_creator = all_models.AccessControlRole.query.filter_by( name="Creators", object_type="Assessment").first() with factories.single_commit(): person = factories.PersonFactory() asmnt_ids = [] for _ in range(2): asmnt = factories.AssessmentFactory() asmnt_ids.append(asmnt.id) factories.AccessControlListFactory(object=asmnt, person=person, ac_role=acr_creator) for asmnt_id in asmnt_ids: asmnt = all_models.Assessment.query.get(asmnt_id) self.gen.generate_relationship(source=asmnt, destination=control)
def setUp(self): super(TestStatusApiPatch, self).setUp() self.api = Api() with factories.single_commit(): self.assignee = factories.PersonFactory( email="*****@*****.**") ( self.workflow, self.cycle, self.group, self.tasks, ) = self._create_cycle_structure() self.group_id = self.group.id # Emulate that current user is assignee for all test CycleTasks. all_models.CycleTaskGroupObjectTask.current_user_wfa_or_assignee = ( MagicMock(return_value=True))
def create(self): """Create new Task Group object.""" person = factories.PersonFactory() return self.api.post(all_models.TaskGroup, { "task_group": { "contact": { "id": person.id, "type": "Person", }, "title": "New Task Group", "context": None, "workflow": { "id": self.workflow_id, "type": "Workflow", }, } })
def test_search_by_new_owner(self): """Filter by added new owner and old owner""" basic_email, basic_name = self.basic_owner.email, self.basic_owner.name with factories.single_commit(): new_owner = factories.PersonFactory(name="new owner") self.control.add_person_with_role_name(new_owner, "Admin") new_owner_email = new_owner.email new_owner_name = new_owner.email control_slug = self.control.slug self.client.post("/admin/full_reindex") self.assert_slugs("Admin", new_owner_email, [control_slug]) self.assert_slugs("Admin", new_owner_name, [control_slug]) self.assert_slugs("Admin", basic_email, [control_slug]) self.assert_slugs("Admin", basic_name, [control_slug])
def test_update_import_creators(self): "Test for creation assessment with mapped creator" slug = "TestAssessment" assessment = factories.AssessmentFactory(slug=slug) name = "test_name" email = "*****@*****.**" creator_id = factories.PersonFactory(name=name, email=email).id self.assertNotEqual([creator_id], [i.id for i in assessment.creators]) self.import_data( OrderedDict([ ("object_type", "Assessment"), ("Code*", slug), ("Creators", email), ])) assessment = models.Assessment.query.filter( models.Assessment.slug == slug).first() self.assertEqual([creator_id], [i.id for i in assessment.creators])
def test_profile_get_failed(self): """Test person_profiles GET method fails Now only logged user can request his profile """ with factories.single_commit(): valid_user = factories.PersonFactory() self._create_users_names_rbac([valid_user]) response = self.client.get("/api/people/{}/profile".format( valid_user.id)) # logged with default user during setUp self.assert403(response) response = self.api.client.get("/api/people/{}/profile".format( valid_user.id)) # not authorized user self.assert403(response)
def test_generate_empty_auditor(self): """Test generation in audit without Auditor from template with Auditor.""" with factories.single_commit(): person = factories.PersonFactory() self.audit.add_person_with_role(person, self.captains_role) template = factories.AssessmentTemplateFactory( default_people={ "assignees": "Auditors", "verifiers": "Auditors" }) response = self.assessment_post(template) self.assert_assignees("Creators", response, "*****@*****.**") audit = all_models.Audit.query.get(self.audit_id) acp = audit.acr_name_acl_map["Audit Captains"].access_control_people[0] # If Auditor is not set, Audit Captain should be used as Assignee self.assert_assignees("Assignees", response, acp.person.email) self.assert_assignees("Verifiers", response, acp.person.email)
def setup_people(self): """Setup people with global roles.""" # pylint: disable=attribute-defined-outside-init roles_query = all_models.Role.query.filter( all_models.Role.name.in_(self.GLOBAL_ROLES) ) global_roles = {role.name: role for role in roles_query} self.people = {} with factories.single_commit(): for role_name in self.GLOBAL_ROLES: user = factories.PersonFactory() self.people[role_name] = user rbac_factories.UserRoleFactory( role=global_roles[role_name], person=user )
def test_deep_propagation(self): """Test nested propagation from programs to assessments. Test 3 people with 2 roles on programs to propagate to assessments """ audit_count = 3 people_count = 3 program_roles = ["Program Editors", "Program Readers"] with factories.single_commit(): people = [factories.PersonFactory() for _ in range(people_count)] for i in range(audit_count): audit = factories.AuditFactory() assessment = factories.AssessmentFactory(audit=audit) factories.RelationshipFactory( source=audit.program if i % 2 == 0 else audit, destination=audit.program if i % 2 == 1 else audit, ) factories.RelationshipFactory( source=assessment if i % 2 == 0 else audit, destination=assessment if i % 2 == 1 else audit, ) acl_ids = [] for person in people: for role_name in program_roles: acl_ids.append( factories.AccessControlListFactory( ac_role=self.roles["Program"][role_name], object=audit.program, person=person, ).id, ) propagation._propagate(acl_ids) assessment_acls = all_models.AccessControlList.query.filter( all_models.AccessControlList.object_type == all_models.Assessment.__name__).all() self.assertEqual( len(assessment_acls), 3 * 2 # 3 people each with 2 roles on a program that should be # propagated ) for assessment_acl in assessment_acls: self.assertIsNotNone(assessment_acl.parent_id)
def test_issue_bulk_generate(self): """Test bulk generation of issuetracker issues for Issue.""" issue_ids = [] with factories.single_commit(): person = factories.PersonFactory() person_email = person.email for _ in range(3): issue = factories.IssueFactory(modified_by=person) for role_name in ["Admin", "Primary Contacts"]: issue.add_person_with_role_name(person, role_name) factories.IssueTrackerIssueFactory( enabled=True, issue_tracked_obj=issue, issue_id=None, title='', component_id=12345, hotlist_id=54321, issue_priority="P2", issue_severity="S2", ) issue_ids.append(issue.id) issue_issuetracker_info = [("Issue", id_, None, None) for id_ in issue_ids] response = self.generate_issues_for(issue_issuetracker_info) self.assert200(response) self.assertEqual(response.json.get("errors"), []) issues = all_models.IssuetrackerIssue.query.filter( all_models.IssuetrackerIssue.object_type == "Issue", all_models.IssuetrackerIssue.object_id.in_(issue_ids)).all() for issue in issues: parent_obj = issue.Issue_issue_tracked self.assertEqual(issue.enabled, 1) self.assertEqual(issue.title, parent_obj.title) self.assertEqual(issue.component_id, "12345") self.assertEqual(issue.hotlist_id, "54321") self.assertEqual(issue.issue_priority, "P2") self.assertEqual(issue.issue_severity, "S2") self.assertEqual(issue.assignee, person_email) self.assertEqual(issue.cc_list, "") self.assertEqual(issue.issue_id, self.issue_id) self.assertEqual(issue.issue_url, "http://issue/{}".format(self.issue_id))
def test_change_assessment_status(self, status, additional_kwargs, mocked_update_issue): """Issue status should be changed for assessment with {status} status.""" email1 = "*****@*****.**" assignee_role_id = AccessControlRole.query.filter_by( object_type="Assessment", name="Assignees").first().id assignees = [factories.PersonFactory(email=email1)] iti_issue_id = [] iti = factories.IssueTrackerIssueFactory(enabled=True) iti_issue_id.append(iti.issue_id) asmt = iti.issue_tracked_obj asmt_title = asmt.title with mock.patch.object(assessment_integration, '_is_issue_tracker_enabled', return_value=True): acl = [ acl_helper.get_acl_json(assignee_role_id, assignee.id) for assignee in assignees ] self.api.put(asmt, { "access_control_list": acl, "status": status, }) kwargs = { 'component_id': None, 'severity': None, 'title': asmt_title, 'hotlist_ids': [], 'priority': None, 'assignee': email1, 'verifier': email1, 'ccs': [] } asmt_link = assessment_integration._get_assessment_url(asmt) if 'comment' in additional_kwargs: additional_kwargs['comment'] = \ additional_kwargs['comment'] % (status, asmt_link) kwargs.update(additional_kwargs) mocked_update_issue.assert_called_once_with( iti_issue_id[0], kwargs) issue = db.session.query(models.IssuetrackerIssue).get(iti.id) self.assertEqual(issue.assignee, email1) self.assertEqual(issue.cc_list, "")
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" }]
def test_autogenerated_no_acl_in_snapshot(self, field, role_name): """Test autogenerated assessment assignees base on template settings and no ACL list in snapshot.""" email = "{}@example.com".format(field) with factories.single_commit(): person = factories.PersonFactory(email=email, name=field) template = factories.AssessmentTemplateFactory( test_plan_procedure=False, procedure_description="Assessment Template Test Plan", default_people={"assignees": role_name}) content = self.control.log_json() content.pop("access_control_list") content[field] = {"id": person.id} self.snapshot.revision.content = content db.session.add(self.snapshot.revision) response = self.assessment_post(template) self.assert_assignees("Assignees", response, email)
def test_update_import_assignee(self): "Test for creation assessment with mapped creator" slug = "TestAssessment" name = "test_name" email = "*****@*****.**" with factories.single_commit(): assessment = factories.AssessmentFactory(slug=slug) assignee_id = factories.PersonFactory(name=name, email=email).id self._test_assigned_user(assessment, None, "Assignees") self.import_data( OrderedDict([ ("object_type", "Assessment"), ("Code*", slug), ("Assignees", email), ])) assessment = all_models.Assessment.query.filter( all_models.Assessment.slug == slug).first() self._test_assigned_user(assessment, assignee_id, "Assignees")
def test_evidence_mapped_roles(self): """Test creation of mapped evidence roles.""" with factories.single_commit(): person = factories.PersonFactory() person_email = person.email audit = factories.AuditFactory() assessment = factories.AssessmentFactory(audit=audit) for ac_role_id in self.assignee_roles.values(): assessment.add_person_with_role_id(person, ac_role_id) factories.RelationshipFactory(source=audit, destination=assessment) evidence = factories.EvidenceUrlFactory() factories.RelationshipFactory(source=assessment, destination=evidence) db.session.add(evidence) for role in ["Assignees", "Creators", "Verifiers"]: self.assert_propagated_role(role, person_email, evidence)
def setUp(self): super(TestAccessControlList, self).setUp() self.api = Api() self.person = factories.PersonFactory(name="My Person") self.control = factories.ControlFactory() self.acr = factories.AccessControlRoleFactory( object_type="Control", read=True ) self.second_acr = factories.AccessControlRoleFactory( object_type="Control", read=True ) self.acl = factories.AccessControlListFactory( object=self.control, ac_role_id=self.acr.id, person=self.person )
def test_generate_empty_auditor(self): """Test generation in audit without Auditor from template with Auditor.""" with factories.single_commit(): person = factories.PersonFactory() captain_acl_id = factories.AccessControlListFactory( object=self.audit, person=person, ac_role=self.captains_role).id template = factories.AssessmentTemplateFactory( default_people={ "assignees": "Auditors", "verifiers": "Auditors" }) response = self.assessment_post(template) self.assert_assignees("Creators", response, "*****@*****.**") captain_acl = all_models.AccessControlList.query.get(captain_acl_id) # If Auditor is not set, Audit Captain should be used as Assignee self.assert_assignees("Assignees", response, captain_acl.person.email) self.assert_assignees("Verifiers", response, captain_acl.person.email)
def test_permissions_reload_on_role_delete(self): """Test permissions in memcache are recalculated on UserRole DELETE.""" admin_role = all_models.Role.query.filter_by( name="Administrator").one() with ggrc_factories.single_commit(): person = ggrc_factories.PersonFactory() person_permissions_key = "permissions:{}".format(person.id) person_role = rbac_factories.UserRoleFactory( role=admin_role, person=person, ) self.memcache_client.delete("permissions:list") response = self.api.delete(person_role) self.assertStatus(response, 200) cached_keys = self.memcache_client.get("permissions:list") self.assertIn(person_permissions_key, cached_keys)