def test_comments_delete(self, object_factory): """Test if {} deleted along with comments.""" obj = object_factory() comment_first = factories.CommentFactory() comment_second = factories.CommentFactory() comment_ids = (comment_first.id, comment_second.id) relationship_first = factories.RelationshipFactory( source=comment_first, destination=obj) relationship_second = factories.RelationshipFactory( source=obj, destination=comment_second) rel_ids = (relationship_first.id, relationship_second.id) result = self.api.delete(obj) self.assertEqual(result.status_code, 200) for rel_id in rel_ids: relationship = all_models.Relationship.query.get(rel_id) self.assertEqual(relationship, None) for comment_id in comment_ids: comment = all_models.Comment.query.get(comment_id) self.assertEqual(comment, None) delete_revision = all_models.Revision.query.filter( all_models.Revision.resource_id == comment_id, all_models.Revision.resource_type == "Comment", all_models.Revision.action == "deleted").first() self.assertNotEqual(delete_revision, None)
def setup_objects(self): """Sets up all the objects needed by the tests""" objects = self.objects # Program objects['program'] = program = factories.ProgramFactory( title="A Program") # Controls objects['controls'] = controls = [ factories.ControlFactory(title="My First Control"), factories.ControlFactory(title="My Second Control") ] # Audit objects['audit'] = audit = factories.AuditFactory( program=objects['program'], access_control_list=[{ "ac_role_id": self.audit_roles['Auditors'].id, "person": { "id": self.people['created_auditor'].id }, }, { "ac_role_id": self.audit_roles['Audit Captains'].id, "person": { "id": self.people['created_captain'].id }, }]) factories.RelationshipFactory(source=program, destination=audit) # Assessment template objects['assessment_template'] = factories.AssessmentTemplateFactory() # Assessment objects['assessment'] = factories.AssessmentFactory(audit=audit) # Snapshot objects['snapshots'] = self._create_snapshots(audit, controls) for snapshot in objects['snapshots']: factories.RelationshipFactory(source=audit, destination=snapshot) # Issues objects['issue'] = factories.IssueFactory( access_control_list=[{ "ac_role_id": self.issue_roles['Admin'].id, "person": { "id": self.people['issue_admin'].id }, }]) # Comments objects['comment'] = factories.CommentFactory() objects['issue_comment'] = factories.CommentFactory() # Documents objects['issue_document'] = factories.DocumentFactory() # Evidence objects['evidence'] = factories.EvidenceUrlFactory()
def test_adding_comment_to_issue(self, update_issue_mock, url_builder_mock): """Test adding comment to issue.""" iti = factories.IssueTrackerIssueFactory( enabled=True, issue_tracked_obj=factories.IssueFactory()) comment = factories.CommentFactory(description="test comment") expected_result = { "comment": u"A new comment is added by 'Example User' to the 'Issue': " u"'test comment'.\nUse the following to link to get more " u"information from the GGRC 'Issue'. Link - " u"http://issue_url.com" } with mock.patch.object(settings, "ISSUE_TRACKER_ENABLED", True): self.api.post( all_models.Relationship, { "relationship": { "source": { "id": iti.issue_tracked_obj.id, "type": "Issue" }, "destination": { "id": comment.id, "type": "comment" }, "context": None }, }) url_builder_mock.assert_called_once() update_issue_mock.assert_called_with(iti.issue_id, expected_result)
def test_last_comment_value(self): """Test proper value in last_comment field""" with factories.single_commit(): c_task = wf_factories.CycleTaskGroupObjectTaskFactory() c_task_id = c_task.id comment_1 = factories.CommentFactory(description=factories.random_str()) comment_2 = factories.CommentFactory(description=factories.random_str()) comment_2_id = comment_2.id factories.RelationshipFactory(source=c_task, destination=comment_1) factories.RelationshipFactory(source=c_task, destination=comment_2) self.compute_attributes() comment_2 = all_models.Comment.query.get(comment_2_id) c_task = all_models.CycleTaskGroupObjectTask.query.get(c_task_id) self.assertEqual(c_task.last_comment, comment_2.description)
def _setup_comment(self): """Crate and map comment""" with factories.single_commit(): comment = factories.CommentFactory(description="Hey!") parent = db.session.query(self.parent.__class__).get(self.parent_id) factories.RelationshipFactory(source=parent, destination=comment) return comment.id
def read_document_comment(self): """Read comments mapped to document""" doc_id = self._setup_document() document = all_models.Document.query.get(doc_id) with factories.single_commit(): comment = factories.CommentFactory(description=factories.random_str()) factories.RelationshipFactory(source=document, destination=comment) query_request_data = [ { "fields": [], "filters": { "expression": { "object_name": "Document", "op": { "name": "relevant" }, "ids": [document.id] } }, "object_name": "Comment", } ] response = self.api.send_request( self.api.client.post, data=query_request_data, api_link="/query" ) return response
def test_preconditions_failed_with_present_mandatory_comment(self): """No preconditions failed if comment required by CA is present.""" ca = CustomAttributeMock( self.assessment, attribute_type="Dropdown", dropdown_parameters=("foo,comment_required", "0,1"), value=None, # the value is made with generator to store revision too ) _, ca.value = GENERATOR.generate_custom_attribute_value( custom_attribute_id=ca.definition.id, attributable=self.assessment, attribute_value="comment_required", ) comment = factories.CommentFactory( assignee_type="Assessor", description="Mandatory comment", ) comment.custom_attribute_revision_upd({ "custom_attribute_revision_upd": { "custom_attribute_value": { "id": ca.value.id, }, }, }) factories.RelationshipFactory( source=self.assessment, destination=comment, ) preconditions_failed = self.assessment.preconditions_failed self.assertEqual(preconditions_failed, False) self.assertFalse(ca.value.preconditions_failed)
def read_comments(self): """Read comments mapped to evidence""" evidence = all_models.Evidence.query.get(self.evidence_id) with factories.single_commit(): comment = factories.CommentFactory( description=factories.random_str()) factories.RelationshipFactory(source=evidence, destination=comment) query_request_data = [{ "fields": [], "filters": { "expression": { "object_name": "Evidence", "op": { "name": "relevant" }, "ids": [evidence.id] } }, "object_name": "Comment", }] response = self.api.send_request(self.api.client.post, data=query_request_data, api_link="/query") return response
def read_comment(self): """Read comments mapped to cycle task""" cycle_task = all_models.CycleTaskGroupObjectTask.query.get( self.cycle_task_id) with factories.single_commit(): comment = factories.CommentFactory( description=factories.random_str()) factories.RelationshipFactory(source=cycle_task, destination=comment) query_request_data = [{ "fields": [], "filters": { "expression": { "object_name": "CycleTaskGroupObjectTask", "op": { "name": "relevant" }, "ids": [cycle_task.id] } }, "object_name": "Comment", }] response = self.api.send_request(self.api.client.post, data=query_request_data, api_link="/query") return response
def test_handle_one_comment(self, send_email_mock): """Test handling of mapped comment.""" with factories.single_commit(): person = factories.PersonFactory(email="*****@*****.**") obj = factories.ProductFactory(title="Product1") comment = factories.CommentFactory( description=u"One <a href=\"mailto:[email protected]\"></a>", ) comment.modified_by_id = person.id comment.created_at = datetime.datetime(2018, 1, 10, 7, 31, 42) url = urljoin(get_url_root(), utils.view_url_for(obj)) people_mentions.handle_comment_mapped(obj, [comment]) expected_title = (u"[email protected] mentioned you " u"on a comment within Product1") expected_body = ( u"[email protected] mentioned you on a comment within Product1 " u"at 01/09/2018 23:31:42 PST:\n" u"One <a href=\"mailto:[email protected]\"></a>\n") body = settings.EMAIL_MENTIONED_PERSON.render( person_mention={ "comments": [expected_body], "url": url, }) send_email_mock.assert_called_once_with(u"*****@*****.**", expected_title, body)
def test_handle_task_comment(self, send_email_mock): """Test handling of mapped comment to cycle task.""" with factories.single_commit(): person = factories.PersonFactory(email="*****@*****.**") obj = wf_factories.CycleTaskGroupObjectTaskFactory( slug=u"TSK-1", title=u"task1", ) comment = factories.CommentFactory( description=u"One <a href=\"mailto:[email protected]\"></a>", ) comment.modified_by_id = person.id comment.created_at = datetime.datetime(2018, 1, 10, 7, 31, 42) url = "http://localhost/dashboard#!task&query=%22task%20slug%22%3DTSK-1" people_mentions.handle_comment_mapped(obj, [comment]) expected_title = (u"[email protected] mentioned you " u"on a comment within task1") expected_body = ( u"[email protected] mentioned you on a comment within task1 " u"at 01/09/2018 23:31:42 PST:\n" u"One <a href=\"mailto:[email protected]\"></a>\n") body = settings.EMAIL_MENTIONED_PERSON.render( person_mention={ "comments": [expected_body], "url": url, }) send_email_mock.assert_called_once_with(u"*****@*****.**", expected_title, body)
def test_adding_comment_to_issue(self, update_issue_mock, url_builder_mock): """Test adding comment to issue.""" role = all_models.Role.query.filter( all_models.Role.name == "Administrator" ).one() with factories.single_commit(): client_user = factories.PersonFactory(name="Test User") rbac_factories.UserRoleFactory(role=role, person=client_user) self.api.set_user(client_user) self.client.get("/login") iti = factories.IssueTrackerIssueFactory( enabled=True, issue_tracked_obj=factories.IssueFactory() ) comment = factories.CommentFactory(description="test comment") expected_result = { "comment": params_builder.BaseIssueTrackerParamsBuilder.COMMENT_TMPL.format( author=client_user.name, comment=comment.description, model="Issue", link="http://issue_url.com", ) } with mock.patch.object(settings, "ISSUE_TRACKER_ENABLED", True): self.api.post(all_models.Relationship, { "relationship": { "source": {"id": iti.issue_tracked_obj.id, "type": "Issue"}, "destination": {"id": comment.id, "type": "comment"}, "context": None }, }) url_builder_mock.assert_called_once() update_issue_mock.assert_called_with(iti.issue_id, expected_result)
def setup_objects(self): """Sets up all the objects needed by the tests""" objects = self.objects # Program objects['program'] = factories.ProgramFactory(title="A Program") # Controls objects['controls'] = controls = [ factories.ControlFactory(title="My First Control"), factories.ControlFactory(title="My Second Control") ] # Audit objects['audit'] = audit = factories.AuditFactory( program=objects['program'], access_control_list=[{ "ac_role": self.audit_roles['Auditors'], "person": self.people['created_auditor'] }, { "ac_role": self.audit_roles['Audit Captains'], "person": self.people['created_captain'] }] ) # Assessment template objects['assessment_template'] = factories.AssessmentTemplateFactory() # Assessment objects['assessment'] = factories.AssessmentFactory(audit=audit) # Snapshot objects['snapshots'] = self._create_snapshots(audit, controls) # Issues objects['issue'] = factories.IssueFactory( access_control_list=[{ "ac_role": self.issue_roles['Admin'], "person": self.people['issue_admin'] }] ) # Comments objects['comment'] = factories.CommentFactory() objects['issue_comment'] = factories.CommentFactory() # Documents objects['document'] = factories.DocumentFactory() objects['issue_document'] = factories.DocumentFactory()
def test_search_by_new_comment(self): """Filter by added new comment and old comment exists""" slugs = [self.assessment.slug] desc = "321" new_comment = factories.CommentFactory(description=desc) factories.RelationshipFactory(source=new_comment, destination=self.assessment) self.assert_slugs("comment", self.comment.description, slugs) self.assert_slugs("comment", desc, slugs)
def test_filter_by_task_comment(self): """Test filter by comments""" task_id = self.generate_tasks_for_cycle(4)[0] comment_text = "123" task = all_models.CycleTaskGroupObjectTask.query.filter( all_models.CycleTaskGroupObjectTask.id == task_id ).one() comment = ggrc_factories.CommentFactory(description=comment_text) ggrc_factories.RelationshipFactory(source=task, destination=comment) self.assert_slugs("task comment", comment_text, [task.slug])
def test_handle_empty_comment(self, send_email_mock): """Test handling of mapped comment with no mention.""" with factories.single_commit(): person = factories.PersonFactory(email="*****@*****.**") obj = factories.ProductFactory(title="Product2") comment = factories.CommentFactory(description=u"test") comment.created_at = datetime.datetime(2018, 1, 10, 7, 31, 42) comment.modified_by_id = person.id people_mentions.handle_comment_mapped(obj, [comment]) send_email_mock.assert_not_called()
def setUp(self): super(TestCollection, self).setUp() self.clear_data() self.expected_ids = [] assessments = [factories.AssessmentFactory() for _ in range(10)] random.shuffle(assessments) for idx, assessment in enumerate(assessments): comment = factories.CommentFactory(description=str(idx)) factories.RelationshipFactory(source=assessment, destination=comment) self.expected_ids.append(assessment.id)
def setUp(self): super(TestExport, self).setUp() self.client.get("/login") self.headers = { 'Content-Type': 'application/json', "X-Requested-By": "GGRC", "X-export-view": "blocks", } extr_comment = factories.CommentFactory(description="bad_desc") extr_assessment = factories.AssessmentFactory() db.engine.execute( 'update assessments set ' 'updated_at = "2010-10-10", ' 'created_at = "2010-10-10";' ) factories.RelationshipFactory(source=extr_assessment, destination=extr_comment) self.comment = factories.CommentFactory(description="123") self.assessment = factories.AssessmentFactory() self.rel = factories.RelationshipFactory(source=self.comment, destination=self.assessment)
def test_ca_cleanup_on_obj_delete(self): """Test cleaning of fulltext and attributes tables on obj delete""" with factories.single_commit(): for _ in range(2): c_task = wf_factories.CycleTaskGroupObjectTaskFactory() comment = factories.CommentFactory( description=factories.random_str() ) factories.RelationshipFactory(source=c_task, destination=comment) self.compute_attributes() c_task = all_models.CycleTaskGroupObjectTask.query.first() last_comment_records = self.get_model_fulltext( "CycleTaskGroupObjectTask", "last_comment", [c_task.id] ) last_comment_attrs = self.get_model_ca( "CycleTaskGroupObjectTask", [c_task.id] ) self.assertEqual(last_comment_records.count(), 1) self.assertEqual(last_comment_attrs.count(), 1) response = self.api.delete(c_task) self.assert200(response) last_comment_records = self.get_model_fulltext( "CycleTaskGroupObjectTask", "last_comment", [c_task.id] ) last_comment_attrs = self.get_model_ca( "CycleTaskGroupObjectTask", [c_task.id] ) self.assertEqual(last_comment_attrs.count(), 0) self.assertEqual(last_comment_records.count(), 0) # Check that other records weren't affected task_ids = [task.id for task in all_models.CycleTaskGroupObjectTask.query.all()] last_comment_records = self.get_model_fulltext( "CycleTaskGroupObjectTask", "last_comment", task_ids ) last_comment_attrs = self.get_model_ca( "CycleTaskGroupObjectTask", task_ids, ) self.assertEqual(last_comment_records.count(), 1) self.assertEqual(last_comment_attrs.count(), 1)
def test_preconditions_failed_with_changed_value(self): """Preconditions failed and comment invalidated on update to CAV.""" ca = CustomAttributeMock( self.assessment, attribute_type="Dropdown", dropdown_parameters=("foo,comment_required", "0,1"), value=None, # the value is made with generator to store revision too ) _, ca.value = GENERATOR.generate_custom_attribute_value( custom_attribute_id=ca.definition.id, attributable=self.assessment, attribute_value="comment_required", ) comment = factories.CommentFactory( assignee_type="Assessor", description="Mandatory comment", ) comment.custom_attribute_revision_upd({ "custom_attribute_revision_upd": { "custom_attribute_value": { "id": ca.value.id, }, }, }) factories.RelationshipFactory( source=self.assessment, destination=comment, ) # new CA value not requiring comment self.assessment.custom_attribute_values = [{ "attribute_value": "foo", "custom_attribute_id": ca.definition.id, }] GENERATOR.api.modify_object(self.assessment, {}) # new CA value requiring comment; the old comment should be considered # invalid self.assessment.custom_attribute_values = [{ "attribute_value": "comment_required", "custom_attribute_id": ca.definition.id, }] GENERATOR.api.modify_object(self.assessment, {}) preconditions_failed = self.assessment.preconditions_failed self.assertEqual(preconditions_failed, True)
def test_comment_ordering(self): """Check ordering for comment""" with factories.single_commit(): cgot = wf_factories.CycleTaskGroupObjectTaskFactory() comment1 = factories.CommentFactory(description="comment 1", created_at=datetime.datetime( 2017, 1, 1, 7, 31, 32)) comment2 = factories.CommentFactory(description="comment 2", created_at=datetime.datetime( 2017, 1, 1, 7, 31, 42)) factories.RelationshipFactory(source=comment1, destination=cgot) factories.RelationshipFactory(source=comment2, destination=cgot) query_request_data = [{ u"object_name": u"Comment", u"filters": { u"expression": { u"object_name": u"CycleTaskGroupObjectTask", u"op": { u"name": u"relevant" }, u"ids": [cgot.id] } }, u"order_by": [{ u"name": u"created_at", u"desc": True }] }] resp = self.api.send_request(self.api.client.post, data=query_request_data, api_link="/query") self.assertEqual(2, resp.json[0]["Comment"]["count"]) self.assertEqual("comment 2", resp.json[0]["Comment"]["values"][0]["description"]) self.assertEqual("comment 1", resp.json[0]["Comment"]["values"][1]["description"])
def test_person_mentioned_create(self, send_email_mock, *_): """Test that a user with authorized domain is created when mentioned.""" with factories.single_commit(): obj = factories.ProductFactory(title="Product6") comment = factories.CommentFactory( description=u"One <a href=\"mailto:[email protected]" u"\"></a>", ) comment.created_at = datetime.datetime(2018, 1, 10, 7, 31, 42) people_mentions.handle_comment_mapped(obj, [comment]) person = all_models.Person.query.filter_by( email="*****@*****.**").first() self.assertIsNotNone(person) send_email_mock.assert_called_once()
def test_relation_comment_posted(self, send_email_mock): """Test sending mention email after posting a relationship to comment.""" with factories.single_commit(): author_person = factories.PersonFactory(email="*****@*****.**") factories.PersonFactory(email="*****@*****.**") obj = factories.ProductFactory(title="Product3") obj_id = obj.id comment = factories.CommentFactory( description= u"One <a href=\"mailto:[email protected]\"></a>", ) comment_id = comment.id comment.created_at = datetime.datetime(2018, 07, 10, 8, 31, 42) comment.modified_by_id = author_person.id url = urljoin(get_url_root(), utils.view_url_for(obj)) author_person = all_models.Person.query.filter_by( email="*****@*****.**").one() api = api_helper.Api() api.set_user(author_person) response = api.post( all_models.Relationship, { "relationship": { "source": { "id": obj_id, "type": obj.type, }, "destination": { "id": comment_id, "type": comment.type }, "context": None }, }) self.assertEqual(response.status_code, 201) expected_title = (u"[email protected] mentioned you on " u"a comment within Product3") expected_body = ( u"[email protected] mentioned you on a comment within Product3 " u"at 07/10/2018 01:31:42 PDT:\n" u"One <a href=\"mailto:[email protected]\"></a>\n") body = settings.EMAIL_MENTIONED_PERSON.render( person_mention={ "comments": [expected_body], "url": url, }) send_email_mock.assert_called_once_with(u"*****@*****.**", expected_title, body)
def test_status_unchanged(self): """Test auto status isn't change after add comment action""" assessment = factories.AssessmentFactory() comment = factories.CommentFactory() response = self.api.put(assessment, { "actions": { "add_related": [{ "id": comment.id, "type": "Comment", }] } }) self.assert200(response) self.assertEqual(response.json["assessment"]["status"], all_models.Assessment.START_STATE)
def test_remove_comment(self): """Test remove comment action.""" assessment = factories.AssessmentFactory() comment = factories.CommentFactory(description="123") rel_id = factories.RelationshipFactory(source=assessment, destination=comment).id response = self.api.put(assessment, {"actions": {"remove_related": [ { "id": comment.id, "type": "Comment", } ]}}) self.assert200(response) relationship = all_models.Relationship.query.get(rel_id) self.assertIsNone(relationship)
def test_local_user_create_external_relationship(self): """Test that local user can't create external relationships""" with factories.single_commit(): program = factories.ProgramFactory() comment = factories.CommentFactory() response = self.api.client.post( self.REL_URL, data=self.build_relationship_json(program, comment, is_external=True), headers=self.HEADERS) rel = all_models.Relationship.query.first() self.assert400(response) self.assertIsNone(rel)
def test_filter_by_task_comment(self, cycle_count, task_count): """Test filter cycles by task comments.""" task_cycle_filter = self.generate_tasks_for_cycle( cycle_count, task_count) filter_params = {} for task_id, slug in task_cycle_filter.iteritems(): task = all_models.CycleTaskGroupObjectTask.query.filter( all_models.CycleTaskGroupObjectTask.id == task_id).one() comment_text = "comment for task # {}".format(task_id) comment = ggrc_factories.CommentFactory(description=comment_text) ggrc_factories.RelationshipFactory(source=task, destination=comment) filter_params[comment_text] = slug for comment_text, slug in filter_params.iteritems(): self.assertCycles("task comment", comment_text, [slug])
def test_adding_comment_to_issue(self, update_issue_mock): """Test not adding comment to issue when issue tracker disabled.""" iti = factories.IssueTrackerIssueFactory( enabled=False, issue_tracked_obj=factories.IssueFactory() ) comment = factories.CommentFactory(description="test comment") with mock.patch.object(settings, "ISSUE_TRACKER_ENABLED", True): self.api.post(all_models.Relationship, { "relationship": { "source": {"id": iti.issue_tracked_obj.id, "type": "Issue"}, "destination": {"id": comment.id, "type": "comment"}, "context": None }, }) update_issue_mock.assert_not_called()
def test_order_by_test(self, desc): """Order by fultext attr""" expected_ids = [] with factories.single_commit(): assessments = [factories.AssessmentFactory() for _ in range(10)] random.shuffle(assessments) with factories.single_commit(): for idx, assessment in enumerate(assessments): comment = factories.CommentFactory(description=str(idx)) factories.RelationshipFactory(source=assessment, destination=comment) expected_ids.append(assessment.id) query = self._make_query_dict( "Assessment", order_by=[{"name": "comment", "desc": desc}] ) if desc: expected_ids = expected_ids[::-1] results = self._get_first_result_set(query, "Assessment", "values") self.assertEqual(expected_ids, [i['id'] for i in results])
def test_adding_comment_to_assessment(self, desc, mocked_update_issue): """Test adding comment with blank lines in the end.""" with mock.patch.object( assessment_integration.AssessmentTrackerHandler, '_is_tracker_enabled', return_value=True ): iti = factories.IssueTrackerIssueFactory( enabled=True, component_id="11111", hotlist_id="222222", issue_type="PROCESS", issue_priority="P2", issue_severity="S2" ) iti_title = iti.title iti_issue_id = iti.issue_id asmt = iti.issue_tracked_obj comment = factories.CommentFactory(description=desc) self.api.put(asmt, { "actions": {"add_related": [{"id": comment.id, "type": "Comment"}]}, }) tracker_handler = assessment_integration.AssessmentTrackerHandler() asmt = db.session.query(models.Assessment).get(asmt.id) builder_class = params_builder.BaseIssueTrackerParamsBuilder expected_comment = builder_class.COMMENT_TMPL.format( author=None, comment="test comment", model="Assessment", link=tracker_handler._get_assessment_page_url(asmt), ) kwargs = {'status': 'ACCEPTED', 'component_id': 11111, 'severity': "S2", 'title': iti_title, 'hotlist_ids': [222222], 'priority': "P2", 'comment': expected_comment} mocked_update_issue.assert_called_once_with(iti_issue_id, kwargs)