예제 #1
0
 def translate(message_code, context={}, language='ar', enhanced=False):
     with translation.override(language):
         if enhanced:
             text = get_message(message_code).enhanced
         else:
             text = get_message(message_code).msg
         return text.format(**context)
예제 #2
0
 def test_no_such_citizen(self):
     data = {'national_id': '123456789012', 'fbr_number': '1234'}
     data.update(self.captcha)
     rsp = self.client.post(self.url, data=data)
     self.assertEqual(200, rsp.status_code)
     context = rsp.context
     self.assertIn('form', context)
     form = context['form']
     self.assertIn('national_id', form.errors)
     self.assertIn(get_message(constants.NID_INVALID).msg,
                   form.errors['national_id'])
     content = rsp.content.decode('utf-8')
     self.assertIn(get_message(constants.NID_INVALID).msg, content)
예제 #3
0
 def test_no_such_citizen(self):
     data = {'national_id': '123456789012', 'fbr_number': '1234'}
     data.update(self.captcha)
     rsp = self.client.post(self.url, data=data)
     self.assertEqual(200, rsp.status_code)
     context = rsp.context
     self.assertIn('form', context)
     form = context['form']
     self.assertIn('national_id', form.errors)
     self.assertIn(
         get_message(constants.NID_INVALID).msg, form.errors['national_id'])
     content = rsp.content.decode('utf-8')
     self.assertIn(get_message(constants.NID_INVALID).msg, content)
예제 #4
0
 def test_one_message_not_enhanced(self):
     # If there's an enhanced message available, but only one
     # outgoing message with the current error code, don't use
     # enhanced
     self.add_message("411", 999)
     r = Result("411", 999)
     self.assertEqual(get_message(999).msg, r.message)
예제 #5
0
 def test_with_context(self):
     # Messages can be formatted with context vars
     m = get_message(999)
     m.msg_en = "one: {one} two: {two} three: {three}"
     m.save()
     r = Result("", 999, dict(one=1, two=2, three=3))
     self.assertEqual("one: 1 two: 2 three: 3", r.message)
예제 #6
0
 def test_with_context(self):
     # Messages can be formatted with context vars
     m = get_message(999)
     m.msg_en = 'one: {one} two: {two} three: {three}'
     m.save()
     r = Result("", 999, dict(one=1, two=2, three=3))
     self.assertEqual('one: 1 two: 2 three: 3', r.message)
예제 #7
0
 def test_one_message_not_enhanced(self):
     # If there's an enhanced message available, but only one
     # outgoing message with the current error code, don't use
     # enhanced
     self.add_message("411", 999)
     r = Result("411", 999)
     self.assertEqual(get_message(999).msg, r.message)
예제 #8
0
파일: forms.py 프로젝트: chaabni/SmartElect
 def clean_national_id(self):
     national_id = long(self.cleaned_data['national_id'])
     citizen = get_citizen_by_national_id(national_id)
     if not citizen:
         raise ValidationError(get_message(constants.NID_INVALID).msg)
     self.citizen = citizen
     return national_id
예제 #9
0
 def clean_national_id(self):
     national_id = long(self.cleaned_data['national_id'])
     citizen = get_citizen_by_national_id(national_id)
     if not citizen:
         raise ValidationError(get_message(constants.NID_INVALID).msg)
     self.citizen = citizen
     return national_id
예제 #10
0
    def __init__(self, phone_number, message_code, context=None):
        self.message_code = message_code
        self.phone_number = phone_number
        context = context or {}

        message = get_message(self.message_code)

        # If we've sent the same message code to the same phone number
        # at least 3 times, after that start using an enhanced error
        # message text for that code.  (If we have one.)
        text = message.msg
        if message.enhanced and self._should_enhance():
            text = message.enhanced

        # :self.message is the formatted, final message

        # Default (if everything goes haywire below) to the message without parameters
        # filled in
        self.message = text
        try:
            self.message = text.format(**context)
        except KeyError as e:
            logger.error(
                "Translated message appears to have a parameter that we don't have a "
                "value for.  text = %r.  Exception = %s.", text, e)
            # Try just leaving it blank.
            try:
                key = e.args[0]
                context[key] = ''
                self.message = text.format(**context)
            except Exception as e:
                logger.error("Got second error. text = %r.  Exception = %s.",
                             text, e)
