Esempio n. 1
0
 def test_no_times_by_default(self):
     report = Report(owner=self.user)
     report.encrypt_report("test report", "key")
     report.save()
     self.assertIsNone(Report.objects.first().last_edited)
     self.assertIsNone(Report.objects.first().submitted_to_school)
     self.assertIsNone(Report.objects.first().entered_into_matching)
Esempio n. 2
0
class MatchReportTest(TestCase):

    def setUp(self):
        self.user = User.objects.create_user(username="******", password="******")
        self.report = Report(owner=self.user)
        self.report.encrypt_report("test report", "key")
        self.report.save()
        match_report = MatchReport(report=self.report, identifier='dummy')
        match_report.encrypt_match_report("test match report", match_report.identifier)
        match_report.save()

    def test_entered_into_matching_property_is_set(self):
        self.assertIsNotNone(Report.objects.first().entered_into_matching)

    def test_entered_into_matching_is_blank_before_entering_into_matching(self):
        report = Report(owner=self.user)
        report.encrypt_report("test non-matching report", "key")
        report.save()
        self.assertIsNone(Report.objects.get(pk=report.id).entered_into_matching)

    def test_can_encrypt_match_report(self):
        saved_match_report = MatchReport.objects.first()
        self.assertIsNotNone(saved_match_report.salt)
        self.assertNotEqual(saved_match_report.salt, '')
        self.assertIsNotNone(saved_match_report.encrypted)
        self.assertTrue(len(saved_match_report.encrypted) > 0)

    def test_can_decrypt_match_report(self):
        saved_match_report = MatchReport.objects.first()
        self.assertEqual(saved_match_report.get_match('dummy'), "test match report")
Esempio n. 3
0
 def test_entered_into_matching_property_is_set(self):
     report = Report(owner = self.user)
     report.encrypt_report("test report", "key")
     report.save()
     MatchReport.objects.create(report = report, contact_phone='phone',
                                contact_email='*****@*****.**', identifier='dummy')
     self.assertIsNotNone(Report.objects.first().entered_into_matching)
Esempio n. 4
0
 def test_can_decrypt_report(self):
     report = Report(owner=self.user)
     report.encrypt_report("this text should be encrypted, yes it should by golly!", key='this is my key')
     report.save()
     saved_report = Report.objects.first()
     self.assertEqual(saved_report.decrypted_report('this is my key'),
                      "this text should be encrypted, yes it should by golly!")
Esempio n. 5
0
 def test_edit_sets_edited_time(self):
     report = Report(owner=self.user)
     report.encrypt_report("test report", "key")
     report.save()
     report.encrypt_report("a different report", "key")
     report.save()
     self.assertIsNotNone(Report.objects.first().last_edited)
Esempio n. 6
0
 def test_deleted_report_doesnt_delete_sent_match_report(self):
     match_report = MatchReport(report=self.report, identifier='dummy')
     match_report.encrypt_match_report("test match report", 'dummy')
     match_report.save()
     user2 = User.objects.create_user(username="******", password="******")
     report2 = Report(owner=user2)
     report2.encrypt_report("test report 2", "key")
     report2.save()
     match_report2 = MatchReport(report=report2, identifier='dummy')
     match_report2.encrypt_match_report("test match report 2", 'dummy')
     match_report2.save()
     sent_match_report = SentMatchReport.objects.create()
     sent_match_report.reports.add(match_report, match_report2)
     self.report.match_found = True
     self.report.save()
     report2.match_found = True
     report2.save()
     self.assertIsNotNone(match_report.sentmatchreport_set.first())
     self.assertIsNotNone(match_report2.sentmatchreport_set.first())
     self.assertEqual(match_report, SentMatchReport.objects.first().reports.all()[0])
     self.assertEqual(match_report2, SentMatchReport.objects.first().reports.all()[1])
     self.report.delete()
     self.assertEqual(Report.objects.count(), 1)
     self.assertEqual(MatchReport.objects.count(), 1)
     self.assertEqual(SentMatchReport.objects.first(), sent_match_report)
     self.assertEqual(SentMatchReport.objects.first().reports.count(), 1)
     self.assertEqual(SentMatchReport.objects.first().reports.first(), match_report2)
     self.assertTrue(Report.objects.first().match_found)
     report2.delete()
     self.assertEqual(Report.objects.count(), 0)
     self.assertEqual(SentMatchReport.objects.first(), sent_match_report)
Esempio n. 7
0
 def test_edit_sets_edited_time(self):
     report = Report(owner=self.user)
     report.encrypt_report("test report", "key")
     report.save()
     report.encrypt_report("a different report", "key")
     report.save()
     self.assertIsNotNone(Report.objects.first().last_edited)
Esempio n. 8
0
class ExistingRecordTest(RecordFormBaseTest):

    def setUp(self):
        super(ExistingRecordTest, self).setUp()

        User.objects.create_user(username='******', password='******')
        self.client.login(username='******', password='******')
        self.request = HttpRequest()
        self.request.GET = {}
        self.request.method = 'GET'
        self.request.user = User.objects.get(username='******')

        self.report_text = """[
    { "answer": "test answer",
      "id": %i,
      "section": 1,
      "question_text": "first question",
      "type": "SingleLineText"
    },
    { "answer": "another answer to a different question",
      "id": %i,
      "section": 1,
      "question_text": "2nd question",
      "type": "SingleLineText"
    }
  ]""" % (self.question1.pk, self.question2.pk)
        self.report = Report(owner=self.request.user)
        self.report_key = 'bananabread! is not my key'
        self.report.encrypt_report(self.report_text, self.report_key)
        self.report.save()
        row = EvalRow()
        row.anonymise_record(action=EvalRow.CREATE, report=self.report, decrypted_text=self.report_text)
        row.save()
Esempio n. 9
0
class ExistingRecordTest(RecordFormBaseTest):
    def setUp(self):
        super(ExistingRecordTest, self).setUp()

        User.objects.create_user(username='******', password='******')
        self.client.login(username='******', password='******')
        self.request = HttpRequest()
        self.request.GET = {}
        self.request.method = 'GET'
        self.request.user = User.objects.get(username='******')

        self.report_text = """[
    { "answer": "test answer",
      "id": %i,
      "section": 1,
      "question_text": "first question",
      "type": "SingleLineText"
    },
    { "answer": "another answer to a different question",
      "id": %i,
      "section": 1,
      "question_text": "2nd question",
      "type": "SingleLineText"
    }
  ]""" % (self.question1.pk, self.question2.pk)
        self.report = Report(owner=self.request.user)
        self.report_key = 'bananabread! is not my key'
        self.report.encrypt_report(self.report_text, self.report_key)
        self.report.save()
        row = EvalRow()
        row.anonymise_record(action=EvalRow.CREATE,
                             report=self.report,
                             decrypted_text=self.report_text)
        row.save()
Esempio n. 10
0
 def test_no_times_by_default(self):
     report = Report(owner=self.user)
     report.encrypt_report("test report", "key")
     report.save()
     self.assertIsNone(Report.objects.first().last_edited)
     self.assertIsNone(Report.objects.first().submitted_to_school)
     self.assertIsNone(Report.objects.first().entered_into_matching)
