def test_assigned_task_delete(self, user_role, ac_role, can_delete): """ Test possibility to delete of assigned cycle task""" user = self.users[user_role] workflow_obj = self.activate_workflow_with_cycle(self.workflow_obj)[1] cycle_task = workflow_obj.cycles[0].cycle_task_group_object_tasks[0] role_map = { name: ind for (ind, name) in role.get_custom_roles_for( all_models.Workflow.__name__).iteritems() } put_params = { 'access_control_list': [ acl_helper.get_acl_json(role_map[ac_role], user.id), acl_helper.get_acl_json(role_map["Admin"], self.users["admin"].id), ] } response = self.api.put(workflow_obj, put_params) self.assert200(response) self.api.set_user(user) res = self.api.delete(cycle_task) if can_delete: self.assert200(res) else: self.assert403(res)
def test_access_conrol_list(self): """Test notification when access conrol list is changed""" assignee_acr = all_models.AccessControlRole.query.filter_by( object_type="Assessment", name="Assignees", ).first() response = self.api.put( self.assessment, { "access_control_list": [ acl_helper.get_acl_json(self.secondary_role_id, self.auditor.id), acl_helper.get_acl_json(assignee_acr.id, self.auditor.id) ], }) self.assert200(response) notifs, notif_data = common.get_daily_notifications() updated = notif_data["*****@*****.**"]["assessment_updated"] self.assertEqual(len(notifs), 1) self.assertEqual( updated[self.assessment.id]["updated_data"]["PRIMARY CONTACTS"], ([], ["*****@*****.**"])) self.assertEqual( updated[self.assessment.id]["updated_data"]["SECONDARY CONTACTS"], (["*****@*****.**"], []))
def test_assigned_task_delete(self, user_role, ac_role, can_delete): """ Test possibility to delete of assigned cycle task""" user = self.users[user_role] workflow_obj = self.activate_workflow_with_cycle(self.workflow_obj)[1] cycle_task = workflow_obj.cycles[0].cycle_task_group_object_tasks[0] role_map = { name: ind for (ind, name) in role.get_custom_roles_for(all_models.Workflow.__name__).iteritems() } put_params = {'access_control_list': [ acl_helper.get_acl_json(role_map[ac_role], user.id), acl_helper.get_acl_json(role_map["Admin"], self.users["admin"].id), ]} response = self.api.put(workflow_obj, put_params) self.assert200(response) self.api.set_user(user) res = self.api.delete(cycle_task) if can_delete: self.assert200(res) else: self.assert403(res)
def create_test_cases(self): def person_dict(person_id): return { "href": "/api/people/%d" % person_id, "id": person_id, "type": "Person" } role_id = all_models.AccessControlRole.query.filter( all_models.AccessControlRole.name == "Task Assignees", all_models.AccessControlRole.object_type == "TaskGroupTask", ).one().id self.one_time_workflow_1 = { "title": "one time test workflow", "notify_on_change": True, "description": "some test workflow", # admin will be current user with id == 1 "task_groups": [{ "title": "single task group", "contact": person_dict(self.user.id), "task_group_tasks": [{ "title": "task 1", "description": "single task in a wf", "access_control_list": [ acl_helper.get_acl_json(role_id, self.user.id)], "start_date": date(2015, 5, 1), # friday "end_date": date(2015, 5, 5), }], }] } self.one_time_workflow_2 = { "title": "one time test workflow", "notify_on_change": True, "description": "some test workflow", # admin will be current user with id == 1 "task_groups": [{ "title": "one time task group", "contact": person_dict(self.user.id), "task_group_tasks": [{ "title": "task 1", "description": "two taks in wf with different objects", "access_control_list": [ acl_helper.get_acl_json(role_id, self.user.id)], "start_date": date(2015, 5, 1), # friday "end_date": date(2015, 5, 5), }, { "title": "task 2", "description": "two taks in wf with different objects", "access_control_list": [ acl_helper.get_acl_json(role_id, self.user.id)], "start_date": date(2015, 5, 1), # friday "end_date": date(2015, 5, 5), }], "task_group_objects": self.random_objects }] }
def _create_test_cases(self): """Create configuration to use for generating a new workflow.""" def person_dict(person_id): return { "href": "/api/people/" + str(person_id), "id": person_id, "type": "Person" } role_id = models.all_models.AccessControlRole.query.filter( models.all_models.AccessControlRole.name == "Task Assignees", models.all_models.AccessControlRole.object_type == "TaskGroupTask", ).one().id self.one_time_workflow = { "title": "one time test workflow", "notify_on_change": True, "description": "some test workflow", # admin will be current user with id == 1 "task_groups": [{ "title": "one time task group", "contact": person_dict(self.user.id), "task_group_tasks": [ { "title": "task 1", "description": "some task", "start_date": date(2017, 5, 5), # Friday "end_date": date(2017, 5, 15), "access_control_list": [acl_helper.get_acl_json(role_id, self.user.id)], }, { "title": "task 2", "description": "some task 2", "start_date": date(2017, 5, 5), # Friday "end_date": date(2017, 5, 16), "access_control_list": [acl_helper.get_acl_json(role_id, self.user.id)], } ], "task_group_objects": self.random_objects }] }
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_issue_tracker_verifier(self, mock_create_issue): """Test ticket verifier is first of admins in alphabetical order""" title = "test title" with factories.single_commit(): verifier_email = '*****@*****.**' verifier_id = factories.PersonFactory( email=verifier_email, name='Weel', ).id person1_id = factories.PersonFactory( email='*****@*****.**', name='David', ).id person2_id = factories.PersonFactory( email='*****@*****.**', name='Ann', ).id admin_acr_id = all_models.AccessControlRole.query.filter( all_models.AccessControlRole.name == "Admin", all_models.AccessControlRole.object_type == "Issue", ).one().id response = self.api.post( all_models.Issue, { "issue": { "title": title, "issue_tracker": { "enabled": True, }, "access_control_list": [ acl_helper.get_acl_json(admin_acr_id, person1_id), acl_helper.get_acl_json(admin_acr_id, person2_id), acl_helper.get_acl_json(admin_acr_id, verifier_id), ], "due_date": "10/10/2019" }, }) mock_create_issue.assert_called_once() call_args_list, _ = mock_create_issue.call_args call_args = call_args_list[0] self.assertEqual(call_args['verifier'], verifier_email) self.assertEqual(response.status_code, 201) issue_id = response.json.get("issue").get("id") issue_tracker_issue = models.IssuetrackerIssue.get_issue( "Issue", issue_id) self.assertTrue(issue_tracker_issue.enabled) self.assertEqual(issue_tracker_issue.title, title)
def _create_test_cases(self): """Create configuration to use for generating a new workflow.""" role_id = all_models.AccessControlRole.query.filter( all_models.AccessControlRole.name == "Task Assignees", all_models.AccessControlRole.object_type == "TaskGroupTask", ).one().id self.one_time_workflow = { "title": "one time test workflow", "notify_on_change": True, "description": "some test workflow", "task_groups": [{ "title": "one time task group", "contact": { "href": "/api/people/" + str(self.user.id), "id": self.user.id, "type": "Person" }, "task_group_tasks": [{ "title": "task 1", "description": "some task", "start_date": date(2018, 6, 10), "end_date": date(2018, 7, 10), "access_control_list": [ acl_helper.get_acl_json(role_id, self.user.id)], }] }] }
def generate_workflow(self, data=None): """ create a workflow with dict data return: wf if it was created, or response otherwise """ if data is None: data = {} obj_name = "workflow" data = copy.deepcopy(data) tgs = data.pop("task_groups", []) wf_instance = Workflow(title="wf " + factories.random_str()) obj_dict = self.obj_to_dict(wf_instance, obj_name) wf_admin_role_id = { n: i for (i, n) in role.get_custom_roles_for(Workflow.__name__).iteritems() }['Admin'] if "access_control_list" not in data: wf_admin_id = Person.query.first().id data["access_control_list"] = [ acl_helper.get_acl_json(wf_admin_role_id, wf_admin_id)] obj_dict[obj_name].update(data) response, workflow = self.generate(Workflow, obj_name, obj_dict) for task_group in tgs: self.generate_task_group(workflow, task_group) return response, workflow
def test_deletion_multiple_assignee(self): """Test deletion of multiple mapped roles.""" with factories.single_commit(): persons = [factories.PersonFactory() for _ in range(2)] person_ids = [p.id for p in persons] person_email = persons[1].email audit = factories.AuditFactory() assessment = factories.AssessmentFactory(audit=audit) for ac_role_id in self.assignee_roles.values(): for person in persons: assessment.add_person_with_role_id(person, ac_role_id) factories.RelationshipFactory(source=audit, destination=assessment) # Remove assignee roles for first person response = self.api.put(assessment, { "access_control_list": [ acl_helper.get_acl_json(role_id, person_ids[1]) for role_id in self.assignee_roles.values() ] }) self.assertEqual(response.status_code, 200) assignee_acl = all_models.AccessControlPerson.query.filter_by( person_id=person_ids[0] ) # All roles for first person should be removed self.assertEqual(assignee_acl.count(), 0) db.session.add(audit) for ac_role in self.assignee_roles.keys(): self.assert_mapped_role(ac_role, person_email, assessment) self.assert_propagated_role( "{}".format(ac_role), person_email, audit )
def _create_test_cases(self): """Create configuration to use for generating a new workflow.""" role_id = all_models.AccessControlRole.query.filter( all_models.AccessControlRole.name == "Task Assignees", all_models.AccessControlRole.object_type == "TaskGroupTask", ).one().id self.one_time_workflow = { "title": "one time test workflow", "notify_on_change": True, "description": "some test workflow", "task_groups": [{ "title": "one time task group", "contact": { "href": "/api/people/" + str(self.user.id), "id": self.user.id, "type": "Person" }, "task_group_tasks": [{ "title": "task 1", "description": "some task", "start_date": date(2018, 6, 10), "end_date": date(2018, 7, 10), "access_control_list": [acl_helper.get_acl_json(role_id, self.user.id)], }] }] }
def setUp(self): super(TestPermissionsOnAssessmentTemplate, self).setUp() self.api = Api() editor = all_models.AccessControlRole.query.filter( all_models.AccessControlRole.name == "Program Editors").one() self.generator = ObjectGenerator() _, self.editor = self.generator.generate_person(user_role="Creator") _, program = self.generator.generate_object( all_models.Program, { "access_control_list": [acl_helper.get_acl_json(editor.id, self.editor.id)] }) program_id = program.id _, audit = self.generator.generate_object( all_models.Audit, { "title": "Assessment Template test Audit", "program": { "id": program_id }, "status": "Planned" }, ) audit_id = audit.id generated_at = self.generator.generate_object( all_models.AssessmentTemplate, self._get_assessment_template_base("Template", audit)) self.assessment_template_resp, assessment_template = generated_at assessment_template_id = assessment_template.id self.api.set_user(self.editor) self.perms_data = self.api.client.get("/permissions").json self.audit = all_models.Audit.query.get(audit_id) self.assessment_template = all_models.AssessmentTemplate.query.get( assessment_template_id)
def test_put_all_affected_evidence(self, kind, attr_name): """Test put all affected of evidence data assessment status changed""" expected_status = models.Assessment.PROGRESS_STATE with factories.single_commit(): evidence = factories.EvidenceFactory(kind=kind) evidence_id = evidence.id factories.RelationshipFactory(destination=self.assessment, source=evidence) person_id = factories.PersonFactory().id role_id = models.AccessControlRole.query.filter( models.AccessControlRole.object_type == "Evidence", models.AccessControlRole.name == 'Admin', ).one().id self.api.put( evidence, { attr_name: "test text", "access_control_list": [ acl_helper.get_acl_json(role_id, person_id), ] }) assessment = self.refresh_object(self.assessment, self.assessment_id) evidence = self.refresh_object(evidence, evidence_id) self.assertEqual(assessment.status, expected_status) self.assertEqual(getattr(evidence, attr_name), "test text")
def generate_workflow(self, data=None): """ create a workflow with dict data return: wf if it was created, or response otherwise """ if data is None: data = {} obj_name = "workflow" data = copy.deepcopy(data) tgs = data.pop("task_groups", []) wf_instance = Workflow(title="wf " + factories.random_str()) obj_dict = self.obj_to_dict(wf_instance, obj_name) wf_admin_role_id = { n: i for ( i, n) in role.get_custom_roles_for(Workflow.__name__).iteritems() }['Admin'] if "access_control_list" not in data: wf_admin_id = Person.query.first().id data["access_control_list"] = [ acl_helper.get_acl_json(wf_admin_role_id, wf_admin_id) ] obj_dict[obj_name].update(data) response, workflow = self.generate(Workflow, obj_name, obj_dict) for task_group in tgs: self.generate_task_group(workflow, task_group) return response, workflow
def generate_task_group_task(self, task_group=None, data=None): """Generate task group task over api.""" if data is None: data = {} if not task_group: _, task_group = self.generate_task_group() task_group = self._session_add(task_group) default_start = self.random_date() default_end = self.random_date(default_start, date.today()) obj_name = "task_group_task" cycle_task_role_id = { v: k for (k, v) in role.get_custom_roles_for("TaskGroupTask").iteritems() }['Task Assignees'] tgt = TaskGroupTask( task_group_id=task_group.id, context_id=task_group.context.id, title="tgt " + factories.random_str(), start_date=default_start, end_date=default_end, ) obj_dict = self.obj_to_dict(tgt, obj_name) if "access_control_list" not in data: wf_admin_id = Person.query.first().id data["access_control_list"] = [ acl_helper.get_acl_json(cycle_task_role_id, wf_admin_id)] obj_dict[obj_name].update(data) return self.generate(TaskGroupTask, obj_name, obj_dict)
def generate_task_group_task(self, task_group=None, data=None): """Generate task group task over api.""" if data is None: data = {} if not task_group: _, task_group = self.generate_task_group() task_group = self._session_add(task_group) default_start = self.random_date() default_end = self.random_date(default_start, date.today()) obj_name = "task_group_task" cycle_task_role_id = { v: k for (k, v) in role.get_custom_roles_for("TaskGroupTask").iteritems() }['Task Assignees'] tgt = TaskGroupTask( task_group_id=task_group.id, context_id=task_group.context.id, title="tgt " + factories.random_str(), start_date=default_start, end_date=default_end, ) obj_dict = self.obj_to_dict(tgt, obj_name) if "access_control_list" not in data: wf_admin_id = Person.query.first().id data["access_control_list"] = [ acl_helper.get_acl_json(cycle_task_role_id, wf_admin_id) ] obj_dict[obj_name].update(data) return self.generate(TaskGroupTask, obj_name, obj_dict)
def test_revision_access(self): """Check if creator can access the right revision objects.""" def gen(title, extra_data=None): """Generates section.""" section_content = {"title": title, "context": None} if extra_data: section_content.update(**extra_data) return self.generator.generate(all_models.Section, "section", {"section": section_content})[1] def check(obj, expected): """Check that how many revisions of an object current user can see.""" response = self.api.get_query( all_models.Revision, "resource_type={}&resource_id={}".format(obj.type, obj.id)) self.assertEqual(response.status_code, 200) self.assertEqual( len(response.json['revisions_collection']['revisions']), expected) self.api.set_user(self.users["admin"]) obj_1 = gen("Test Section 1") self.api.set_user(self.users["creator"]) acr_id = all_models.AccessControlRole.query.filter_by( object_type="Section", name="Admin").first().id linked_acl = { "access_control_list": [acl_helper.get_acl_json(acr_id, self.users["creator"].id)], } check(obj_1, 0) obj_2 = gen("Test Section 2", linked_acl) obj2_acl = obj_2.access_control_list[0] check(obj_2, 1) check(obj2_acl, 1)
def create_program(self, program_role, userid): """Create default program for audit snapshot RBAC tests""" if program_role and program_role != "Auditors": program_role = all_models.AccessControlRole.query.filter( all_models.AccessControlRole.name == program_role).one() else: program_role = None _, program = self.objgen.generate_object( all_models.Program, { "title": "test program", "access_control_list": [acl_helper.get_acl_json(program_role.id, userid)] if program_role else None }) for model_type in Types.all - Types.external: model = get_model(model_type) _, model_object = self.objgen.generate_object( model, { "title": "Test Snapshot - {}".format(model_type), }) self.objgen.generate_relationship(program, model_object) return program
def test_update_issuetracker_assignee(self, mocked_update_issue): """Test assignee sync in case it has been updated.""" email1 = "*****@*****.**" email2 = "*****@*****.**" assignee_role_id = AccessControlRole.query.filter_by( object_type="Assessment", name="Assignees" ).first().id assignees = [factories.PersonFactory(email=email2), 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 }) kwargs = {'status': 'ASSIGNED', 'component_id': None, 'severity': None, 'title': asmt_title, 'hotlist_ids': [], 'priority': None, 'assignee': email1, 'verifier': email1, 'ccs': [email2]} mocked_update_issue.assert_called_once_with(iti_issue_id[0], kwargs)
def test_update_issuetracker_assignee(self, mocked_update_issue): """Test assignee sync in case it has been updated.""" email1 = "*****@*****.**" email2 = "*****@*****.**" assignee_role_id = AccessControlRole.query.filter_by( object_type="Assessment", name="Assignees" ).first().id assignees = [factories.PersonFactory(email=email2), factories.PersonFactory(email=email1)] iti_issue_id = [] iti = factories.IssueTrackerIssueFactory(enabled=True) iti_issue_id.append(iti.issue_id) asmt = iti.issue_tracked_obj with mock.patch.object(issue_tracker, '_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 }) kwargs = {'status': 'ASSIGNED', 'component_id': None, 'severity': None, 'title': iti.title, 'hotlist_ids': [], 'priority': None, 'assignee': email1, 'verifier': email1, 'ccs': [email2]} mocked_update_issue.assert_called_once_with(iti_issue_id[0], kwargs)
def _post_control(self, acr_id, person_id, assertion_id, collection=False): """Helper function for posting a control""" title = factories.random_str(prefix="Control - ") control = { "control": { "title": title, "type": "Control", "context": None, "access_control_list": [acl_helper.get_acl_json(acr_id, person_id)], "assertions": [{ "id": assertion_id }] }, } response = self.api.post(all_models.Control, [control] if collection else control) self.assertTrue( response.status_code == 200 or response.status_code == 201, "Control not created successfully {}".format(response.status)) if collection: return response.json[0][1] return response.json
def _post_control(self, acr_id, person_id, assertion, collection=False): """Helper function for posting a control""" title = factories.random_str(prefix="Control - ") control = { "control": { "title": title, "type": "Control", "context": None, "access_control_list": [acl_helper.get_acl_json(acr_id, person_id)], "assertions": '["{}"]'.format(assertion), "external_id": factories.SynchronizableExternalId.next(), "external_slug": factories.random_str(), "review_status": all_models.Review.STATES.UNREVIEWED, "review_status_display_name": "some status", }, } with self.api.as_external(): response = self.api.post(all_models.Control, [control] if collection else control) self.assertTrue( response.status_code == 200 or response.status_code == 201, "Control not created successfully {}".format(response.status)) if collection: return response.json[0][1] return response.json
def test_deletion_mapped_roles(self): """Test deletion of mapped 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(): factories.AccessControlListFactory( ac_role_id=ac_role_id, person=person, object=assessment ) factories.RelationshipFactory(source=audit, destination=assessment) # Remove verifier and assignee from Assessment response = self.api.put(assessment, { "access_control_list": [ acl_helper.get_acl_json(self.assignee_roles["Creators"], person.id) ] }) self.assertEqual(response.status_code, 200) db.session.add(audit) self.assert_mapped_role("Creators", person_email, assessment) self.assert_propagated_role("Creators", person_email, audit)
def test_post_mapped_roles(self): """Test mapped roles creation when new assessment created""" audit = factories.AuditFactory() person = factories.PersonFactory() person_email = person.email response = self.api.post(all_models.Assessment, { "assessment": { "audit": { "id": audit.id, "type": "Audit" }, "access_control_list": [ acl_helper.get_acl_json(role_id, person.id) for role_id in self.assignee_roles.values() ], "context": { "id": audit.context.id, "type": "Context" }, "title": "Some title" } }) self.assertEqual(response.status_code, 201) db.session.add(audit) assessment = all_models.Assessment.query.get( response.json["assessment"]["id"] ) for role in self.assignee_roles: self.assert_mapped_role(role, person_email, assessment) self.assert_propagated_role("{}".format(role), person_email, audit)
def test_put_mapped_roles(self): """Test mapped roles creation when assessment updated""" with factories.single_commit(): person = factories.PersonFactory() person_email = person.email audit = factories.AuditFactory() assessment = factories.AssessmentFactory(audit=audit) factories.AccessControlListFactory( ac_role_id=self.assignee_roles["Assignees"], person=person, object=assessment ) factories.AccessControlListFactory( ac_role_id=self.assignee_roles["Creators"], person=person, object=assessment ) factories.RelationshipFactory(source=audit, destination=assessment) # Add verifier to Assessment response = self.api.put(assessment, { "access_control_list": [ acl_helper.get_acl_json(role_id, person.id) for role_id in self.assignee_roles.values() ] }) self.assertEqual(response.status_code, 200) db.session.add_all([audit, assessment]) self.assert_mapped_role("Verifiers", person_email, assessment) self.assert_propagated_role("Verifiers", person_email, audit)
def test_creator_search(self): """Test if creator can see the correct object while using the search api""" self.api.set_user(self.users['admin']) self.api.post(all_models.Regulation, { "regulation": { "title": "Admin regulation", "context": None }, }) self.api.set_user(self.users['creator']) acr_id = all_models.AccessControlRole.query.filter_by( object_type="Policy", name="Admin").first().id response = self.api.post( all_models.Policy, { "policy": { "title": "Creator Policy", "context": None, "access_control_list": [ acl_helper.get_acl_json(acr_id, self.users["creator"].id) ], }, }) response.json.get("policy").get("id") response, _ = self.api.search("Regulation,Policy") entries = response.json["results"]["entries"] self.assertEqual(len(entries), 1) self.assertEqual(entries[0]["type"], "Policy") response, _ = self.api.search("Regulation,Policy", counts=True) self.assertEqual(response.json["results"]["counts"]["Policy"], 1) self.assertEqual(response.json["results"]["counts"].get("Regulation"), None)
def init_workflow(self): """Creates a workflow which is owned by an user with Admin role""" admin_role_id = { n: i for (i, n) in role.get_custom_roles_for(Workflow.__name__).iteritems() }['Admin'] initial_workflow_data = { "title": "test workflow", "description": "test workflow", "access_control_list": [ acl_helper.get_acl_json(admin_role_id, self.users['admin'].id)], "status": "Draft", "task_groups": [{ "title": "task group 1", "contact": self.person_dict(self.users['admin'].id), "task_group_tasks": [{ "title": "task 1", "description": "some task", "contact": self.person_dict(self.users['admin'].id), "start_date": date(2016, 5, 26), "end_date": date(2016, 5, 28), }], "task_group_objects": self.random_objects[:2] }] } self.workflow_res, self.workflow_obj =\ self.generator.generate_workflow(initial_workflow_data)
def test_creator_search(self): """Test if creator can see the correct object while using the search api""" self.api.set_user(self.users['admin']) self.api.post(all_models.Regulation, { "regulation": {"title": "Admin regulation", "context": None}, }) self.api.set_user(self.users['creator']) acr_id = all_models.AccessControlRole.query.filter_by( object_type="Policy", name="Admin" ).first().id response = self.api.post(all_models.Policy, { "policy": { "title": "Creator Policy", "context": None, "access_control_list": [ acl_helper.get_acl_json(acr_id, self.users["creator"].id)], }, }) response.json.get("policy").get("id") response, _ = self.api.search("Regulation,Policy") entries = response.json["results"]["entries"] self.assertEqual(len(entries), 1) self.assertEqual(entries[0]["type"], "Policy") response, _ = self.api.search("Regulation,Policy", counts=True) self.assertEqual(response.json["results"]["counts"]["Policy"], 1) self.assertEqual( response.json["results"]["counts"].get("Regulation"), None)
def create_audit(self, audit_role, userid): """Create default audit for audit snapshot RBAC tests""" is_auditor = False if audit_role == "Auditors": is_auditor = True auditor_role = all_models.AccessControlRole.query.filter( all_models.AccessControlRole.name == "Auditors").one() program = db.session.query(all_models.Program).get(self.program_id) _, audit = self.objgen.generate_object( all_models.Audit, { "title": "Snapshotable audit", "program": { "id": self.program_id }, "status": "Planned", "snapshots": { "operation": "create", }, "access_control_list": [acl_helper.get_acl_json(auditor_role.id, userid)] if is_auditor else None, "context": { "type": "Context", "id": program.context_id, "href": "/api/contexts/{}".format(program.context_id) } }) return audit
def test_deletion_multiple_assignee(self): """Test deletion of multiple mapped roles.""" with factories.single_commit(): persons = [factories.PersonFactory() for _ in range(2)] person_ids = [p.id for p in persons] person_email = persons[1].email audit = factories.AuditFactory() assessment = factories.AssessmentFactory(audit=audit) for ac_role_id in self.assignee_roles.values(): for person in persons: assessment.add_person_with_role_id(person, ac_role_id) factories.RelationshipFactory(source=audit, destination=assessment) # Remove assignee roles for first person response = self.api.put( assessment, { "access_control_list": [ acl_helper.get_acl_json(role_id, person_ids[1]) for role_id in self.assignee_roles.values() ] }) self.assertEqual(response.status_code, 200) assignee_acl = all_models.AccessControlPerson.query.filter_by( person_id=person_ids[0]) # All roles for first person should be removed self.assertEqual(assignee_acl.count(), 0) db.session.add(audit) for ac_role in self.assignee_roles.keys(): self.assert_mapped_role(ac_role, person_email, assessment) self.assert_propagated_role("{}".format(ac_role), person_email, audit)
def test_post_mapped_roles(self): """Test mapped roles creation when new assessment created""" audit = factories.AuditFactory() person = factories.PersonFactory() person_email = person.email response = self.api.post( all_models.Assessment, { "assessment": { "audit": { "id": audit.id, "type": "Audit" }, "access_control_list": [ acl_helper.get_acl_json(role_id, person.id) for role_id in self.assignee_roles.values() ], "context": { "id": audit.context.id, "type": "Context" }, "title": "Some title" } }) self.assertEqual(response.status_code, 201) db.session.add(audit) assessment = all_models.Assessment.query.get( response.json["assessment"]["id"]) for role in self.assignee_roles: self.assert_mapped_role(role, person_email, assessment) self.assert_propagated_role("{}".format(role), person_email, audit)
def _add_creator(self, asmnt, user): """Helper method for creating assignees on an object""" acr = all_models.AccessControlRole.query.filter( all_models.AccessControlRole.object_type == "Assessment", all_models.AccessControlRole.name == "Creators", ).first() return self.api.put(asmnt, { "access_control_list": [acl_helper.get_acl_json(acr.id, user.id)] })
def test_access_conrol_list(self): """Test notification when access conrol list is changed""" assignee_acr = all_models.AccessControlRole.query.filter_by( object_type="Assessment", name="Assignees", ).first() response = self.api.put(self.assessment, { "access_control_list": [ acl_helper.get_acl_json(self.secondary_role_id, self.auditor.id), acl_helper.get_acl_json(assignee_acr.id, self.auditor.id) ], }) self.assert200(response) notifs, notif_data = common.get_daily_notifications() updated = notif_data["*****@*****.**"]["assessment_updated"] self.assertEqual(len(notifs), 1) self.assertEqual(updated[self.assessment.id]["updated_fields"], ["PRIMARY CONTACTS", "SECONDARY CONTACTS"])
def _prepare_acl_json(obj_type, rolename_emails_map): """Prepate ACL json for specific object type.""" result = [] with factories.single_commit(): for rolename, emails in rolename_emails_map.iteritems(): for email in emails: person_id = factories.PersonFactory(email=email).id role_id = all_models.AccessControlRole.query.filter_by( name=rolename, object_type=obj_type).one().id result.append(acl_helper.get_acl_json(role_id, person_id)) return result
def _create_test_cases(self): """Create configuration to use for generating a new workflow.""" def person_dict(person_id): return { "href": "/api/people/" + str(person_id), "id": person_id, "type": "Person" } role_id = models.all_models.AccessControlRole.query.filter( models.all_models.AccessControlRole.name == "Task Assignees", models.all_models.AccessControlRole.object_type == "TaskGroupTask", ).one().id self.one_time_workflow = { "title": "one time test workflow", "notify_on_change": True, "description": "some test workflow", # admin will be current user with id == 1 "task_groups": [{ "title": "one time task group", "contact": person_dict(self.user.id), "task_group_tasks": [{ "title": "task 1", "description": "some task", "start_date": date(2017, 5, 5), # Friday "end_date": date(2017, 5, 15), "access_control_list": [ acl_helper.get_acl_json(role_id, self.user.id)], }, { "title": "task 2", "description": "some task 2", "start_date": date(2017, 5, 5), # Friday "end_date": date(2017, 5, 16), "access_control_list": [ acl_helper.get_acl_json(role_id, self.user.id)], }], "task_group_objects": self.random_objects }] }
def setUp(self): super(TestPermissionsOnAssessmentTemplate, self).setUp() self.api = Api() editor = all_models.AccessControlRole.query.filter( all_models.AccessControlRole.name == "Program Editors").one() self.generator = ObjectGenerator() _, self.editor = self.generator.generate_person(user_role="Creator") _, program = self.generator.generate_object( all_models.Program, { "access_control_list": [acl_helper.get_acl_json(editor.id, self.editor.id)] }) program_id = program.id _, audit = self.generator.generate_object( all_models.Audit, { "title": "Audit", "program": { "id": program_id }, "status": "Planned" }, ) audit_id = audit.id generated_at = self.generator.generate_object( all_models.AssessmentTemplate, { "title": "Template", "_NON_RELEVANT_OBJ_TYPES": {}, "_objectTypes": {}, "audit": { "id": audit.id }, "audit_title": audit.title, "people_value": [], "default_people": { "assignees": "Admin", "verifiers": "Admin", }, "context": { "id": audit.context.id }, }) self.assessment_template_resp, assessment_template = generated_at assessment_template_id = assessment_template.id self.api.set_user(self.editor) self.perms_data = self.api.client.get("/permissions").json self.audit = all_models.Audit.query.get(audit_id) self.assessment_template = all_models.AssessmentTemplate.query.get( assessment_template_id)
def _get_create_proposal_request(risk_id, acr_id, person_id): """Prepare dict with proposal creation request""" return { "proposal": { "instance": { "id": risk_id, "type": all_models.Risk.__name__, }, "full_instance_content": {"title": "new_title"}, "agenda": "update cav", "context": None, "access_control_list": [acl_helper.get_acl_json(acr_id, person_id)] } }
def test_put_object_roles(self): """Test if PUTing object roles saves them correctly""" id_2, person_id = self.second_acr.id, self.person.id response = self.api.get(all_models.Control, self.control.id) assert response.status_code == 200, \ "Failed to fetch created control {}".format(response.status) control = response.json['control'] control['access_control_list'].append( acl_helper.get_acl_json(id_2, person_id)) response = self.api.put(self.control, {"control": control}) assert response.status_code == 200, \ "PUTing control failed {}".format(response.status) acl = response.json['control']['access_control_list'] assert len(acl) == 2, \ "Access control list not correctly updated {}".format(acl)
def test_evidence_acl(self): """Test evidence with ACR creation""" person = factories.PersonFactory() acr_class = all_models.AccessControlRole acr = acr_class.query.filter( acr_class.name == 'Admin', acr_class.object_type == 'Evidence').one() evidence = factories.EvidenceFactory( title='Simple title', kind=all_models.Evidence.URL, link='simple_url.test', access_control_list=[acl_helper.get_acl_json(acr.id, person.id)]) acl_class = all_models.AccessControlList acl = acl_class.query.filter(acl_class.object_id == evidence.id).one() self.assertTrue(acl)
def test_issue_audit_creator(self, user_email): """Test automapping issue to audit for {}. This test should check if the issue is automapped to an audit when a creator raises an issue on an assessment that belongs to the given audit. """ user = all_models.Person.query.filter_by(email=user_email).one() self.api.set_user(user) assessment = all_models.Assessment.query.first() response = self.api.post( all_models.Issue, data=[{ "issue": { "status": "Draft", "access_control_list": [ acl_helper.get_acl_json(self.issue_admin_role.id, user.id) ], "assessment": { "type": assessment.type, "id": assessment.id, # Fields sent by the request but not actually needed. # "title": "assessment", # "title_singular": "Assessment", # "table_singular": "assessment" }, "title": "aa", "context": None, # Setting the context would make the test match the front-end # change that was reverted in 577afd6686 # "context": { # "type": assessment.context.type, # "id": assessment.context.id, # }, } }]) self.assert200(response) issue = all_models.Issue.query.first() audit = all_models.Audit.query.first() self.assertIsNotNone(issue) relationship = all_models.Relationship.find_related(issue, audit) self.assertIsNotNone(relationship) self.assertEqual(audit.context_id, issue.context_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 modify_assignee(self, obj, email, new_roles): """Modfiy assignee type. Args: obj: Object email: Person's email new_role: New roles for AssigneeType """ person = models.Person.query.filter_by(email=email).first() ac_roles = { acr_name: acr_id for acr_id, acr_name in get_custom_roles_for(obj.type).items() } self.api.modify_object(obj, { "access_control_list": [ acl_helper.get_acl_json(ac_roles[role], person.id) for role in new_roles ] })
def test_evidence_acl(self): """Test evidence with ACR creation""" person = factories.PersonFactory() acr_class = all_models.AccessControlRole acr = acr_class.query.filter(acr_class.name == 'Admin', acr_class.object_type == 'Evidence').one() evidence = factories.EvidenceFactory( title='Simple title', kind=all_models.Evidence.URL, link='simple_url.test', access_control_list=[ acl_helper.get_acl_json(acr.id, person.id) ] ) acl_class = all_models.AccessControlList acl = acl_class.query.filter( acl_class.object_id == evidence.id).one() self.assertTrue(acl)
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 test_revision_access(self): """Check if creator can access the right revision objects.""" def gen(title, extra_data=None): """Generates requirement.""" requirement_content = {"title": title, "context": None} if extra_data: requirement_content.update(**extra_data) return self.object_generator.generate_object( all_models.Requirement, data={"requirement": requirement_content} )[1] def check(obj, expected): """Check that how many revisions of an object current user can see.""" response = self.api.get_query( all_models.Revision, "resource_type={}&resource_id={}".format(obj.type, obj.id) ) self.assertEqual(response.status_code, 200) self.assertEqual( len(response.json['revisions_collection']['revisions']), expected ) self.api.set_user(self.users["admin"]) obj_1 = gen("Test Requirement 1") self.api.set_user(self.users["creator"]) acr_id = all_models.AccessControlRole.query.filter_by( object_type="Requirement", name="Admin" ).first().id linked_acl = { "access_control_list": [ acl_helper.get_acl_json(acr_id, self.users["creator"].id)], } check(obj_1, 0) obj_2 = gen("Test Requirement 2", linked_acl) obj2_acl = obj_2.access_control_list[0][1] check(obj_2, 1) check(obj2_acl, 1)
def _post_control(self, id_, person_id, collection=False): """Helper function for posting a control""" title = random_str(prefix="Control - ") control = { "control": { "title": title, "type": "Control", "context": None, "access_control_list": [ acl_helper.get_acl_json(id_, person_id) ] }, } response = self.api.post( all_models.Control, [control] if collection else control) assert response.status_code == 200 or response.status_code == 201, \ "Control with acl not created successfully {}".format(response.status) if collection: return response.json[0][1] return response.json
def test_issue_audit_creator(self, user_email): """Test automapping issue to audit for {}. This test should check if the issue is automapped to an audit when a creator raises an issue on an assessment that belongs to the given audit. """ user = all_models.Person.query.filter_by(email=user_email).one() self.api.set_user(user) assessment = all_models.Assessment.query.first() response = self.api.post(all_models.Issue, data=[{ "issue": { "status": "Draft", "access_control_list": [ acl_helper.get_acl_json(self.issue_admin_role.id, user.id)], "assessment": { "type": assessment.type, "id": assessment.id, # Fields sent by the request but not actually needed. # "title": "assessment", # "title_singular": "Assessment", # "table_singular": "assessment" }, "title": "aa", "context": None, # Setting the context would make the test match the front-end # change that was reverted in 577afd6686 # "context": { # "type": assessment.context.type, # "id": assessment.context.id, # }, } }]) self.assert200(response) issue = all_models.Issue.query.first() audit = all_models.Audit.query.first() self.assertIsNotNone(issue) relationship = all_models.Relationship.find_related(issue, audit) self.assertIsNotNone(relationship) self.assertEqual(audit.context_id, issue.context_id)
def setUp(self): super(TestPermissionsOnAssessmentTemplate, self).setUp() self.api = Api() editor = all_models.AccessControlRole.query.filter( all_models.AccessControlRole.name == "Program Editors" ).one() self.generator = ObjectGenerator() _, self.editor = self.generator.generate_person( user_role="Creator" ) _, program = self.generator.generate_object(all_models.Program, { "access_control_list": [ acl_helper.get_acl_json(editor.id, self.editor.id) ] }) program_id = program.id _, audit = self.generator.generate_object( all_models.Audit, { "title": "Assessment Template test Audit", "program": {"id": program_id}, "status": "Planned" }, ) audit_id = audit.id generated_at = self.generator.generate_object( all_models.AssessmentTemplate, self._get_assessment_template_base("Template", audit) ) self.assessment_template_resp, assessment_template = generated_at assessment_template_id = assessment_template.id self.api.set_user(self.editor) self.perms_data = self.api.client.get("/permissions").json self.audit = all_models.Audit.query.get(audit_id) self.assessment_template = all_models.AssessmentTemplate.query.get( assessment_template_id)
def create_test_cases(self): def person_dict(person_id): return { "href": "/api/people/%d" % person_id, "id": person_id, "type": "Person" } role_id = all_models.AccessControlRole.query.filter( all_models.AccessControlRole.name == "Task Assignees", all_models.AccessControlRole.object_type == "TaskGroupTask", ).one().id self.one_time_workflow_1 = { "title": "one time test workflow", "description": "some test workflow", "notify_on_change": True, # admin will be current user with id == 1 "task_groups": [{ "title": "one time task group", "contact": person_dict(self.random_people[2].id), "task_group_tasks": [{ "title": "task 1", "description": "some task", "access_control_list": [ acl_helper.get_acl_json(role_id, self.random_people[0].id) ], "start_date": date(2015, 5, 1), # friday "end_date": date(2015, 5, 5), }, { "title": "task 2", "description": "some task", "access_control_list": [ acl_helper.get_acl_json(role_id, self.random_people[1].id) ], "start_date": date(2015, 5, 4), "end_date": date(2015, 5, 7), }], "task_group_objects": self.random_objects[:2] }, { "title": "another one time task group", "contact": person_dict(self.random_people[2].id), "task_group_tasks": [{ "title": "task 1 in tg 2", "description": "some task", "access_control_list": [ acl_helper.get_acl_json(role_id, self.random_people[0].id) ], "start_date": date(2015, 5, 8), # friday "end_date": date(2015, 5, 12), }, { "title": "task 2 in tg 2", "description": "some task", "access_control_list": [ acl_helper.get_acl_json(role_id, self.random_people[2].id) ], "start_date": date(2015, 5, 1), # friday "end_date": date(2015, 5, 5), }], "task_group_objects": [] }] } user = Person.query.filter(Person.email == "*****@*****.**").one().id self.one_time_workflow_single_person = { "title": "one time test workflow", "notify_on_change": True, "description": "some test workflow", # admin will be current user with id == 1 "task_groups": [{ "title": "one time task group", "contact": person_dict(user), "task_group_tasks": [{ "title": u"task 1 \u2062 WITH AN UMBRELLA ELLA ELLA. \u2062", "description": "some task. ", "access_control_list": [ acl_helper.get_acl_json(role_id, user) ], "start_date": date(2015, 5, 1), # friday "end_date": date(2015, 5, 5), }, { "title": "task 2", "description": "some task", "access_control_list": [ acl_helper.get_acl_json(role_id, user) ], "start_date": date(2015, 5, 4), "end_date": date(2015, 5, 7), }], "task_group_objects": self.random_objects[:2] }, { "title": "another one time task group", "contact": person_dict(user), "task_group_tasks": [{ "title": u"task 1 \u2062 WITH AN UMBRELLA ELLA ELLA. \u2062", "description": "some task", "access_control_list": [ acl_helper.get_acl_json(role_id, user) ], "start_date": date(2015, 5, 8), # friday "end_date": date(2015, 5, 12), }, { "title": "task 2 in tg 2", "description": "some task", "access_control_list": [ acl_helper.get_acl_json(role_id, user) ], "start_date": date(2015, 5, 1), # friday "end_date": date(2015, 5, 5), }], "task_group_objects": [] }] }
def init_objects(self, test_case_name): """ Create a Program and a Mapped object for a given test case """ # Create a program test_case = self.test_cases[test_case_name] creator = self.people.get('creator') self.api.set_user(creator) random_title = factories.random_str() person = self.people.get(test_case_name) acl = [acl_helper.get_acl_json(self.ac_roles["Program Managers"], creator.id)] if "program_role" in test_case: ac_role_id = self.ac_roles[test_case["program_role"]] acl.append(acl_helper.get_acl_json(ac_role_id, person.id)) response = self.api.post(all_models.Program, { "program": { "title": random_title, "context": None, "access_control_list": acl }, }) self.assertEqual(response.status_code, 201, "Creator can't create program") context_id = response.json.get("program").get("context").get("id") program_id = response.json.get("program").get("id") # Use admin owner role to map it with system acr_id = all_models.AccessControlRole.query.filter_by( object_type="System", name="Admin" ).first().id self.objects["program"] = all_models.Program.query.get(program_id) # Create an object: for obj in ("mapped_object", "unrelated"): random_title = factories.random_str() response = self.api.post(all_models.System, { "system": { "title": random_title, "context": None, "access_control_list": [ acl_helper.get_acl_json(acr_id, creator.id)], }, }) self.assertEqual(response.status_code, 201, "Creator can't create object") system_id = response.json.get("system").get("id") self.objects[obj] = all_models.System.query.get(system_id) # Map Object to Program response = self.api.post(all_models.Relationship, { "relationship": {"source": { "id": program_id, "type": "Program" }, "destination": { "id": self.objects["mapped_object"].id, "type": "System" }, "context": None}, }) self.assertEqual(response.status_code, 201, "Creator can't map object to program") # Map people to Program: if test_case_name != "notmapped": person = self.people.get(test_case_name) response = self.api.post(all_models.ObjectPerson, {"object_person": { "person": { "id": person.id, "type": "Person", "href": "/api/people/{}".format(person.id), }, "personable": { "type": "Program", "href": "/api/programs/{}".format(program_id), "id": program_id, }, "context": { "type": "Context", "id": context_id, "href": "/api/contexts/{}".format(context_id) }}})
def _create_test_cases_data(self): """Create test cases data: for object generation, expected data for checks""" def person_dict(person_id): """Return person data""" return { "href": "/api/people/%d" % person_id, "id": person_id, "type": "Person" } wf_admin_role_id = { n: i for (i, n) in role.get_custom_roles_for(Workflow.__name__).iteritems() }['Admin'] self.workflow_active = { "title": "workflow active title", "description": "workflow active description", "access_control_list": [ acl_helper.get_acl_json(wf_admin_role_id, self.person_1.id)], "notify_on_change": False, } self.task_group_active = { "title": "task group active title", "contact": person_dict(self.person_1.id), } self.task_group_tasks_active = [{ "title": "task active title 1", "description": "task active description 1", "contact": person_dict(self.person_1.id), "start_date": "07/01/2016", "end_date": "07/06/2016", }, { "title": "task active title 2", "description": "task active description 2", "contact": person_dict(self.person_1.id), "start_date": "07/07/2016", "end_date": "07/12/2016", }, { "title": "task active title 3", "description": "task active description 3", "contact": person_dict(self.person_1.id), "start_date": "07/13/2016", "end_date": "07/18/2016", }, { "title": "task active title 4", "description": "task active description 4", "contact": person_dict(self.person_1.id), "start_date": "07/19/2016", "end_date": "07/24/2016", }, { "title": "task active title 5", "description": "task active description 5", "contact": person_dict(self.person_1.id), "start_date": "07/25/2016", "end_date": "07/30/2016", }] # Active cycle tasks which should be generated from previous structure # at the beginning of each test self.generated_cycle_tasks_active = { "CYCLETASK-1": { "title": self.task_group_tasks_active[0]["title"], "description": self.task_group_tasks_active[0]["description"], "start_date": "2016-07-01", "end_date": "2016-07-06", "finished_date": "None", "verified_date": "None", "status": "Assigned" }, "CYCLETASK-2": { "title": self.task_group_tasks_active[1]["title"], "description": self.task_group_tasks_active[1]["description"], "start_date": "2016-07-07", "end_date": "2016-07-12", "finished_date": "None", "verified_date": "None", "status": "Declined" }, "CYCLETASK-3": { "title": self.task_group_tasks_active[2]["title"], "description": self.task_group_tasks_active[2]["description"], "start_date": "2016-07-13", "end_date": "2016-07-18", "finished_date": "None", "verified_date": "None", "status": "In Progress" }, "CYCLETASK-4": { "title": self.task_group_tasks_active[3]["title"], "description": self.task_group_tasks_active[3]["description"], "start_date": "2016-07-19", "end_date": "2016-07-22", "finished_date": "2016-07-01", "verified_date": "None", "status": "Finished" }, "CYCLETASK-5": { "title": self.task_group_tasks_active[4]["title"], "description": self.task_group_tasks_active[4]["description"], "start_date": "2016-07-25", "end_date": "2016-07-29", "finished_date": "2016-07-01", "verified_date": "2016-07-01", "status": "Verified" } } self.workflow_historical = { "title": "workflow historical title", "description": "workflow historical description", "access_control_list": [ acl_helper.get_acl_json(wf_admin_role_id, self.person_1.id)], "notify_on_change": False, } self.task_group_historical = { "title": "task group historical title", "contact": person_dict(self.person_1.id), } self.task_group_tasks_historical = [{ "title": "task historical title 1", "description": "task historical description 1", "contact": person_dict(self.person_1.id), "start_date": "05/01/2014", "end_date": "05/06/2014", }, { "title": "task historical title 2", "description": "task historical description 2", "contact": person_dict(self.person_1.id), "start_date": "05/07/2014", "end_date": "05/12/2014", }, { "title": "task historical title 3", "description": "task historical description 3", "contact": person_dict(self.person_1.id), "start_date": "05/13/2014", "end_date": "05/18/2014", }, { "title": "task historical title 4", "description": "task historical description 4", "contact": person_dict(self.person_1.id), "start_date": "05/19/2014", "end_date": "05/24/2014", }, { "title": "task historical title 5", "description": "task historical description 5", "contact": person_dict(self.person_1.id), "start_date": "05/25/2014", "end_date": "05/30/2014", }, ] # Historical cycle tasks which should be generated from previous structure # at the beginning of each test. self.generated_cycle_tasks_historical = { "CYCLETASK-6": { "title": self.task_group_tasks_historical[0]["title"], "description": self.task_group_tasks_historical[0]["description"], "start_date": "2014-05-01", "end_date": "2014-05-06", "finished_date": "None", "verified_date": "None", "status": "Assigned" }, "CYCLETASK-7": { "title": self.task_group_tasks_historical[1]["title"], "description": self.task_group_tasks_historical[1]["description"], "start_date": "2014-05-07", "end_date": "2014-05-12", "finished_date": "None", "verified_date": "None", "status": "Declined" }, "CYCLETASK-8": { "title": self.task_group_tasks_historical[2]["title"], "description": self.task_group_tasks_historical[2]["description"], "start_date": "2014-05-13", "end_date": "2014-05-16", "finished_date": "None", "verified_date": "None", "status": "In Progress" }, "CYCLETASK-9": { "title": self.task_group_tasks_historical[3]["title"], "description": self.task_group_tasks_historical[3]["description"], "start_date": "2014-05-19", "end_date": "2014-05-23", "finished_date": "2014-05-01", "verified_date": "None", "status": "Finished" }, "CYCLETASK-10": { "title": self.task_group_tasks_historical[4]["title"], "description": self.task_group_tasks_historical[4]["description"], "start_date": "2014-05-23", "end_date": "2014-05-30", "finished_date": "2014-05-01", "verified_date": "2014-05-01", "status": "Verified" } } # Expected cycle tasks which should be created in correct cycle task update # case. It is needed for most tests. self.expected_cycle_task_correct = { "CYCLETASK-1": { "title": self.task_group_tasks_active[0]["title"] + " one", "description": self.task_group_tasks_active[0]["description"] + " one", "start_date": "2016-06-01", "end_date": "2016-06-06", "finished_date": "None", "verified_date": "None", "status": "Assigned" }, "CYCLETASK-2": { "title": self.task_group_tasks_active[1]["title"] + " two", "description": self.task_group_tasks_active[1]["description"] + " two", "start_date": "2016-06-07", "end_date": "2016-06-12", "finished_date": "None", "verified_date": "None", "status": "Declined" }, "CYCLETASK-3": { "title": self.task_group_tasks_active[2]["title"] + " three", "description": self.task_group_tasks_active[2]["description"] + " three", "start_date": "2016-06-13", "end_date": "2016-06-18", "finished_date": "None", "verified_date": "None", "status": "In Progress" }, "CYCLETASK-4": { "title": self.task_group_tasks_active[3]["title"] + " four", "description": self.task_group_tasks_active[3]["description"] + " four", "start_date": "2016-06-19", "end_date": "2016-06-24", "finished_date": "2016-07-19", "verified_date": "None", "status": "Finished" }, "CYCLETASK-5": { "title": self.task_group_tasks_active[4]["title"] + " five", "description": self.task_group_tasks_active[4]["description"] + " five", "start_date": "2016-06-25", "end_date": "2016-06-30", "finished_date": "2016-07-25", "verified_date": "2016-08-30", "status": "Verified" }, "CYCLETASK-6": { "title": self.task_group_tasks_historical[0]["title"] + " one", "description": self.task_group_tasks_historical[0]["description"] + " one", "start_date": "2014-04-01", "end_date": "2014-04-06", "finished_date": "None", "verified_date": "None", "status": "Assigned" }, "CYCLETASK-7": { "title": self.task_group_tasks_historical[1]["title"] + " two", "description": self.task_group_tasks_historical[1]["description"] + " two", "start_date": "2014-04-07", "end_date": "2014-04-12", "finished_date": "None", "verified_date": "None", "status": "Declined" }, "CYCLETASK-8": { "title": self.task_group_tasks_historical[2]["title"] + " three", "description": self.task_group_tasks_historical[2]["description"] + " three", "start_date": "2014-04-13", "end_date": "2014-04-18", "finished_date": "None", "verified_date": "None", "status": "In Progress" }, "CYCLETASK-9": { "title": self.task_group_tasks_historical[3]["title"] + " four", "description": self.task_group_tasks_historical[3]["description"] + " four", "start_date": "2014-04-19", "end_date": "2014-04-24", "finished_date": "2014-05-19", "verified_date": "None", "status": "Finished" }, "CYCLETASK-10": { "title": self.task_group_tasks_historical[4]["title"] + " five", "description": self.task_group_tasks_historical[4]["description"] + " five", "start_date": "2014-04-25", "end_date": "2014-04-30", "finished_date": "2014-05-25", "verified_date": "2014-06-30", "status": "Verified" } } # This is an error message which should be shown during # test_cycle_task_create_error test self.expected_create_error = { 'Cycle Task': { 'row_errors': {errors.CREATE_INSTANCE_ERROR.format(line=13)} } } # Below is expected date errors for test_cycle_task_date_error. They should # be shown during date validator's tests. self.expected_date_error = { 'Cycle Task': { 'row_errors': { errors.INVALID_START_END_DATES.format( line=3, start_date="Start Date", end_date="End Date", ), errors.INVALID_STATUS_DATE_CORRELATION.format( line=4, date="Actual Finish Date", deny_states=DENY_FINISHED_DATES_STATUSES_STR, ), errors.INVALID_STATUS_DATE_CORRELATION.format( line=6, date="Actual Verified Date", deny_states=DENY_VERIFIED_DATES_STATUSES_STR, ), errors.INVALID_START_END_DATES.format( line=7, start_date="Actual Finish Date", end_date="Actual Verified Date", ), errors.INVALID_START_END_DATES.format( line=8, start_date="Start Date", end_date="End Date", ), }, } } # Below is expected cycle-tasks data which should appear in test DB after # test_cycle_task_date_error run self.expected_cycle_task_date_error = dict() self.expected_cycle_task_date_error.update( self.generated_cycle_tasks_active) self.expected_cycle_task_date_error.update( self.generated_cycle_tasks_historical) self.expected_cycle_task_date_error["CYCLETASK-9"] = ( self.expected_cycle_task_correct["CYCLETASK-9"]) self.expected_cycle_task_date_error["CYCLETASK-10"] = ( self.expected_cycle_task_correct["CYCLETASK-10"]) # Expected error message which should be shown after # test_cycle_task_permission_error run self.expected_permission_error = { 'Cycle Task': { 'block_errors': {errors.PERMISSION_ERROR.format(line=2)} } }
def test_task_count(self, is_verification_needed, transitions): """Test person task counts. This tests checks for correct task counts - with inactive workflows and - with overdue tasks - without overdue tasks - with finished overdue tasks The four checks are done in a single test due to complex differences between tests that make ddt cumbersome and the single test also improves integration test performance due to slow workflow setup stage. """ # pylint: disable=too-many-locals user = all_models.Person.query.first() dummy_user = factories.PersonFactory() user_id = user.id role_id = all_models.AccessControlRole.query.filter( all_models.AccessControlRole.name == "Task Assignees", all_models.AccessControlRole.object_type == "TaskGroupTask", ).one().id secondary_role_id = all_models.AccessControlRole.query.filter( all_models.AccessControlRole.name == "Task Secondary Assignees", all_models.AccessControlRole.object_type == "TaskGroupTask", ).one().id one_time_workflow = { "title": "Person resource test workflow", "notify_on_change": True, "description": "some test workflow", "owners": [create_stub(user)], "is_verification_needed": is_verification_needed, "task_groups": [{ "title": "one time task group", "contact": create_stub(user), "task_group_tasks": [{ "title": "task 1", "description": "some task", "access_control_list": [ acl_helper.get_acl_json(role_id, user.id), acl_helper.get_acl_json(secondary_role_id, user.id) ], "start_date": date(2017, 5, 5), "end_date": date(2017, 8, 15), }, { "title": "task 2", "description": "some task 3", "access_control_list": [ acl_helper.get_acl_json(role_id, user.id), acl_helper.get_acl_json(secondary_role_id, user.id), acl_helper.get_acl_json(secondary_role_id, dummy_user.id) ], "start_date": date(2017, 5, 5), "end_date": date(2017, 9, 16), }, { "title": "task 3", "description": "some task 4", "access_control_list": [ acl_helper.get_acl_json(role_id, user.id), acl_helper.get_acl_json(role_id, dummy_user.id) ], "start_date": date(2017, 6, 5), "end_date": date(2017, 10, 16), }, { "title": "dummy task 4", # task should not counted "description": "some task 4", "access_control_list": [ acl_helper.get_acl_json(role_id, dummy_user.id)], "start_date": date(2017, 6, 5), "end_date": date(2017, 11, 17), }, { "title": "dummy task 5", # task should not counted "description": "some task 4", "access_control_list": [ acl_helper.get_acl_json(role_id, dummy_user.id)], "start_date": date(2017, 6, 5), "end_date": date(2017, 11, 18), }], "task_group_objects": [] }] } inactive_workflow = { "title": "Activated workflow with archived cycles", "notify_on_change": True, "description": "Extra test workflow", "owners": [create_stub(user)], "task_groups": [{ "title": "Extra task group", "contact": create_stub(user), "task_group_tasks": [{ "title": "not counted existing task", "description": "", "access_control_list": [ acl_helper.get_acl_json(role_id, user.id)], "start_date": date(2017, 5, 5), "end_date": date(2017, 8, 15), }], "task_group_objects": [] }] } with freeze_time("2017-10-16 05:09:10"): self.client.get("/login") # Activate normal one time workflow _, workflow = self.generator.generate_workflow(one_time_workflow) _, cycle = self.generator.generate_cycle(workflow) tasks = {t.title: t for t in cycle.cycle_task_group_object_tasks} _, workflow = self.generator.activate_workflow(workflow) # Activate and close the inactive workflow _, workflow = self.generator.generate_workflow(inactive_workflow) _, cycle = self.generator.generate_cycle(workflow) _, workflow = self.generator.activate_workflow(workflow) self.generator.modify_object(cycle, data={"is_current": False}) with freeze_time("2017-7-16 07:09:10"): self.client.get("/login") response = self.client.get("/api/people/{}/task_count".format(user_id)) self.assertEqual( response.json, {"open_task_count": 3, "has_overdue": False} ) with freeze_time("2017-10-16 08:09:10"): # same day as task 3 end date self.client.get("/login") response = self.client.get("/api/people/{}/task_count".format(user_id)) self.assertEqual( response.json, {"open_task_count": 3, "has_overdue": True} ) for task, status, count, overdue, my_work_count in transitions: self.generator.modify_object(tasks[task], data={"status": status}) task_count_response = \ self.client.get("/api/people/{}/task_count".format(user_id)) my_work_count_response = \ self.client.get("/api/people/{}/my_work_count".format(user_id)) self.assertEqual( task_count_response.json, {"open_task_count": count, "has_overdue": overdue} ) self.assertEqual( my_work_count_response.json["CycleTaskGroupObjectTask"], my_work_count )
def test_task_count_multiple_wfs(self): """Test task count with both verified and non verified workflows. This checks task counts with 4 tasks 2017, 8, 15 - verification needed 2017, 11, 18 - verification needed 2017, 8, 15 - No verification needed 2017, 11, 18 - No verification needed """ user = all_models.Person.query.first() user_id = user.id role_id = all_models.AccessControlRole.query.filter( all_models.AccessControlRole.name == "Task Assignees", all_models.AccessControlRole.object_type == "TaskGroupTask", ).one().id workflow_template = { "title": "verified workflow", "owners": [create_stub(user)], "is_verification_needed": True, "task_groups": [{ "title": "one time task group", "contact": create_stub(user), "task_group_tasks": [{ "title": "task 1", "description": "some task", "access_control_list": [ acl_helper.get_acl_json(role_id, user.id)], "start_date": date(2017, 5, 5), "end_date": date(2017, 8, 15), }, { "title": "dummy task 5", "description": "some task 4", "access_control_list": [ acl_helper.get_acl_json(role_id, user.id)], "start_date": date(2017, 6, 5), "end_date": date(2017, 11, 18), }], "task_group_objects": [] }] } with freeze_time("2017-10-16 05:09:10"): self.client.get("/login") verified_workflow = workflow_template.copy() verified_workflow["is_verification_needed"] = True _, workflow = self.generator.generate_workflow(verified_workflow) _, cycle = self.generator.generate_cycle(workflow) verified_tasks = { task.title: task for task in cycle.cycle_task_group_object_tasks } _, workflow = self.generator.activate_workflow(workflow) non_verified_workflow = workflow_template.copy() non_verified_workflow["is_verification_needed"] = False _, workflow = self.generator.generate_workflow(non_verified_workflow) _, cycle = self.generator.generate_cycle(workflow) non_verified_tasks = { task.title: task for task in cycle.cycle_task_group_object_tasks } _, workflow = self.generator.activate_workflow(workflow) with freeze_time("2017-7-16 07:09:10"): self.client.get("/login") response = self.client.get("/api/people/{}/task_count".format(user_id)) self.assertEqual( response.json, {"open_task_count": 4, "has_overdue": False} ) with freeze_time("2017-10-16 08:09:10"): self.client.get("/login") response = self.client.get("/api/people/{}/task_count".format(user_id)) self.assertEqual( response.json, {"open_task_count": 4, "has_overdue": True} ) # transition 1, task that needs verification goes to finished state. This # transition should not change anything self.generator.modify_object( verified_tasks["task 1"], data={"status": "Finished"} ) response = self.client.get("/api/people/{}/task_count".format(user_id)) self.assertEqual( response.json, {"open_task_count": 4, "has_overdue": True} ) # transition 2, task that needs verification goes to verified state. This # transition should reduce task count. self.generator.modify_object( verified_tasks["task 1"], data={"status": "Verified"} ) response = self.client.get("/api/people/{}/task_count".format(user_id)) self.assertEqual( response.json, {"open_task_count": 3, "has_overdue": True} ) # transition 3, task that does not need verification goes into Finished # state. This transition should reduce task count and remove all overdue # tasks self.generator.modify_object( non_verified_tasks["task 1"], data={"status": "Finished"} ) response = self.client.get("/api/people/{}/task_count".format(user_id)) self.assertEqual( response.json, {"open_task_count": 2, "has_overdue": False} )
def setUp(self): super(TestTaskDueNotifications, self).setUp() self.api = Api() self.wf_generator = WorkflowsGenerator() self.object_generator = ObjectGenerator() models.Notification.query.delete() self._fix_notification_init() self.random_objects = self.object_generator.generate_random_objects(2) _, self.user = self.object_generator.generate_person( user_role="Administrator") role_id = models.all_models.AccessControlRole.query.filter( models.all_models.AccessControlRole.name == "Task Assignees", models.all_models.AccessControlRole.object_type == "TaskGroupTask", ).one().id self.one_time_workflow = { "title": "one time test workflow", "notify_on_change": True, "description": "some test workflow", "is_verification_needed": False, # admin will be current user with id == 1 "task_groups": [{ "title": "one time task group", "contact": { "href": "/api/people/{}".format(self.user.id), "id": self.user.id, "type": "Person", }, "task_group_tasks": [{ "title": "task 1", "description": "some task", "access_control_list": [ acl_helper.get_acl_json(role_id, self.user.id)], "start_date": date(2017, 5, 15), "end_date": date(2017, 6, 11), }, { "title": "task 2", "description": "some task 2", "access_control_list": [ acl_helper.get_acl_json(role_id, self.user.id)], "start_date": date(2017, 5, 8), "end_date": date(2017, 6, 12), }, { "title": "task 3", "description": "some task 3", "access_control_list": [ acl_helper.get_acl_json(role_id, self.user.id)], "start_date": date(2017, 5, 31), "end_date": date(2017, 6, 13), }, { "title": "task 4", "description": "some task 4", "access_control_list": [ acl_helper.get_acl_json(role_id, self.user.id)], "start_date": date(2017, 6, 2), "end_date": date(2017, 6, 14), }, { "title": "task 5", "description": "some task 5", "access_control_list": [ acl_helper.get_acl_json(role_id, self.user.id)], "start_date": date(2017, 6, 8), "end_date": date(2017, 6, 15), }], "task_group_objects": self.random_objects }] }