예제 #11
0
    def __init__(self, phone_number, message_code, context=None):
        self.message_code = message_code
        self.phone_number = phone_number
        context = context or {}

        message = get_message(self.message_code)

        # If we've sent the same message code to the same phone number
        # at least 3 times, after that start using an enhanced error
        # message text for that code.  (If we have one.)
        text = message.msg
        if message.enhanced and self._should_enhance():
            text = message.enhanced

        # :self.message is the formatted, final message

        # Default (if everything goes haywire below) to the message without parameters
        # filled in
        self.message = text
        try:
            self.message = text.format(**context)
        except KeyError as e:
            logger.error("Translated message appears to have a parameter that we don't have a "
                         "value for.  text = %r.  Exception = %s.", text, e)
            # Try just leaving it blank.
            try:
                key = e.args[0]
                context[key] = ''
                self.message = text.format(**context)
            except Exception as e:
                logger.error("Got second error. text = %r.  Exception = %s.", text, e)
예제 #12
0
 def test_context_two_missing_vars(self):
     # If a message has two vars we don't have values for, we punt
     # (just use the unformatted message)
     m = get_message(999)
     m.msg_en = "one: {one} two: {two} three: {three}"
     m.save()
     r = Result("", 999, dict(one=1))
     self.assertEqual(m.msg_en, r.message)
예제 #13
0
 def test_context_missing_var(self):
     # If a message has one var we don't have values for, we still carry on
     # we just leave the value blank
     m = get_message(999)
     m.msg_en = "one: {one} two: {two} three: {three}"
     m.save()
     r = Result("", 999, dict(one=1, two=2))
     self.assertEqual("one: 1 two: 2 three: ", r.message)
예제 #14
0
파일: forms.py 프로젝트: chaabni/SmartElect
 def clean(self):
     # Check FBRN against citizen. We need the national ID to have already
     # been validated, so do it in the general form clean() method.
     citizen = getattr(self, 'citizen', None)
     if citizen and 'fbr_number' in self.cleaned_data \
             and citizen.fbr_number != self.cleaned_data['fbr_number']:
         raise ValidationError(get_message(constants.FBRN_MISMATCH).msg)
     return self.cleaned_data
예제 #15
0
 def clean(self):
     # Check FBRN against citizen. We need the national ID to have already
     # been validated, so do it in the general form clean() method.
     citizen = getattr(self, 'citizen', None)
     if citizen and 'fbr_number' in self.cleaned_data \
             and citizen.fbr_number != self.cleaned_data['fbr_number']:
         raise ValidationError(get_message(constants.FBRN_MISMATCH).msg)
     return self.cleaned_data
예제 #16
0
 def test_context_missing_var(self):
     # If a message has one var we don't have values for, we still carry on
     # we just leave the value blank
     m = get_message(999)
     m.msg_en = 'one: {one} two: {two} three: {three}'
     m.save()
     r = Result("", 999, dict(one=1, two=2))
     self.assertEqual('one: 1 two: 2 three: ', r.message)
예제 #17
0
 def test_mixed_phones(self):
     # If the last three messages were the same code, but they weren't
     # all to our phone number, then don't use enhanced
     self.add_message("411", 999)
     self.add_message("410", 999)
     self.add_message("411", 999)
     r = Result("411", 999)
     self.assertEqual(get_message(999).msg, r.message)
예제 #18
0
 def test_mixed_phones(self):
     # If the last three messages were the same code, but they weren't
     # all to our phone number, then don't use enhanced
     self.add_message("411", 999)
     self.add_message("410", 999)
     self.add_message("411", 999)
     r = Result("411", 999)
     self.assertEqual(get_message(999).msg, r.message)
예제 #19
0
 def test_context_two_missing_vars(self):
     # If a message has two vars we don't have values for, we punt
     # (just use the unformatted message)
     m = get_message(999)
     m.msg_en = 'one: {one} two: {two} three: {three}'
     m.save()
     r = Result("", 999, dict(one=1))
     self.assertEqual(m.msg_en, r.message)
예제 #20
0
 def test_three_messages_enhanced(self):
     # If there's an enhanced message available, and three
     # messages with the current error code, use
     # enhanced
     self.add_message("411", 999)
     self.add_message("411", 999)
     self.add_message("411", 999)
     r = Result("411", 999)
     self.assertEqual(get_message(999).enhanced, r.message)
예제 #21
0
 def test_not_last_three(self):
     # If there were three in a row, but not the last three,
     # don't use enhanced
     self.add_message("411", 999)
     self.add_message("411", 999)
     self.add_message("411", 999)
     self.add_message("411", constants.MESSAGE_INCORRECT)
     r = Result("411", 999)
     self.assertEqual(get_message(999).msg, r.message)