Esempio n. 11
0
class EvalActionTest(MatchTest):

    def setUp(self):
        super(EvalActionTest, self).setUp()

        self.client.login(username='******', password='******')
        self.request = HttpRequest()
        self.request.GET = {}
        self.request.method = 'GET'
        self.request.user = User.objects.get(username='******')

        self.report_text = json.dumps({'test_question': 'test answer'})
        self.key = 'a key a key a key'
        self.report = Report(owner=self.user1)
        self.report.encrypt_report(self.report_text, self.key)
        self.report.save()

    @patch('callisto.delivery.views.run_matching')
    @patch('callisto.delivery.views.EvalRow.anonymise_record')
    def test_submission_to_matching_creates_eval_row(self, mock_anonymise_record, mock_run_matching):
        response = self.client.post(('/test_reports/match/%s/' % self.report.pk),
                                    data={'name': 'test submitter',
                                          'email': '*****@*****.**',
                                          'phone_number': '555-555-1212',
                                          'email_confirmation': "False",
                                          'key': self.key,
                                          'form-0-perp': 'facebook.com/test_url',
                                          'form-TOTAL_FORMS': '1',
                                          'form-INITIAL_FORMS': '1',
                                          'form-MAX_NUM_FORMS': '', })
        self.assertEqual(response.status_code, 200)
        self.assertNotIn('submit_error', response.context)
        mock_anonymise_record.assert_called_with(action=EvalRow.MATCH, report=self.report, match_identifier="test_url",
                                                 decrypted_text=None)

    @patch('callisto.delivery.matching.EvalRow.anonymise_record')
    @patch('callisto.delivery.matching.send_notification_email')
    @patch('callisto.delivery.matching.PDFMatchReport.send_matching_report_to_school')
    def test_match_trigger_creates_eval_row(self, mock_send_to_school, mock_notify, mock_anonymise_record):
        match1 = self.create_match(self.user1, 'dummy')
        match2 = self.create_match(self.user2, 'dummy')
        run_matching()
        call1 = call(action=EvalRow.MATCH_FOUND, report=match1.report, decrypted_text=None, match_identifier=None)
        call2 = call(action=EvalRow.MATCH_FOUND, report=match2.report, decrypted_text=None, match_identifier=None)
        mock_anonymise_record.assert_has_calls([call1, call2])

    @patch('callisto.delivery.views.EvalRow.anonymise_record')
    @patch('callisto.delivery.report_delivery.PDFFullReport.send_report_to_school')
    def test_submit_creates_eval_row(self, mock_send_report, mock_anonymise_record):
        response = self.client.post(('/test_reports/submit/%s/' % self.report.pk),
                                    data={'name': 'test submitter',
                                          'email': '*****@*****.**',
                                          'phone_number': '555-555-1212',
                                          'email_confirmation': "False",
                                          'key': self.key})
        self.assertEqual(response.status_code, 200)
        self.assertNotIn('submit_error', response.context)
        mock_anonymise_record.assert_called_with(action=EvalRow.SUBMIT, report=self.report, decrypted_text=None,
                                                 match_identifier=None)
Esempio n. 12
0
   def test_match_sends_report_immediately(self):
       self.client.post((self.submission_url % self.report.pk),
                        data={'name': 'test submitter 1',
                              'email': '*****@*****.**',
                              'phone_number': '555-555-1212',
                              'email_confirmation': "False",
                              'key': self.report_key,
                              'form-0-perp': 'facebook.com/triggered_match',
                              'form-TOTAL_FORMS': '1',
                              'form-INITIAL_FORMS': '1',
                              'form-MAX_NUM_FORMS': '', })
       user2 = User.objects.create_user(username='******', password='******')
       self.client.login(username='******', password='******')
       report2_text = """[
   { "answer": "test answer",
     "id": %i,
     "section": 1,
     "question_text": "first question",
     "type": "SingleLineText"
   },
   { "answer": "another answer to a different question",
     "id": %i,
     "section": 1,
     "question_text": "2nd question",
     "type": "SingleLineText"
   }
 ]""" % (self.question1.pk, self.question2.pk)
       report2 = Report(owner=user2)
       report2_key = 'a key a key a key a key key'
       report2.encrypt_report(report2_text, report2_key)
       report2.save()
       response = self.client.post((self.submission_url % report2.pk),
                                   data={'name': 'test submitter 2',
                                         'email': '*****@*****.**',
                                         'phone_number': '555-555-1213',
                                         'email_confirmation': "False",
                                         'key': report2_key,
                                         'form-0-perp': 'facebook.com/triggered_match',
                                         'form-TOTAL_FORMS': '1',
                                         'form-INITIAL_FORMS': '1',
                                         'form-MAX_NUM_FORMS': '', })
       self.assertNotIn('submit_error', response.context)
       self.assertEqual(len(mail.outbox), 3)
       message = mail.outbox[0]
       self.assertEqual(message.subject, 'test match notification')
       self.assertEqual(message.to, ['*****@*****.**'])
       self.assertIn('Matching" <notification@', message.from_email)
       self.assertIn('test match notification body', message.body)
       message = mail.outbox[1]
       self.assertEqual(message.subject, 'test match notification')
       self.assertEqual(message.to, ['*****@*****.**'])
       self.assertIn('Matching" <notification@', message.from_email)
       self.assertIn('test match notification body', message.body)
       message = mail.outbox[2]
       self.assertEqual(message.subject, 'test match delivery')
       self.assertEqual(message.to, ['*****@*****.**'])
       self.assertIn('"Reports" <reports@', message.from_email)
       self.assertIn('test match delivery body', message.body)
       self.assertRegexpMatches(message.attachments[0][0], 'report_.*\.pdf\.gpg')
Esempio n. 13
0
 def test_can_decrypt_old_reports(self):
     legacy_report = LegacyReportData()
     legacy_report.encrypt_report("this text should be encrypted otherwise bad things", key='this is my key')
     report = Report(owner=self.user, encrypted=legacy_report.encrypted, salt=legacy_report.salt)
     report.save()
     saved_report = Report.objects.first()
     self.assertEqual(saved_report.decrypted_report('this is my key'),
                      "this text should be encrypted otherwise bad things")
Esempio n. 14
0
 def create_match(self, user, identifier):
     report = Report(owner=user)
     report.encrypt_report("test report 1", "key")
     report.save()
     return MatchReport.objects.create(report=report,
                                       contact_phone='phone',
                                       contact_email='*****@*****.**',
                                       identifier=identifier)
Esempio n. 15
0
 def test_can_encrypt_report(self):
     report = Report(owner=self.user)
     report.encrypt_report("this text should be encrypted", key='this is my key')
     report.save()
     saved_report = Report.objects.first()
     self.assertIsNotNone(saved_report.salt)
     self.assertNotEqual(saved_report.salt, '')
     self.assertIsNotNone(saved_report.encrypted)
     self.assertTrue(len(saved_report.encrypted) > 0)
Esempio n. 16
0
 def test_entered_into_matching_property_is_set(self):
     report = Report(owner=self.user)
     report.encrypt_report("test report", "key")
     report.save()
     MatchReport.objects.create(report=report,
                                contact_phone='phone',
                                contact_email='*****@*****.**',
                                identifier='dummy')
     self.assertIsNotNone(Report.objects.first().entered_into_matching)
Esempio n. 17
0
   def test_match_sends_custom_report(self):
       self.client.post(
           ('/test_reports/match_custom/%s/' % self.report.pk),
           data={
               'name': 'test submitter 1',
               'email': '*****@*****.**',
               'phone_number': '555-555-1212',
               'email_confirmation': "False",
               'key': self.report_key,
               'form-0-perp': 'facebook.com/triggered_match',
               'form-TOTAL_FORMS': '1',
               'form-INITIAL_FORMS': '1',
               'form-MAX_NUM_FORMS': '',
           })
       user2 = User.objects.create_user(username='******', password='******')
       self.client.login(username='******', password='******')
       report2_text = """[
   { "answer": "test answer",
     "id": %i,
     "section": 1,
     "question_text": "first question",
     "type": "SingleLineText"
   },
   { "answer": "another answer to a different question",
     "id": %i,
     "section": 1,
     "question_text": "2nd question",
     "type": "SingleLineText"
   }
 ]""" % (self.question1.pk, self.question2.pk)
       report2 = Report(owner=user2)
       report2_key = 'a key a key a key a key key'
       report2.encrypt_report(report2_text, report2_key)
       report2.save()
       response = self.client.post(
           ('/test_reports/match_custom/%s/' % report2.pk),
           data={
               'name': 'test submitter 2',
               'email': '*****@*****.**',
               'phone_number': '555-555-1213',
               'email_confirmation': "False",
               'key': report2_key,
               'form-0-perp': 'facebook.com/triggered_match',
               'form-TOTAL_FORMS': '1',
               'form-INITIAL_FORMS': '1',
               'form-MAX_NUM_FORMS': '',
           })
       self.assertNotIn('submit_error', response.context)
       self.assertEqual(len(mail.outbox), 3)
       message = mail.outbox[2]
       self.assertEqual(message.subject, 'test match delivery')
       self.assertEqual(message.to, ['*****@*****.**'])
       self.assertIn('"Custom" <custom@', message.from_email)
       self.assertIn('test match delivery body', message.body)
       self.assertRegexpMatches(message.attachments[0][0],
                                'custom_.*\.pdf\.gpg')
Esempio n. 18
0
 def create_match(self, user, identifier, match_report_content=None):
     report = Report(owner=user)
     report.encrypt_report("test report 1", "key")
     report.save()
     match_report = MatchReport(report=report, identifier=identifier)
     match_report_object = match_report_content if match_report_content else MatchReportContent(
         identifier='test', perp_name='test', email='*****@*****.**', phone="test")
     match_report.encrypt_match_report(json.dumps(match_report_object.__dict__), identifier)
     match_report.save()
     return match_report