예제 #22
0
 def test_mixed_messages(self):
     # If there are at least three messages with the same code,
     # but not the last three, then don't use enhanced.
     self.add_message("411", 999)
     self.add_message("411", constants.MESSAGE_INCORRECT)
     self.add_message("411", 999)
     self.add_message("411", 999)
     r = Result("411", 999)
     self.assertEqual(get_message(999).msg, r.message)
예제 #23
0
 def test_three_messages_enhanced(self):
     # If there's an enhanced message available, and three
     # messages with the current error code, use
     # enhanced
     self.add_message("411", 999)
     self.add_message("411", 999)
     self.add_message("411", 999)
     r = Result("411", 999)
     self.assertEqual(get_message(999).enhanced, r.message)
예제 #24
0
 def test_not_last_three(self):
     # If there were three in a row, but not the last three,
     # don't use enhanced
     self.add_message("411", 999)
     self.add_message("411", 999)
     self.add_message("411", 999)
     self.add_message("411", constants.MESSAGE_INCORRECT)
     r = Result("411", 999)
     self.assertEqual(get_message(999).msg, r.message)
예제 #25
0
 def test_mixed_messages(self):
     # If there are at least three messages with the same code,
     # but not the last three, then don't use enhanced.
     self.add_message("411", 999)
     self.add_message("411", constants.MESSAGE_INCORRECT)
     self.add_message("411", 999)
     self.add_message("411", 999)
     r = Result("411", 999)
     self.assertEqual(get_message(999).msg, r.message)
예제 #26
0
 def test_messages_are_cached(self):
     with self.assertNumQueries(1):
         get_message(self.number)
     with self.assertNumQueries(0):
         get_message(self.number)
     # If we save a message, the cache should be cleared and we
     # will have to query again
     MessageText.objects.get(number=self.number).save()
     with self.assertNumQueries(1):
         get_message(self.number)
     with self.assertNumQueries(0):
         get_message(self.number)
예제 #27
0
 def test_messages_are_cached(self):
     with self.assertNumQueries(1):
         get_message(self.number)
     with self.assertNumQueries(0):
         get_message(self.number)
     # If we save a message, the cache should be cleared and we
     # will have to query again
     MessageText.objects.get(number=self.number).save()
     with self.assertNumQueries(1):
         get_message(self.number)
     with self.assertNumQueries(0):
         get_message(self.number)
예제 #28
0
 def test_fbr_number_mismatch(self):
     citizen = CitizenFactory(fbr_number=1234)
     RegistrationFactory(citizen=citizen, archive_time=None)
     data = {'national_id': str(citizen.national_id), 'fbr_number': '2345678'}
     data.update(self.captcha)
     rsp = self.client.post(self.url, data=data)
     self.assertEqual(200, rsp.status_code)
     context = rsp.context
     self.assertIn('form', context)
     form = context['form']
     self.assertTrue(form.errors)
     content = rsp.content.decode('utf-8')
     self.assertIn(get_message(constants.FBRN_MISMATCH).msg, content)
예제 #29
0
 def test_fbr_number_mismatch(self):
     citizen = CitizenFactory(fbr_number=1234)
     RegistrationFactory(citizen=citizen, archive_time=None)
     data = {
         'national_id': str(citizen.national_id),
         'fbr_number': '2345678'
     }
     data.update(self.captcha)
     rsp = self.client.post(self.url, data=data)
     self.assertEqual(200, rsp.status_code)
     context = rsp.context
     self.assertIn('form', context)
     form = context['form']
     self.assertTrue(form.errors)
     content = rsp.content.decode('utf-8')
     self.assertIn(get_message(constants.FBRN_MISMATCH).msg, content)
예제 #30
0
 def test_cache_clearing(self):
     # we can add, change, and delete messages and we keep
     # getting the right answers, despite the cache
     MessageText.objects.filter(pk=self.number).delete()
     with self.assertRaises(ValueError):
         get_message(self.number)
     new_number = self.number + 1
     with self.assertRaises(ValueError):
         get_message(new_number)
     msg = MessageText.objects.create(number=new_number,
                                      msg_en="new Message",
                                      msg_ar="new Message (ar)")
     self.assertEqual("new Message", get_message(new_number).msg)
     msg.msg_en = "Newer message"
     msg.save()
     self.assertEqual("Newer message", get_message(new_number).msg)