Esempio n. 19
0
 def test_can_encrypt_report(self):
     report = Report(owner=self.user)
     report.encrypt_report("this text should be encrypted",
                           key='this is my key')
     report.save()
     saved_report = Report.objects.first()
     self.assertIsNotNone(saved_report.salt)
     self.assertNotEqual(saved_report.salt, '')
     self.assertIsNotNone(saved_report.encrypted)
     self.assertTrue(len(saved_report.encrypted) > 0)
Esempio n. 20
0
 def test_can_decrypt_report(self):
     report = Report(owner=self.user)
     report.encrypt_report(
         "this text should be encrypted, yes it should by golly!",
         key='this is my key')
     report.save()
     saved_report = Report.objects.first()
     self.assertEqual(
         saved_report.decrypted_report('this is my key'),
         "this text should be encrypted, yes it should by golly!")
Esempio n. 21
0
 def test_user_identifier(self):
     user_with_email = User.objects.create_user(username="******", password="******", email="*****@*****.**")
     report = Report(owner=user_with_email)
     report.encrypt_report(self.decrypted_report, "a key a key a key")
     report.save()
     pdf_report = PDFFullReport(report, self.decrypted_report)
     output = pdf_report.generate_pdf_report(recipient=None, report_id=None)
     exported_report = BytesIO(output)
     pdfReader = PyPDF2.PdfFileReader(exported_report)
     self.assertIn("Submitted by: [email protected]", pdfReader.getPage(0).extractText())
Esempio n. 22
0
 def test_user_identifier(self):
     user_with_email = User.objects.create_user(username="******",
                                                password="******",
                                                email="*****@*****.**")
     report = Report(owner=user_with_email)
     report.encrypt_report(self.decrypted_report, "a key a key a key")
     report.save()
     pdf_report = PDFFullReport(report, self.decrypted_report)
     output = pdf_report.generate_pdf_report(recipient=None, report_id=None)
     exported_report = BytesIO(output)
     pdfReader = PyPDF2.PdfFileReader(exported_report)
     self.assertIn("Submitted by: [email protected]",
                   pdfReader.getPage(0).extractText())
Esempio n. 23
0
    def test_can_decrypt_old_match_report(self):
        legacy_match_report = LegacyMatchReportData()
        legacy_match_report.encrypt_match_report("test legacy match report", "dumbo")

        legacy_report = LegacyReportData()
        legacy_report.encrypt_report("this text should be encrypted otherwise bad things", key='this is my key')
        report = Report(owner=self.user, encrypted=legacy_report.encrypted, salt=legacy_report.salt)
        report.save()

        new_match_report = MatchReport(report=report, encrypted=legacy_match_report.encrypted,
                                       salt=legacy_match_report.salt, identifier="dumbo")
        new_match_report.save()
        self.assertEqual(new_match_report.get_match("dumbo"), "test legacy match report")
Esempio n. 24
0
    def test_edit_saves_original_record_if_no_data_exists(self):
        old_report = Report(owner = self.request.user)
        old_report.encrypt_report(self.report_text, self.report_key)
        old_report.save()

        self.assertEqual(EvalRow.objects.count(), 1)
        self.assertEqual(EvalRow.objects.filter(action=EvalRow.FIRST).count(), 0)

        self.edit_record(record_to_edit=old_report)
        self.assertEqual(EvalRow.objects.count(), 3)
        self.assertEqual(EvalRow.objects.filter(action=EvalRow.FIRST).count(), 1)
        self.assertEqual(EvalRow.objects.last().action, EvalRow.EDIT)
        self.assertEqual(EvalRow.objects.filter(action=EvalRow.FIRST).first().record_identifier, EvalRow.objects.last().record_identifier)
        self.assertNotEqual(EvalRow.objects.filter(action=EvalRow.FIRST).first().row, EvalRow.objects.last().row)
Esempio n. 25
0
    def test_done_saves_anonymised_qs(self, mockReport):
        self.maxDiff = None

        radio_button_q = RadioButton.objects.create(text="this is a radio button question", page=self.page2)
        for i in range(5):
            Choice.objects.create(text="This is choice %i" % i, question=radio_button_q)
        wizard = EncryptedFormWizard.wizard_factory()()

        PageOneForm = wizard.form_list[0]
        PageTwoForm = wizard.form_list[1]
        KeyForm = wizard.form_list[2]

        page_one = PageOneForm({'question_%i' % self.question1.pk: 'test answer'})
        page_one.is_valid()
        page_two = PageTwoForm({'question_%i' % self.question2.pk: 'another answer to a different question',
                                'question_%i' % radio_button_q.pk: radio_button_q.choice_set.all()[2].pk})
        page_two.is_valid()
        key_form = KeyForm({'key': self.report_key, 'key2': self.report_key})
        key_form.is_valid()

        mock_report = Report()
        mock_report.save = Mock()
        mock_report.owner = self.request.user
        mockReport.return_value = mock_report

        self._get_wizard_response(wizard, form_list=[page_one, page_two, key_form], request=self.request)
Esempio n. 26
0
class MatchReportTest(TestCase):

    def setUp(self):
        self.user = User.objects.create_user(username="******", password="******")
        self.report = Report(owner=self.user)
        self.report.encrypt_report("test report", "key")
        self.report.save()
        match_report = MatchReport(report=self.report, identifier='dummy')
        match_report.encrypt_match_report("test match report", match_report.identifier)
        match_report.save()

    def test_entered_into_matching_property_is_set(self):
        self.assertIsNotNone(Report.objects.first().entered_into_matching)

    def test_entered_into_matching_is_blank_before_entering_into_matching(self):
        report = Report(owner=self.user)
        report.encrypt_report("test non-matching report", "key")
        report.save()
        self.assertIsNone(Report.objects.get(pk=report.id).entered_into_matching)

    def test_can_encrypt_match_report(self):
        saved_match_report = MatchReport.objects.first()
        self.assertIsNotNone(saved_match_report.encode_prefix)
        self.assertNotEqual(saved_match_report.encode_prefix, '')
        self.assertIsNotNone(saved_match_report.encrypted)
        self.assertTrue(len(saved_match_report.encrypted) > 0)

    def test_can_decrypt_match_report(self):
        saved_match_report = MatchReport.objects.first()
        self.assertEqual(saved_match_report.get_match('dummy'), "test match report")

    def test_can_decrypt_old_match_report(self):
        legacy_match_report = LegacyMatchReportData()
        legacy_match_report.encrypt_match_report("test legacy match report", "dumbo")

        legacy_report = LegacyReportData()
        legacy_report.encrypt_report("this text should be encrypted otherwise bad things", key='this is my key')
        report = Report(owner=self.user, encrypted=legacy_report.encrypted, salt=legacy_report.salt)
        report.save()

        new_match_report = MatchReport(report=report, encrypted=legacy_match_report.encrypted,
                                       salt=legacy_match_report.salt, identifier="dumbo")
        new_match_report.save()
        self.assertEqual(new_match_report.get_match("dumbo"), "test legacy match report")
Esempio n. 27
0
class DecryptKeyFormTest(TestCase):
    def setUp(self):
        user = User.objects.create(username="******", password="******")
        self.report = Report(owner=user)
        self.key = '~*~*~*~my key~*~*~*~'
        self.report.encrypt_report('this is a report', self.key)
        self.report.save()

    def test_wrong_key_rejected(self, mock_add_report_data):
        bad_request = {'key': 'not my key'}
        form = SecretKeyForm(bad_request)
        form.report = self.report
        self.assertFalse(form.is_valid())
        self.assertEqual(form.errors['key'], ["The passphrase didn't match."])

    def test_right_key_accepted(self, mock_add_report_data):
        good_request = {'key': self.key}
        form = SecretKeyForm(good_request)
        form.report = self.report
        self.assertTrue(form.is_valid())
Esempio n. 28
0
    def test_edit_saves_original_record_if_no_data_exists(self):
        old_report = Report(owner=self.request.user)
        old_report.encrypt_report(self.report_text, self.report_key)
        old_report.save()

        self.assertEqual(EvalRow.objects.count(), 1)
        self.assertEqual(
            EvalRow.objects.filter(action=EvalRow.FIRST).count(), 0)

        self.edit_record(record_to_edit=old_report)
        self.assertEqual(EvalRow.objects.count(), 3)
        self.assertEqual(
            EvalRow.objects.filter(action=EvalRow.FIRST).count(), 1)
        self.assertEqual(EvalRow.objects.last().action, EvalRow.EDIT)
        self.assertEqual(
            EvalRow.objects.filter(
                action=EvalRow.FIRST).first().record_identifier,
            EvalRow.objects.last().record_identifier)
        self.assertNotEqual(
            EvalRow.objects.filter(action=EvalRow.FIRST).first().row,
            EvalRow.objects.last().row)
Esempio n. 29
0
class DecryptKeyFormTest(TestCase):

    def setUp(self):
        user = User.objects.create(username="******", password="******")
        self.report = Report(owner=user)
        self.key = '~*~*~*~my key~*~*~*~'
        self.report.encrypt_report('this is a report', self.key)
        self.report.save()

    def test_wrong_key_rejected(self, mock_add_report_data):
        bad_request = {'key': 'not my key'}
        form = SecretKeyForm(bad_request)
        form.report = self.report
        self.assertFalse(form.is_valid())
        self.assertEqual(
            form.errors['key'],
            ["The passphrase didn't match."]
        )

    def test_right_key_accepted(self, mock_add_report_data):
        good_request = {'key': self.key}
        form = SecretKeyForm(good_request)
        form.report = self.report
        self.assertTrue(form.is_valid())
Esempio n. 30
0
 def test_can_withdraw_from_matching(self):
     report = Report(owner=self.user)
     report.encrypt_report("test report", "key")
     report.save()
     MatchReport.objects.create(report=report, contact_email='*****@*****.**', identifier='dummy')
     self.assertIsNotNone(Report.objects.first().entered_into_matching)
     report.match_found = True
     report.save()
     report.withdraw_from_matching()
     report.save()
     self.assertIsNone(Report.objects.first().entered_into_matching)
     self.assertFalse(Report.objects.first().match_found)
Esempio n. 31
0
 def test_can_withdraw_from_matching(self):
     report = Report(owner=self.user)
     report.encrypt_report("test report", "key")
     report.save()
     MatchReport.objects.create(report=report,
                                contact_phone='phone',
                                contact_email='*****@*****.**',
                                identifier='dummy')
     self.assertIsNotNone(Report.objects.first().entered_into_matching)
     report.match_found = True
     report.save()
     report.withdraw_from_matching()
     report.save()
     self.assertIsNone(Report.objects.first().entered_into_matching)
     self.assertFalse(Report.objects.first().match_found)
Esempio n. 32
0
    def test_done_saves_anonymised_qs(self, mockEvalRow, mockReport):
        self.maxDiff = None

        radio_button_q = RadioButton.objects.create(
            text="this is a radio button question", page=self.page2)
        for i in range(5):
            Choice.objects.create(text="This is choice %i" % i,
                                  question=radio_button_q)
        wizard = EncryptedFormWizard.wizard_factory()()

        PageOneForm = wizard.form_list[0]
        PageTwoForm = wizard.form_list[1]
        KeyForm = wizard.form_list[2]

        page_one = PageOneForm(
            {'question_%i' % self.question1.pk: 'test answer'})
        page_one.is_valid()
        page_two = PageTwoForm({
            'question_%i' % self.question2.pk:
            'another answer to a different question',
            'question_%i' % radio_button_q.pk:
            radio_button_q.choice_set.all()[2].pk
        })
        page_two.is_valid()
        key_form = KeyForm({'key': self.report_key, 'key2': self.report_key})
        key_form.is_valid()

        mock_report = Report()
        mock_report.save = Mock()
        mock_report.owner = self.request.user
        mockReport.return_value = mock_report

        mock_eval_row = EvalRow()
        mock_eval_row.save = Mock()
        mockEvalRow.return_value = mock_eval_row

        self._get_wizard_response(wizard,
                                  form_list=[page_one, page_two, key_form],
                                  request=self.request)
        mock_eval_row.save.assert_any_call()
Esempio n. 33
0
class EditRecordFormTest(RecordFormBaseTest):
    record_form_url = '/test_reports/edit/%s/'

    def setUp(self):
        super().setUp()

        User.objects.create_user(username='******', password='******')
        self.client.login(username='******', password='******')
        self.request = HttpRequest()
        self.request.GET = {}
        self.request.method = 'GET'
        self.request.user = User.objects.get(username='******')

        self.report_text = """[
    { "answer": "test answer",
      "id": %i,
      "section": 1,
      "question_text": "first question",
      "type": "SingleLineText"
    },
    { "answer": "another answer to a different question",
      "id": %i,
      "section": 1,
      "question_text": "2nd question",
      "type": "SingleLineText"
    }
  ]""" % (self.question1.pk, self.question2.pk)
        self.report = Report(owner=self.request.user)
        self.report_key = 'bananabread! is not my key'
        self.report.encrypt_report(self.report_text, self.report_key)
        self.report.save()
        row = EvalRow()
        row.anonymise_record(action=EvalRow.CREATE,
                             report=self.report,
                             decrypted_text=self.report_text)
        row.save()

    def enter_edit_key(self):
        return self.client.post(
            (self.record_form_url % self.report.pk),
            data={
                '0-key': self.report_key,
                'wizard_goto_step': 1,
                'form_wizard' + str(self.report.id) + '-current_step': 0
            },
            follow=True)

    def test_edit_record_page_renders_key_prompt(self):
        response = self.client.get(self.record_form_url % self.report.pk,
                                   follow=True)
        self.assertTemplateUsed(response, 'decrypt_record_for_edit.html')
        self.assertIsInstance(response.context['form'], SecretKeyForm)

    def test_edit_record_form_advances_to_second_page(self):
        response = self.enter_edit_key()
        self.assertTemplateUsed(response, 'record_form.html')
        self.assertIsInstance(response.context['form'], QuestionPageForm)
        self.assertContains(response,
                            'name="1-question_%i"' % self.question1.pk)
        self.assertNotContains(response,
                               'name="1-question_%i"' % self.question2.pk)

    def test_initial_is_passed_to_forms(self):
        response = self.enter_edit_key()
        form = response.context['form']
        self.assertIn('test answer', form.initial.values())
        self.assertIn('another answer to a different question',
                      form.initial.values())

    def edit_record(self, record_to_edit):
        wizard = EncryptedFormWizard.wizard_factory(
            object_to_edit=record_to_edit)()

        KeyForm1 = wizard.form_list[0]
        PageOneForm = wizard.form_list[1]
        PageTwoForm = wizard.form_list[2]
        KeyForm2 = wizard.form_list[3]

        key_form_1 = KeyForm1({'key': self.report_key})
        key_form_1.is_valid()

        page_one = PageOneForm(
            {'question_%i' % self.question1.pk: 'test answer'})
        page_one.is_valid()
        page_two = PageTwoForm({
            'question_%i' % self.question2.pk:
            'edited answer to second question',
        })
        page_two.is_valid()
        key_form_2 = KeyForm2({'key': self.report_key})
        key_form_2.is_valid()

        self._get_wizard_response(
            wizard,
            form_list=[key_form_1, page_one, page_two, key_form_2],
            request=self.request)

    def test_edit_modifies_record(self):
        self.maxDiff = None

        json_report = """[
    { "answer": "test answer",
      "id": %i,
      "section": 1,
      "question_text": "first question",
      "type": "SingleLineText"
    },
    { "answer": "edited answer to second question",
      "id": %i,
      "section": 1,
      "question_text": "2nd question",
      "type": "SingleLineText"
    }
  ]""" % (self.question1.pk, self.question2.pk)

        self.edit_record(self.report)
        self.assertEqual(Report.objects.count(), 1)
        self.assertEqual(
            sort_json(
                Report.objects.get(id=self.report.pk).decrypted_report(
                    self.report_key)), sort_json(json_report))

    def test_cant_edit_with_bad_key(self):
        self.maxDiff = None

        wizard = EncryptedFormWizard.wizard_factory(
            object_to_edit=self.report)()

        KeyForm1 = wizard.form_list[0]

        key_form_1 = KeyForm1({'key': "not the right key!!!"})
        self.assertFalse(key_form_1.is_valid())

    def test_cant_save_edit_with_bad_key(self):
        wizard = EncryptedFormWizard.wizard_factory(
            object_to_edit=self.report)()

        KeyForm1 = wizard.form_list[0]
        PageOneForm = wizard.form_list[1]
        PageTwoForm = wizard.form_list[2]
        KeyForm2 = wizard.form_list[3]

        key_form_1 = KeyForm1({'key': self.report_key})
        key_form_1.is_valid()

        page_one = PageOneForm(
            {'question_%i' % self.question1.pk: 'test answer'})
        page_one.is_valid()
        page_two = PageTwoForm({
            'question_%i' % self.question2.pk:
            'edited answer to second question',
        })
        page_two.is_valid()
        key_form_2 = KeyForm2({'key': "not the right key"})
        self.assertFalse(key_form_2.is_valid())
        with self.assertRaises(KeyError):
            self._get_wizard_response(
                wizard,
                form_list=[key_form_1, page_one, page_two, key_form_2],
                request=self.request)
        self.assertEqual(
            sort_json(
                Report.objects.get(id=self.report.pk).decrypted_report(
                    self.report_key)), sort_json(self.report_text))

    def test_edit_saves_anonymous_row(self):
        self.edit_record(self.report)
        self.assertEqual(EvalRow.objects.count(), 2)
        self.assertEqual(EvalRow.objects.last().action, EvalRow.EDIT)
        self.edit_record(self.report)
        self.assertEqual(EvalRow.objects.count(), 3)
        self.assertEqual(Report.objects.count(), 1)

    def test_edit_saves_original_record_if_no_data_exists(self):
        old_report = Report(owner=self.request.user)
        old_report.encrypt_report(self.report_text, self.report_key)
        old_report.save()

        self.assertEqual(EvalRow.objects.count(), 1)
        self.assertEqual(
            EvalRow.objects.filter(action=EvalRow.FIRST).count(), 0)

        self.edit_record(record_to_edit=old_report)
        self.assertEqual(EvalRow.objects.count(), 3)
        self.assertEqual(
            EvalRow.objects.filter(action=EvalRow.FIRST).count(), 1)
        self.assertEqual(EvalRow.objects.last().action, EvalRow.EDIT)
        self.assertEqual(
            EvalRow.objects.filter(
                action=EvalRow.FIRST).first().record_identifier,
            EvalRow.objects.last().record_identifier)
        self.assertNotEqual(
            EvalRow.objects.filter(action=EvalRow.FIRST).first().row,
            EvalRow.objects.last().row)