예제 #31
0
 def test_cache_clearing(self):
     # we can add, change, and delete messages and we keep
     # getting the right answers, despite the cache
     MessageText.objects.filter(pk=self.number).delete()
     with self.assertRaises(ValueError):
         get_message(self.number)
     new_number = self.number + 1
     with self.assertRaises(ValueError):
         get_message(new_number)
     msg = MessageText.objects.create(
         number=new_number,
         msg_en="new Message",
         msg_ar="new Message (ar)"
     )
     self.assertEqual("new Message", get_message(new_number).msg)
     msg.msg_en = "Newer message"
     msg.save()
     self.assertEqual("Newer message", get_message(new_number).msg)
예제 #32
0
 def get_message_text(self):
     context = {
         'message_number': self.message_number,
         'reminder_number': self.reminder_number
     }
     return get_message(self.get_message_code()).msg.format(**context)
예제 #33
0
    def check_it_out(
        self,
        message,
        expected_response_code,
        expected_msg_type,
        expect_phone_activated,
        expect_report_saved,
        expect_center_opened,
        expect_votes_saved=DONT_CARE,
        # change the test environment:
        activation_center_opening_period=True,
        polling_report_period=True,
    ):
        """
        "Send" the message and see if the response and side effects are what we expect.
        """
        conn = self.lookup_connections(identities=[self.NUMBER])[0]
        self.assertEqual(self.NUMBER, conn.identity)
        fields = {
            'to_addr': settings.REPORTS_SHORT_CODE,
            'from_addr': conn.identity
        }

        # These names are getting way long...
        opening_enabled_function = \
            'polling_reports.handlers.center_opening_enabled'
        with patch('polling_reports.handlers.polling_reports_enabled') as pr_enabled, \
                patch(opening_enabled_function) as ce_enabled:
            ce_enabled.return_value = activation_center_opening_period
            pr_enabled.return_value = polling_report_period
            self.receive(message, conn, fields=fields)

        actual_response_code = self.get_last_response_code()
        actual_msg_type = self.get_last_response().sms.msg_type

        if expected_response_code not in (DONT_CARE, actual_response_code):
            expected_label = get_message_label(expected_response_code)
            actual_label = get_message_label(actual_response_code)
            self.fail("Expected response code was %s (%s), got %s (%s)" %
                      (expected_response_code, expected_label,
                       actual_response_code, actual_label))
        if expected_msg_type not in (DONT_CARE, actual_msg_type):
            self.fail("Expected msg_type was %s, got %s" %
                      (expected_msg_type, actual_msg_type))
        if expect_phone_activated is not DONT_CARE:
            exists = StaffPhone.objects.filter(
                phone_number=self.NUMBER).exists()
            if expect_phone_activated:
                self.assertTrue(exists)
            else:
                self.assertFalse(exists)
        if expect_report_saved is not DONT_CARE:
            exists = PollingReport.objects.all().exists()
            if expect_report_saved:
                self.assertTrue(exists)
            else:
                self.assertFalse(exists)
        if expect_center_opened is not DONT_CARE:
            exists = CenterOpen.objects.all().exists()
            if expect_center_opened:
                self.assertTrue(exists)
            else:
                self.assertFalse(exists)
        if expect_votes_saved is not DONT_CARE:
            exists = PreliminaryVoteCount.objects.all().exists()
            if expect_votes_saved:
                self.assertTrue(exists)
            else:
                self.assertFalse(exists)

        # Also test that the message came back in Arabic, just to be safe,
        # by getting the code's message in arabic. Just look at the part up
        # to the first replaceable parameter, that's enough to make sure we
        # used the right language.
        with override(language='ar'):
            expected_message = get_message(expected_response_code).msg
        # Strip off everything from the first replaceable parameter
        if '{' in expected_message:
            offset = expected_message.find('{')
            expected_message = expected_message[:offset]
        if '%s' in expected_message:
            offset = expected_message.find('%s')
            expected_message = expected_message[:offset]
        actual_message = self.get_last_response_message()
        self.assertTrue(actual_message.startswith(expected_message),
                        msg="Expected %r to start with %r" %
                        (actual_message, expected_message))
예제 #34
0
 def test_get_message_success(self):
     msg = get_message(self.number)
     self.assertEqual(msg.pk, self.msg.pk)
예제 #35
0
 def test_get_message_nonesuch(self):
     with self.assertRaises(ValueError):
         get_message(self.number + 1)