Esempio n. 34
0
 def test_reports_have_owners(self):
     report = Report()
     report.owner = self.user
     report.save()
     self.assertIn(report, self.user .report_set.all())
Esempio n. 35
0
class EvalActionTest(MatchTest):

    def setUp(self):
        super(EvalActionTest, self).setUp()

        self.page1 = QuestionPage.objects.create()
        self.page2 = QuestionPage.objects.create()
        self.question1 = SingleLineText.objects.create(text="first question", page=self.page1)
        self.question2 = SingleLineText.objects.create(text="2nd question", page=self.page2)

        self.client.login(username='******', password='******')
        self.request = HttpRequest()
        self.request.GET = {}
        self.request.method = 'GET'
        self.request.user = User.objects.get(username='******')

        self.report_text = json.dumps({'test_question': 'test answer'})
        self.key = 'a key a key a key'
        self.report = Report(owner=self.user1)
        self.report.encrypt_report(self.report_text, self.key)
        self.report.save()

    @patch('callisto.delivery.views.run_matching')
    @patch('callisto.delivery.views.EvalRow.anonymise_record')
    def test_submission_to_matching_creates_eval_row(self, mock_anonymise_record, mock_run_matching):
        response = self.client.post(('/test_reports/match/%s/' % self.report.pk),
                                    data={'name': 'test submitter',
                                          'email': '*****@*****.**',
                                          'phone_number': '555-555-1212',
                                          'email_confirmation': "False",
                                          'key': self.key,
                                          'form-0-perp': 'facebook.com/test_url',
                                          'form-TOTAL_FORMS': '1',
                                          'form-INITIAL_FORMS': '1',
                                          'form-MAX_NUM_FORMS': '', })
        self.assertEqual(response.status_code, 200)
        self.assertNotIn('submit_error', response.context)
        mock_anonymise_record.assert_called_with(action=EvalRow.MATCH, report=self.report, match_identifier="test_url",
                                                 decrypted_text=None)

    @patch('callisto.delivery.matching.EvalRow.anonymise_record')
    @patch('callisto.delivery.matching.send_notification_email')
    @patch('callisto.delivery.matching.PDFMatchReport.send_matching_report_to_school')
    def test_match_trigger_creates_eval_row(self, mock_send_to_school, mock_notify, mock_anonymise_record):
        match1 = self.create_match(self.user1, 'dummy')
        match2 = self.create_match(self.user2, 'dummy')
        run_matching()
        call1 = call(action=EvalRow.MATCH_FOUND, report=match1.report, decrypted_text=None, match_identifier=None)
        call2 = call(action=EvalRow.MATCH_FOUND, report=match2.report, decrypted_text=None, match_identifier=None)
        mock_anonymise_record.assert_has_calls([call1, call2])

    @patch('callisto.delivery.views.EvalRow.anonymise_record')
    @patch('callisto.delivery.report_delivery.PDFFullReport.send_report_to_school')
    def test_submit_creates_eval_row(self, mock_send_report, mock_anonymise_record):
        response = self.client.post(('/test_reports/submit/%s/' % self.report.pk),
                                    data={'name': 'test submitter',
                                          'email': '*****@*****.**',
                                          'phone_number': '555-555-1212',
                                          'email_confirmation': "False",
                                          'key': self.key})
        self.assertEqual(response.status_code, 200)
        self.assertNotIn('submit_error', response.context)
        mock_anonymise_record.assert_called_with(action=EvalRow.SUBMIT, report=self.report, decrypted_text=None,
                                                 match_identifier=None)

    @patch('callisto.delivery.views.EvalRow.anonymise_record')
    @patch('callisto.delivery.views.Report.delete')
    def test_delete_creates_eval_row(self, mock_delete, mock_anonymise_record):
        response = self.client.post(
            '/test_reports/delete/%s/' % self.report.id,
            data={'key': self.key},
        )
        self.assertEqual(response.status_code, 200)
        self.assertNotIn('submit_error', response.context)
        mock_anonymise_record.assert_called_with(action=EvalRow.DELETE, report=self.report, decrypted_text=None,
                                                 match_identifier=None)

    @patch('callisto.delivery.views.EvalRow.anonymise_record')
    def test_autosave_creates_eval_row(self, mock_anonymise_record):
        response = self.client.post(
            '/test_reports/new/0/',
            data={'0-key': self.key,
                  '0-key2': self.key,
                  'form_wizard-current_step': 0},
            follow=True
        )
        self.client.post(
            response.redirect_chain[0][0],
            data={'1-question_%i' % self.question1.pk: 'test answer',
                  'form_wizard-current_step': 1,
                  'wizard_goto_step': 2},
            follow=True)
        self.client.get("www.google.com")
        # JSON sorting is making this test flap
        mock_anonymise_record.assert_called_with(action=EvalRow.AUTOSAVE, report=Report.objects.first(),
                                                 decrypted_text=ANY, match_identifier=None)
Esempio n. 36
0
 def test_report_owner_is_not_optional(self):
     report = Report(encrypted=b'a report')
     with self.assertRaises(IntegrityError):
         report.save()
         report.full_clean()