예제 #36
0
 def get_message_code_display(self):
     try:
         m = get_message(self.message_code)
     except ValueError:
         return _("Obsolete message code: {}").format(self.message_code)
     return m.label
예제 #37
0
    def check_it_out(self,
                     message,
                     expected_response_code,
                     expected_msg_type,
                     expect_phone_activated,
                     expect_report_saved,
                     expect_center_opened,
                     expect_votes_saved=DONT_CARE,
                     # change the test environment:
                     activation_center_opening_period=True,
                     polling_report_period=True,
                     ):
        """
        "Send" the message and see if the response and side effects are what we expect.
        """
        conn = self.lookup_connections(identities=[self.NUMBER])[0]
        self.assertEqual(self.NUMBER, conn.identity)
        fields = {'to_addr': settings.REPORTS_SHORT_CODE,
                  'from_addr': conn.identity}

        # These names are getting way long...
        opening_enabled_function = \
            'polling_reports.handlers.center_opening_enabled'
        with patch('polling_reports.handlers.polling_reports_enabled') as pr_enabled, \
                patch(opening_enabled_function) as ce_enabled:
            ce_enabled.return_value = activation_center_opening_period
            pr_enabled.return_value = polling_report_period
            self.receive(message, conn, fields=fields)

        actual_response_code = self.get_last_response_code()
        actual_msg_type = self.get_last_response().sms.msg_type

        if expected_response_code not in (DONT_CARE, actual_response_code):
            expected_label = get_message_label(expected_response_code)
            actual_label = get_message_label(actual_response_code)
            self.fail("Expected response code was %s (%s), got %s (%s)" %
                      (expected_response_code, expected_label,
                       actual_response_code, actual_label))
        if expected_msg_type not in (DONT_CARE, actual_msg_type):
            self.fail("Expected msg_type was %s, got %s" % (expected_msg_type, actual_msg_type))
        if expect_phone_activated is not DONT_CARE:
            exists = StaffPhone.objects.filter(phone_number=self.NUMBER).exists()
            if expect_phone_activated:
                self.assertTrue(exists)
            else:
                self.assertFalse(exists)
        if expect_report_saved is not DONT_CARE:
            exists = PollingReport.objects.all().exists()
            if expect_report_saved:
                self.assertTrue(exists)
            else:
                self.assertFalse(exists)
        if expect_center_opened is not DONT_CARE:
            exists = CenterOpen.objects.all().exists()
            if expect_center_opened:
                self.assertTrue(exists)
            else:
                self.assertFalse(exists)
        if expect_votes_saved is not DONT_CARE:
            exists = PreliminaryVoteCount.objects.all().exists()
            if expect_votes_saved:
                self.assertTrue(exists)
            else:
                self.assertFalse(exists)

        # Also test that the message came back in Arabic, just to be safe,
        # by getting the code's message in arabic. Just look at the part up
        # to the first replaceable parameter, that's enough to make sure we
        # used the right language.
        with override(language='ar'):
            expected_message = get_message(expected_response_code).msg
        # Strip off everything from the first replaceable parameter
        if '{' in expected_message:
            offset = expected_message.find('{')
            expected_message = expected_message[:offset]
        if '%s' in expected_message:
            offset = expected_message.find('%s')
            expected_message = expected_message[:offset]
        actual_message = self.get_last_response_message()
        self.assertTrue(actual_message.startswith(expected_message),
                        msg="Expected %r to start with %r" % (actual_message, expected_message))
예제 #38
0
 def test_no_context(self):
     # Test it works without passing a context
     # This also tests that with no outgoing messages, we don't use
     # the enhanced message
     r = Result("", 999)
     self.assertEqual(get_message(999).msg, r.message)
예제 #39
0
 def test_no_context(self):
     # Test it works without passing a context
     # This also tests that with no outgoing messages, we don't use
     # the enhanced message
     r = Result("", 999)
     self.assertEqual(get_message(999).msg, r.message)
예제 #40
0
 def test_get_message_nonesuch(self):
     with self.assertRaises(ValueError):
         get_message(self.number + 1)
예제 #41
0
 def test_get_message_success(self):
     msg = get_message(self.number)
     self.assertEqual(msg.pk, self.msg.pk)
예제 #42
0
파일: tasks.py 프로젝트: chaabni/SmartElect
 def get_message_text(self):
     context = {'message_number': self.message_number,
                'reminder_number': self.reminder_number}
     return get_message(self.get_message_code()).msg.format(**context)