Esempio n. 37
0
class ReportDeliveryTest(MatchTest):

    def setUp(self):
        super(ReportDeliveryTest, self).setUp()
        self.user = self.user1
        self.decrypted_report = """[
    { "answer": "test answer",
      "id": 1,
      "section": 1,
      "question_text": "first question",
      "type": "SingleLineText"
    },
    { "answer": "answer to 2nd question",
      "id": 2,
      "section": 1,
      "question_text": "2nd question",
      "type": "SingleLineText"
    }
  ]"""
        self.report = Report(owner=self.user)
        self.report.encrypt_report(self.decrypted_report, "a key a key a key")
        self.report.save()

    def test_pdf_full_report_is_generated(self):
        report = PDFFullReport(self.report, self.decrypted_report)
        output = report.generate_pdf_report(recipient=None, report_id=None)
        exported_report = BytesIO(output)
        pdfReader = PyPDF2.PdfFileReader(exported_report)
        self.assertIn("Submitted by: dummy", pdfReader.getPage(0).extractText())
        self.assertIn("test answer", pdfReader.getPage(1).extractText())
        self.assertIn("answer to 2nd question", pdfReader.getPage(1).extractText())

    def test_submission_to_school(self):
        EmailNotification.objects.create(name='report_delivery', subject="test delivery", body="test body")
        report = PDFFullReport(self.report, self.decrypted_report)
        report.send_report_to_school()
        sent_report_id = SentFullReport.objects.latest('id').get_report_id()
        self.assertEqual(len(mail.outbox), 1)
        message = mail.outbox[0]
        self.assertEqual(message.subject, 'test delivery')
        self.assertIn('"Reports" <reports', message.from_email)
        self.assertEqual(message.attachments[0][0], 'report_%s.pdf.gpg' % sent_report_id)

    # TODO: test encryption of submitted report email

    def test_pdf_match_report_is_generated(self):
        match1 = self.create_match(self.user1, 'dummy')
        match2 = self.create_match(self.user2, 'dummy')
        report = PDFMatchReport([match1, match2])
        output = report.generate_match_report(report_id=1)
        exported_report = BytesIO(output)
        pdfReader = PyPDF2.PdfFileReader(exported_report)
        self.assertIn("Intended for: Title IX Coordinator Tatiana Nine", pdfReader.getPage(0).extractText())
        self.assertIn("Submitted by: dummy", pdfReader.getPage(0).extractText())
        self.assertIn("Submitted by: ymmud", pdfReader.getPage(0).extractText())

    def test_matches_to_school(self):
        EmailNotification.objects.create(name='match_delivery', subject="test match delivery", body="test match body")
        match1 = self.create_match(self.user1, 'dummy')
        match2 = self.create_match(self.user2, 'dummy')
        report = PDFMatchReport([match1, match2])
        report.send_matching_report_to_school()
        sent_report_id = SentMatchReport.objects.latest('id').get_report_id()
        self.assertEqual(len(mail.outbox), 1)
        message = mail.outbox[0]
        self.assertEqual(message.subject, 'test match delivery')
        self.assertIn('"Reports" <reports', message.from_email)
        self.assertEqual(message.attachments[0][0], 'report_%s.pdf.gpg' % sent_report_id)

    def test_user_identifier(self):
        user_with_email = User.objects.create_user(username="******", password="******", email="*****@*****.**")
        report = Report(owner=user_with_email)
        report.encrypt_report(self.decrypted_report, "a key a key a key")
        report.save()
        pdf_report = PDFFullReport(report, self.decrypted_report)
        output = pdf_report.generate_pdf_report(recipient=None, report_id=None)
        exported_report = BytesIO(output)
        pdfReader = PyPDF2.PdfFileReader(exported_report)
        self.assertIn("Submitted by: [email protected]", pdfReader.getPage(0).extractText())
Esempio n. 38
0
 def test_cannot_save_empty_reports(self):
     report = Report(owner=self.user , encrypted=b'')
     with self.assertRaises(ValidationError):
         report.save()
         report.full_clean()
Esempio n. 39
0
class ReportDeliveryTest(MatchTest):
    def setUp(self):
        super(ReportDeliveryTest, self).setUp()
        self.user = self.user1
        self.decrypted_report = """[
    { "answer": "test answer",
      "id": 1,
      "section": 1,
      "question_text": "first question",
      "type": "SingleLineText"
    },
    { "answer": "answer to 2nd question",
      "id": 2,
      "section": 1,
      "question_text": "2nd question",
      "type": "SingleLineText"
    }
  ]"""
        self.report = Report(owner=self.user)
        self.report.encrypt_report(self.decrypted_report, "a key a key a key")
        self.report.save()

    def test_pdf_full_report_is_generated(self):
        report = PDFFullReport(self.report, self.decrypted_report)
        output = report.generate_pdf_report(recipient=None, report_id=None)
        exported_report = BytesIO(output)
        pdfReader = PyPDF2.PdfFileReader(exported_report)
        self.assertIn("Submitted by: dummy",
                      pdfReader.getPage(0).extractText())
        self.assertIn("test answer", pdfReader.getPage(1).extractText())
        self.assertIn("answer to 2nd question",
                      pdfReader.getPage(1).extractText())

    def test_submission_to_school(self):
        EmailNotification.objects.create(name='report_delivery',
                                         subject="test delivery",
                                         body="test body")
        report = PDFFullReport(self.report, self.decrypted_report)
        report.send_report_to_school()
        sent_report_id = SentFullReport.objects.latest('id').get_report_id()
        self.assertEqual(len(mail.outbox), 1)
        message = mail.outbox[0]
        self.assertEqual(message.subject, 'test delivery')
        self.assertIn('"Reports" <reports', message.from_email)
        self.assertEqual(message.attachments[0][0],
                         'report_%s.pdf.gpg' % sent_report_id)

    # TODO: test encryption of submitted report email

    def test_pdf_match_report_is_generated(self):
        match1 = self.create_match(self.user1, 'dummy')
        match2 = self.create_match(self.user2, 'dummy')
        report = PDFMatchReport([match1, match2])
        output = report.generate_match_report(report_id=1)
        exported_report = BytesIO(output)
        pdfReader = PyPDF2.PdfFileReader(exported_report)
        self.assertIn("Intended for: Title IX Coordinator Tatiana Nine",
                      pdfReader.getPage(0).extractText())
        self.assertIn("Submitted by: dummy",
                      pdfReader.getPage(0).extractText())
        self.assertIn("Submitted by: ymmud",
                      pdfReader.getPage(0).extractText())

    def test_matches_to_school(self):
        EmailNotification.objects.create(name='match_delivery',
                                         subject="test match delivery",
                                         body="test match body")
        match1 = self.create_match(self.user1, 'dummy')
        match2 = self.create_match(self.user2, 'dummy')
        report = PDFMatchReport([match1, match2])
        report.send_matching_report_to_school()
        sent_report_id = SentMatchReport.objects.latest('id').get_report_id()
        self.assertEqual(len(mail.outbox), 1)
        message = mail.outbox[0]
        self.assertEqual(message.subject, 'test match delivery')
        self.assertIn('"Reports" <reports', message.from_email)
        self.assertEqual(message.attachments[0][0],
                         'report_%s.pdf.gpg' % sent_report_id)

    def test_user_identifier(self):
        user_with_email = User.objects.create_user(username="******",
                                                   password="******",
                                                   email="*****@*****.**")
        report = Report(owner=user_with_email)
        report.encrypt_report(self.decrypted_report, "a key a key a key")
        report.save()
        pdf_report = PDFFullReport(report, self.decrypted_report)
        output = pdf_report.generate_pdf_report(recipient=None, report_id=None)
        exported_report = BytesIO(output)
        pdfReader = PyPDF2.PdfFileReader(exported_report)
        self.assertIn("Submitted by: [email protected]",
                      pdfReader.getPage(0).extractText())
Esempio n. 40
0
    def test_done_serializes_questions(self, mockReport):
        self.maxDiff = None

        radio_button_q = RadioButton.objects.create(text="this is a radio button question", page=self.page2)
        for i in range(5):
            Choice.objects.create(text="This is choice %i" % i, question=radio_button_q)
        wizard = EncryptedFormWizard.wizard_factory()()

        PageOneForm = wizard.form_list[0]
        PageTwoForm = wizard.form_list[1]
        KeyForm = wizard.form_list[2]

        page_one = PageOneForm({'question_%i' % self.question1.pk: 'test answer'})
        page_one.is_valid()
        page_two = PageTwoForm({'question_%i' % self.question2.pk: 'another answer to a different question',
                                'question_%i' % radio_button_q.pk: radio_button_q.choice_set.all()[2].pk})
        page_two.is_valid()
        key_form = KeyForm({'key': self.report_key, 'key2': self.report_key})
        key_form.is_valid()

        object_ids = [choice.pk for choice in radio_button_q.choice_set.all()]
        selected_id = object_ids[2]
        object_ids.insert(0, radio_button_q.pk)
        object_ids.insert(0, selected_id)
        object_ids.insert(0, self.question2.pk)
        object_ids.insert(0, self.question1.pk)

        json_report = """[
    { "answer": "test answer",
      "id": %i,
      "section": 1,
      "question_text": "first question",
      "type": "SingleLineText"
    },
    { "answer": "another answer to a different question",
      "id": %i,
      "section": 1,
      "question_text": "2nd question",
      "type": "SingleLineText"
    },
    { "answer": "%i",
      "id": %i,
      "section": 1,
      "question_text": "this is a radio button question",
            "choices": [{"id": %i, "choice_text": "This is choice 0"},
                  {"id": %i, "choice_text": "This is choice 1"},
                  {"id": %i, "choice_text": "This is choice 2"},
                  {"id": %i, "choice_text": "This is choice 3"},
                  {"id": %i, "choice_text": "This is choice 4"}],
      "type": "RadioButton"
    }
  ]""" % tuple(object_ids)

        mock_report = Report()
        mock_report.save = Mock()
        mock_report.owner = self.request.user
        mockReport.return_value = mock_report

        def check_json():
            self.assertEqual(sort_json(mock_report.decrypted_report(self.report_key)),
                             sort_json(json_report))

        mock_report.save.side_effect = check_json

        self._get_wizard_response(wizard, form_list=[page_one, page_two, key_form], request=self.request)
        mock_report.save.assert_any_call()
Esempio n. 41
0
 def test_entered_into_matching_is_blank_before_entering_into_matching(self):
     report = Report(owner = self.user)
     report.encrypt_report("test report", "key")
     report.save()
     self.assertIsNone(Report.objects.first().entered_into_matching)
Esempio n. 42
0
 def create_match(self, user, identifier):
     report = Report(owner = user)
     report.encrypt_report("test report 1", "key")
     report.save()
     return MatchReport.objects.create(report=report, contact_phone='phone',
                                       contact_email='*****@*****.**', identifier=identifier)
Esempio n. 43
0
 def test_reports_have_owners(self):
     report = Report()
     report.owner = self.user
     report.save()
     self.assertIn(report, self.user.report_set.all())
Esempio n. 44
0
 def test_cannot_save_empty_reports(self):
     report = Report(owner=self.user, encrypted=b'')
     with self.assertRaises(ValidationError):
         report.save()
         report.full_clean()
Esempio n. 45
0
    def test_done_serializes_questions(self, mockReport):
        self.maxDiff = None

        radio_button_q = RadioButton.objects.create(
            text="this is a radio button question", page=self.page2)
        for i in range(5):
            Choice.objects.create(text="This is choice %i" % i,
                                  question=radio_button_q)
        wizard = EncryptedFormWizard.wizard_factory()()

        PageOneForm = wizard.form_list[0]
        PageTwoForm = wizard.form_list[1]
        KeyForm = wizard.form_list[2]

        page_one = PageOneForm(
            {'question_%i' % self.question1.pk: 'test answer'})
        page_one.is_valid()
        page_two = PageTwoForm({
            'question_%i' % self.question2.pk:
            'another answer to a different question',
            'question_%i' % radio_button_q.pk:
            radio_button_q.choice_set.all()[2].pk
        })
        page_two.is_valid()
        key_form = KeyForm({'key': self.report_key, 'key2': self.report_key})
        key_form.is_valid()

        object_ids = [choice.pk for choice in radio_button_q.choice_set.all()]
        selected_id = object_ids[2]
        object_ids.insert(0, radio_button_q.pk)
        object_ids.insert(0, selected_id)
        object_ids.insert(0, self.question2.pk)
        object_ids.insert(0, self.question1.pk)

        json_report = """[
    { "answer": "test answer",
      "id": %i,
      "section": 1,
      "question_text": "first question",
      "type": "SingleLineText"
    },
    { "answer": "another answer to a different question",
      "id": %i,
      "section": 1,
      "question_text": "2nd question",
      "type": "SingleLineText"
    },
    { "answer": "%i",
      "id": %i,
      "section": 1,
      "question_text": "this is a radio button question",
            "choices": [{"id": %i, "choice_text": "This is choice 0"},
                  {"id": %i, "choice_text": "This is choice 1"},
                  {"id": %i, "choice_text": "This is choice 2"},
                  {"id": %i, "choice_text": "This is choice 3"},
                  {"id": %i, "choice_text": "This is choice 4"}],
      "type": "RadioButton"
    }
  ]""" % tuple(object_ids)

        mock_report = Report()
        mock_report.save = Mock()
        mock_report.owner = self.request.user
        mockReport.return_value = mock_report

        def check_json():
            self.assertEqual(
                sort_json(mock_report.decrypted_report(self.report_key)),
                sort_json(json_report))

        mock_report.save.side_effect = check_json

        self._get_wizard_response(wizard,
                                  form_list=[page_one, page_two, key_form],
                                  request=self.request)
        mock_report.save.assert_any_call()
Esempio n. 46
0
class EditRecordFormTest(RecordFormBaseTest):
    record_form_url = '/test_reports/edit/%s/'

    def setUp(self):
        super().setUp()

        User.objects.create_user(username='******', password='******')
        self.client.login(username='******', password='******')
        self.request = HttpRequest()
        self.request.GET = {}
        self.request.method = 'GET'
        self.request.user = User.objects.get(username='******')

        self.report_text = """[
    { "answer": "test answer",
      "id": %i,
      "section": 1,
      "question_text": "first question",
      "type": "SingleLineText"
    },
    { "answer": "another answer to a different question",
      "id": %i,
      "section": 1,
      "question_text": "2nd question",
      "type": "SingleLineText"
    }
  ]""" % (self.question1.pk, self.question2.pk)
        self.report = Report(owner = self.request.user)
        self.report_key = 'bananabread! is not my key'
        self.report.encrypt_report(self.report_text, self.report_key)
        self.report.save()
        row = EvalRow()
        row.anonymise_record(action=EvalRow.CREATE, report=self.report, decrypted_text=self.report_text)
        row.save()

    def enter_edit_key(self):
        return self.client.post(
            (self.record_form_url % self.report.pk),
            data={'0-key': self.report_key,
                  'wizard_goto_step':1,
                  'form_wizard' + str(self.report.id) + '-current_step': 0},
            follow=True
        )

    def test_edit_record_page_renders_key_prompt(self):
        response = self.client.get(self.record_form_url % self.report.pk, follow=True)
        self.assertTemplateUsed(response, 'decrypt_record_for_edit.html')
        self.assertIsInstance(response.context['form'], SecretKeyForm)

    def test_edit_record_form_advances_to_second_page(self):
        response = self.enter_edit_key()
        self.assertTemplateUsed(response, 'record_form.html')
        self.assertIsInstance(response.context['form'], QuestionPageForm)
        self.assertContains(response, 'name="1-question_%i"' % self.question1.pk)
        self.assertNotContains(response, 'name="1-question_%i"' % self.question2.pk)

    def test_initial_is_passed_to_forms(self):
        response = self.enter_edit_key()
        form = response.context['form']
        self.assertIn('test answer', form.initial.values())
        self.assertIn('another answer to a different question', form.initial.values())

    def edit_record(self, record_to_edit):
        wizard = EncryptedFormWizard.wizard_factory(object_to_edit=record_to_edit)()

        KeyForm1 = wizard.form_list[0]
        PageOneForm = wizard.form_list[1]
        PageTwoForm = wizard.form_list[2]
        KeyForm2 = wizard.form_list[3]

        key_form_1 = KeyForm1({'key': self.report_key})
        key_form_1.is_valid()

        page_one = PageOneForm({'question_%i' % self.question1.pk: 'test answer'})
        page_one.is_valid()
        page_two = PageTwoForm({'question_%i' % self.question2.pk: 'edited answer to second question',})
        page_two.is_valid()
        key_form_2 = KeyForm2({'key': self.report_key})
        key_form_2.is_valid()

        self._get_wizard_response(wizard, form_list=[key_form_1, page_one, page_two, key_form_2], request = self.request)

    def test_edit_modifies_record(self):
        self.maxDiff = None

        json_report = """[
    { "answer": "test answer",
      "id": %i,
      "section": 1,
      "question_text": "first question",
      "type": "SingleLineText"
    },
    { "answer": "edited answer to second question",
      "id": %i,
      "section": 1,
      "question_text": "2nd question",
      "type": "SingleLineText"
    }
  ]"""  % (self.question1.pk, self.question2.pk)

        self.edit_record(self.report)
        self.assertEqual(Report.objects.count(), 1)
        self.assertEqual(sort_json(Report.objects.get(id=self.report.pk).decrypted_report(self.report_key)),
                         sort_json(json_report))

    def test_cant_edit_with_bad_key(self):
        self.maxDiff = None

        wizard = EncryptedFormWizard.wizard_factory(object_to_edit=self.report)()

        KeyForm1 = wizard.form_list[0]

        key_form_1 = KeyForm1({'key': "not the right key!!!"})
        self.assertFalse(key_form_1.is_valid())

    def test_cant_save_edit_with_bad_key(self):
        wizard = EncryptedFormWizard.wizard_factory(object_to_edit=self.report)()

        KeyForm1 = wizard.form_list[0]
        PageOneForm = wizard.form_list[1]
        PageTwoForm = wizard.form_list[2]
        KeyForm2 = wizard.form_list[3]

        key_form_1 = KeyForm1({'key': self.report_key})
        key_form_1.is_valid()

        page_one = PageOneForm({'question_%i' % self.question1.pk: 'test answer'})
        page_one.is_valid()
        page_two = PageTwoForm({'question_%i' % self.question2.pk: 'edited answer to second question',})
        page_two.is_valid()
        key_form_2 = KeyForm2({'key': "not the right key"})
        self.assertFalse(key_form_2.is_valid())
        with self.assertRaises(KeyError):
            self._get_wizard_response(wizard, form_list=[key_form_1, page_one, page_two, key_form_2], request = self.request)
        self.assertEqual(sort_json(Report.objects.get(id=self.report.pk).decrypted_report(self.report_key)),
                         sort_json(self.report_text))

    def test_edit_saves_anonymous_row(self):
        self.edit_record(self.report)
        self.assertEqual(EvalRow.objects.count(), 2)
        self.assertEqual(EvalRow.objects.last().action, EvalRow.EDIT)
        self.edit_record(self.report)
        self.assertEqual(EvalRow.objects.count(), 3)
        self.assertEqual(Report.objects.count(), 1)

    def test_edit_saves_original_record_if_no_data_exists(self):
        old_report = Report(owner = self.request.user)
        old_report.encrypt_report(self.report_text, self.report_key)
        old_report.save()

        self.assertEqual(EvalRow.objects.count(), 1)
        self.assertEqual(EvalRow.objects.filter(action=EvalRow.FIRST).count(), 0)

        self.edit_record(record_to_edit=old_report)
        self.assertEqual(EvalRow.objects.count(), 3)
        self.assertEqual(EvalRow.objects.filter(action=EvalRow.FIRST).count(), 1)
        self.assertEqual(EvalRow.objects.last().action, EvalRow.EDIT)
        self.assertEqual(EvalRow.objects.filter(action=EvalRow.FIRST).first().record_identifier, EvalRow.objects.last().record_identifier)
        self.assertNotEqual(EvalRow.objects.filter(action=EvalRow.FIRST).first().row, EvalRow.objects.last().row)
Esempio n. 47
0
 def test_entered_into_matching_is_blank_before_entering_into_matching(
         self):
     report = Report(owner=self.user)
     report.encrypt_report("test report", "key")
     report.save()
     self.assertIsNone(Report.objects.first().entered_into_matching)
Esempio n. 48
0
class ReportDeliveryTest(MatchTest):

    def setUp(self):
        super(ReportDeliveryTest, self).setUp()
        self.user = self.user1
        self.decrypted_report = """[
    { "answer": "test answer",
      "id": 1,
      "section": 1,
      "question_text": "first question",
      "type": "SingleLineText"
    },
    { "answer": "answer to 2nd question",
      "id": 2,
      "section": 1,
      "question_text": "2nd question",
      "type": "SingleLineText"
    }
  ]"""
        self.report = Report(owner=self.user)
        self.report.encrypt_report(self.decrypted_report, "a key a key a key")
        self.report.save()

    def test_pdf_full_report_is_generated(self):
        report = PDFFullReport(self.report, self.decrypted_report)
        output = report.generate_pdf_report(recipient=None, report_id=None)
        exported_report = BytesIO(output)
        pdfReader = PyPDF2.PdfFileReader(exported_report)
        self.assertIn("Reported by: dummy", pdfReader.getPage(0).extractText())
        self.assertIn("test answer", pdfReader.getPage(1).extractText())
        self.assertIn("answer to 2nd question", pdfReader.getPage(1).extractText())

    def test_submission_to_school(self):
        EmailNotification.objects.create(name='report_delivery', subject="test delivery", body="test body")
        report = PDFFullReport(self.report, self.decrypted_report)
        report.send_report_to_school()
        sent_report_id = SentFullReport.objects.latest('id').get_report_id()
        self.assertEqual(len(mail.outbox), 1)
        message = mail.outbox[0]
        self.assertEqual(message.subject, 'test delivery')
        self.assertIn('"Reports" <reports', message.from_email)
        self.assertEqual(message.attachments[0][0], 'report_%s.pdf.gpg' % sent_report_id)

    # TODO: test encryption of submitted report email

    def test_pdf_match_report_is_generated(self):
        match1_report_content = MatchReportContent(identifier='perp',
                                                   perp_name='Perperick',
                                                   email='*****@*****.**',
                                                   phone='555-555-1212',
                                                   contact_name='Una',
                                                   voicemail='Yes')
        match1 = self.create_match(self.user1, 'perp', match1_report_content)
        match2_report_content = MatchReportContent(identifier='perp',
                                                   perp_name='Perpy',
                                                   email='*****@*****.**',
                                                   phone='(000) 0000000',
                                                   contact_name='Ni',
                                                   notes='Please only call after 5pm')
        match2 = self.create_match(self.user2, 'perp', match2_report_content)
        report = PDFMatchReport([match1, match2], "perp")
        output = report.generate_match_report(report_id=1)
        exported_report = BytesIO(output)
        pdfReader = PyPDF2.PdfFileReader(exported_report)

        pdf_text = pdfReader.getPage(0).extractText()
        self.assertIn("Intended for: Title IX Coordinator Tatiana Nine", pdf_text)
        self.assertIn("Matching identifier: perp", pdf_text)
        self.assertIn("Name(s): Perpy, Perperick", pdf_text)
        # Report 1
        self.assertIn("Perpetrator name given: Perpy", pdf_text)
        self.assertIn("Reported by: ymmud", pdf_text)
        self.assertRegexpMatches(pdf_text,
                                 'Submitted to matching on: \d\d/\d\d/201\d @\d\d:\d\d[P|A]M')
        self.assertRegexpMatches(pdf_text,
                                 'Record created: \d\d/\d\d/201\d @\d\d:\d\d[P|A]M')
        self.assertIn("Full record submitted? No", pdf_text)
        self.assertIn("Name: Una", pdf_text)
        self.assertIn("Phone: 555-555-1212", pdf_text)
        self.assertIn("Voicemail preferences: Yes", pdf_text)
        self.assertIn("Email: [email protected]", pdf_text)
        self.assertIn("Notes on preferred contact time of day, gender of admin, etc.:\nNone provided", pdf_text)
        # Report 2
        self.assertIn("Perpetrator name given: Perperick", pdf_text)
        self.assertIn("Reported by: dummy", pdf_text)
        self.assertIn("Name: Ni", pdf_text)
        self.assertIn("Phone: (000) 0000000", pdf_text)
        self.assertIn("Voicemail preferences: None provided", pdf_text)
        self.assertIn("Email: [email protected]", pdf_text)
        self.assertIn(
            "Notes on preferred contact time of day, gender of admin, etc.:\nPlease only call after 5pm",
            pdf_text)

    def test_matches_to_school(self):
        EmailNotification.objects.create(name='match_delivery', subject="test match delivery", body="test match body")
        match1 = self.create_match(self.user1, 'dummy')
        match2 = self.create_match(self.user2, 'dummy')
        report = PDFMatchReport([match1, match2], "dummy")
        report.send_matching_report_to_school()
        sent_report_id = SentMatchReport.objects.latest('id').get_report_id()
        self.assertEqual(len(mail.outbox), 1)
        message = mail.outbox[0]
        self.assertEqual(message.subject, 'test match delivery')
        self.assertIn('"Reports" <reports', message.from_email)
        self.assertEqual(message.attachments[0][0], 'report_%s.pdf.gpg' % sent_report_id)

    def test_user_identifier(self):
        user_with_email = User.objects.create_user(username="******", password="******", email="*****@*****.**")
        report = Report(owner=user_with_email)
        report.encrypt_report(self.decrypted_report, "a key a key a key")
        report.save()
        pdf_report = PDFFullReport(report, self.decrypted_report)
        output = pdf_report.generate_pdf_report(recipient=None, report_id=None)
        exported_report = BytesIO(output)
        pdfReader = PyPDF2.PdfFileReader(exported_report)
        self.assertIn("Reported by: [email protected]", pdfReader.getPage(0).extractText())
Esempio n. 49
0
 def test_report_owner_is_not_optional(self):
     report = Report(encrypted=b'a report')
     with self.assertRaises(IntegrityError):
         report.save()
         report.full_clean()