示例#1
0
 def test_registration_process_for_gem(self):
     self.create_attribute()
     self.create_role_categories()
     Script.objects.filter(slug='edtrac_autoreg').update(enabled=True)
     self.fake_incoming('join')
     check_progress(self.auto_reg_script)
     self.assertEqual(
         self.role_poll.question,
         Message.objects.filter(direction='O').order_by('-date')[0].text)
     self.fake_incoming('4')
     #self.create_response_category('4',self.gem_category)
     check_progress(self.auto_reg_script)
     self.assertEqual(
         self.district_poll.question,
         Message.objects.filter(direction='O').order_by('-date')[0].text)
     self.fake_incoming('Kamapala')
     check_progress(self.auto_reg_script)
     self.assertEqual(
         self.subcounty_poll.question,
         Message.objects.filter(direction='O').order_by('-date')[0].text)
     self.fake_incoming('Kampala')
     check_progress(self.auto_reg_script)
     self.assertEqual(
         self.name_poll.question,
         Message.objects.filter(direction='O').order_by('-date')[0].text)
     self.fake_incoming('test mctester')
     check_progress(self.auto_reg_script)
     self.assertEqual(
         self.welcome_step.message,
         Message.objects.filter(direction='O').order_by('-date')[0].text)
 def test_messages_are_handled_in_education_app(self):
     schedule_script_now(grp=self.head_teacher_group.name,slug=self.teachers_weekly_script.slug)
     check_progress(self.teachers_weekly_script)
     with patch('script.app.App.handle') as mock_method:
         fake_incoming("dummy response"
             ,self.emis_reporter1)
         assert not mock_method.called
    def handle(self, *args, **options):
        if len(args) < 1:
            print(
                "usage: python manage.py transition_registration_script <sender number> [server ip (2.2.2.2)]"
            )
            exit(-1)

        if len(args) == 2:
            self.server_ip = args[1]
        else:
            self.server_ip = "2.2.2.2"

        try:
            self.send_join_message(args)

            self.transition_through_first_step()

            print "starting session as [%s]" % self.sender_number

            self.start_interactive_console()

        except Exception:
            self.update_script_progress_object()
            check_progress(self.script_progress_object.script)
            call_command('loaddata',
                         "0004_migration_initial_data",
                         interactive=True)
            print("Congratulations! Registration complete. Cya.")
            exit()
    def test_autoreg_luo(self):
        #fake luo join message
        donyo = 'Donyo'
        self.fakeIncoming(donyo, self.connection2)

        #at this point 1 script shd have been created
        self.assertEquals(ScriptProgress.objects.count(), 1)
        script_prog2 = ScriptProgress.objects.order_by('pk')[0]
        #make sure the luo guy was dumped into the luo script
        self.assertEquals(script_prog2.script.slug, 'ureport_autoreg_luo2')
        res_count = Message.objects.filter(direction='O', connection=self.connection2).count()
        check_progress(script_prog2.script)

        response = Message.objects.filter(direction='O', connection=self.connection2)
        if response.exists() and not response.count() == res_count:
            response = response.latest('date').text
        else:
            response = None
        self.assertEquals(response, script_prog2.script.steps.get(order=0).message)

        self.fake_script_dialog(script_prog2, script_prog2.connection,
                                [ \
                                    ('contactdistrict', 'kampala'), \
                                    ('contactage', '19'), \
                                    ('contactgender', 'm'), \
                                    ('contactvillage', 'makindye'), \
                                    ])

        contact2 = Contact.objects.get(connection=script_prog2.connection)
        self.assertEquals(contact2.language, 'ach')
 def test_should_send_message_if_invalid_response_received(self):
     schedule_script_now(grp=self.head_teacher_group.name,slug=self.teachers_weekly_script.slug)
     check_progress(self.teachers_weekly_script)
     fake_incoming("dummy response",self.emis_reporter1)
     check_progress(self.teachers_weekly_script)
     expected = 'The answer you have provided is not in the correct format. Use figures like 3 to answer the question'
     self.assertTrue(expected in Message.objects.filter(direction='O',connection=self.emis_reporter1.connection_set.all()[0]).values_list('text',flat=True))
    def handle(self, *args, **options):
        if len(args) < 1:
            print("usage: python manage.py transition_registration_script <sender number> [server ip (2.2.2.2)]")
            exit(-1)

        if len(args) == 2:
            self.server_ip = args[1]
        else:
            self.server_ip = "2.2.2.2"

        try:
            self.send_join_message(args)

            self.transition_through_first_step()

            print "starting session as [%s]" % self.sender_number

            self.start_interactive_console()


        except Exception:
            self.update_script_progress_object()
            check_progress(self.script_progress_object.script)
            call_command('loaddata', "0004_migration_initial_data", interactive=True)
            print("Congratulations! Registration complete. Cya.")
            exit()
示例#7
0
 def test_should_reject_numeric_data_thats_implausibly_large(self):
     schedule_script_now(self.head_teacher_group.name, slug=self.teachers_weekly_script.slug)
     check_progress(self.teachers_weekly_script)
     fake_incoming("20 boys", self.emis_reporter1)
     fake_incoming("5001 boys", self.emis_reporter2)
     result = get_numeric_data([self.p3_boys_absent_poll], [self.kampala_district], self.term_range)
     self.assertEqual(20, result)
示例#8
0
 def test_should_return_location_numeric_data_given_a_poll_and_time_range(self):
     schedule_script_now(self.head_teacher_group.name, slug=self.teachers_weekly_script.slug)
     check_progress(self.teachers_weekly_script)
     fake_incoming("20 boys", self.emis_reporter1)
     fake_incoming("10 boys", self.emis_reporter2)
     result = get_numeric_data_for_location([self.p3_boys_absent_poll], [self.kampala_district], self.term_range)
     self.assertEqual(30, result[self.kampala_district.id])
 def test_should_return_10_given_reporter_responds_10_to_boys_enrollment_poll(self):
     schedule_script_now(grp=self.head_teacher_group.name, slug = self.head_teachers_termly_script.slug)
     check_progress(self.head_teachers_termly_script)
     fake_incoming("10", self.emis_reporter1)
     enrolled_boys = get_enrolled_pupils(self.emis_reporter1.connection_set.all()[0], self.p6_boys_enroll_poll.name,
         settings.SCHOOL_TERM_START, settings.SCHOOL_TERM_END)
     self.assertEqual(10, enrolled_boys)
示例#10
0
    def test_gendered_text_responses(self):
        params = {
            "description":
            "A response value for a Poll with expected text responses",
            "datatype": "text",
            "enum_group": None,
            "required": False,
            "type": None,
            "slug": "poll_text_value",
            "name": "Text"
        }
        Attribute.objects.get_or_create(**params)

        schedule_script_now(self.smc_group.name,
                            slug=self.head_teacher_weekly_script.slug)
        check_progress(self.head_teacher_weekly_script)
        fake_incoming("yes", self.emis_reporter3)

        male_yes_result = gendered_text_responses(self.term_range,
                                                  [self.kampala_district],
                                                  ['Yes', 'YES', 'yes'], 'M')
        male_no_result = gendered_text_responses(self.term_range,
                                                 [self.kampala_district],
                                                 ['No', 'NO', 'no'], 'M')
        female_yes_result = gendered_text_responses(self.term_range,
                                                    [self.kampala_district],
                                                    ['Yes', 'YES', 'yes'], 'F')
        female_no_result = gendered_text_responses(self.term_range,
                                                   [self.kampala_district],
                                                   ['No', 'NO', 'no'], 'F')

        self.assertEqual(1, male_yes_result)
        self.assertEqual(0, male_no_result)
        self.assertEqual(0, female_yes_result)
        self.assertEqual(0, female_no_result)
示例#11
0
    def test_autoreg_luo(self):
        #fake luo join message
        donyo = 'Donyo'
        self.fakeIncoming(donyo, self.connection2)

        #at this point 1 script shd have been created
        self.assertEquals(ScriptProgress.objects.count(), 1)
        script_prog2 = ScriptProgress.objects.order_by('pk')[0]
        #make sure the luo guy was dumped into the luo script
        self.assertEquals(script_prog2.script.slug, 'ureport_autoreg_luo2')
        res_count = Message.objects.filter(
            direction='O', connection=self.connection2).count()
        check_progress(script_prog2.script)

        response = Message.objects.filter(direction='O',
                                          connection=self.connection2)
        if response.exists() and not response.count() == res_count:
            response = response.latest('date').text
        else:
            response = None
        self.assertEquals(response,
                          script_prog2.script.steps.get(order=0).message)

        self.fake_script_dialog(script_prog2, script_prog2.connection,
                                [ \
                                    ('contactdistrict', 'kampala'), \
                                    ('contactage', '19'), \
                                    ('contactgender', 'm'), \
                                    ('contactvillage', 'makindye'), \
                                    ])

        contact2 = Contact.objects.get(connection=script_prog2.connection)
        self.assertEquals(contact2.language, 'ach')
 def reschedule(self):
     roster = {"edtrac_p3_teachers_weekly": [self.poll_response_current_week_date.date()]}
     get_day = lambda: self.poll_response_current_week_date.date() - timedelta(days=1)
     schedule(self.connection1, self.script, roster=roster, get_day=get_day)
     schedule(self.connection2, self.script, roster=roster, get_day=get_day)
     schedule(self.connection3, self.script, roster=roster, get_day=get_day)
     check_progress(self.script)
示例#13
0
    def test_gendered_text_responses(self):
        params = {
            "description": "A response value for a Poll with expected text responses",
            "datatype": "text",
            "enum_group": None,
            "required": False,
            "type": None,
            "slug": "poll_text_value",
            "name": "Text"
        }
        Attribute.objects.get_or_create(**params)

        schedule_script_now(self.smc_group.name, slug=self.head_teacher_weekly_script.slug)
        check_progress(self.head_teacher_weekly_script)
        fake_incoming("yes", self.emis_reporter3)

        male_yes_result = gendered_text_responses(self.term_range, [self.kampala_district], ['Yes', 'YES', 'yes'], 'M')
        male_no_result = gendered_text_responses(self.term_range, [self.kampala_district], ['No', 'NO', 'no'], 'M')
        female_yes_result = gendered_text_responses(self.term_range, [self.kampala_district], ['Yes', 'YES', 'yes'], 'F')
        female_no_result = gendered_text_responses(self.term_range, [self.kampala_district],  ['No', 'NO', 'no'], 'F')

        self.assertEqual(1, male_yes_result)
        self.assertEqual(0, male_no_result)
        self.assertEqual(0, female_yes_result)
        self.assertEqual(0, female_no_result)
示例#14
0
 def test_messages_are_handled_in_education_app(self):
     schedule_script_now(grp=self.head_teacher_group.name,
                         slug=self.teachers_weekly_script.slug)
     check_progress(self.teachers_weekly_script)
     with patch('script.app.App.handle') as mock_method:
         fake_incoming("dummy response", self.emis_reporter1)
         assert not mock_method.called
 def trigger_next_step(self):
     self.script_progress_object = ScriptProgress.objects.get(
         connection=self.user_connection)
     next_step = self.script_progress_object.get_next_step()
     next_step.start_offset = 0
     next_step.save()
     check_progress(next_step.script)
 def send_join_message(self, args):
     self.sender_number = int(args[0])
     self.send_sms("JOIN")
     self.user_connection = Connection.objects.get(
         identity=self.sender_number)
     self.update_script_progress_object()
     check_progress(self.script_progress_object.script)
示例#17
0
 def test_should_return_get_numeric_data_all_schools_for_locations(self):
     schedule_script_now(self.head_teacher_group.name,
                         slug=self.teachers_weekly_script.slug)
     check_progress(self.teachers_weekly_script)
     fake_incoming("20 boys", self.emis_reporter1)
     school_results = get_numeric_data_all_schools_for_locations(
         [self.p3_boys_absent_poll], [self.kampala_district],
         self.term_range)
     self.assertEqual({self.kampala_school.id: 20}, school_results)
示例#18
0
 def test_should_return_get_numeric_data_by_school(self):
     schedule_script_now(self.head_teacher_group.name,
                         slug=self.teachers_weekly_script.slug)
     check_progress(self.teachers_weekly_script)
     fake_incoming("20 boys", self.emis_reporter1)
     school_results = get_numeric_data_by_school([self.p3_boys_absent_poll],
                                                 [self.kampala_school],
                                                 self.term_range)
     self.assertEqual(20, sum(school_results))
示例#19
0
 def test_should_ignore_short_messages(self):
     schedule_script_now(grp=self.smc_group.name, slug='edtrac_head_teachers_weekly')
     check_progress(self.head_teachers_script)
     self.fake_incoming("No one in school today", self.emis_reporter9)
     self.fake_incoming("No one in school to", self.emis_reporter8)
     request = self.factory.get('/edtrac/error_messages/')
     request.user = self.admin_user
     list_of_error_messages = error_messages(request)
     self.assertEquals(1, list_of_error_messages.count())
示例#20
0
 def test_should_check_message_of_error_messages(self):
     schedule_script_now(grp=self.smc_group.name,slug='edtrac_head_teachers_weekly')
     check_progress(self.head_teachers_script)
     self.fake_incoming("2", self.emis_reporter6)
     self.fake_incoming("No one in school today", self.emis_reporter7) #error msg
     request = self.factory.get('/customer/messages/?error_msgs=True')
     request.user = self.admin_user
     resp = messages(request)
     self.assertEqual(1 ,resp.count())
示例#21
0
 def test_should_reject_numeric_data_thats_implausibly_large(self):
     schedule_script_now(self.head_teacher_group.name,
                         slug=self.teachers_weekly_script.slug)
     check_progress(self.teachers_weekly_script)
     fake_incoming("20 boys", self.emis_reporter1)
     fake_incoming("5001 boys", self.emis_reporter2)
     result = get_numeric_data([self.p3_boys_absent_poll],
                               [self.kampala_district], self.term_range)
     self.assertEqual(20, result)
示例#22
0
 def test_should_return_numeric_data_given_a_poll_location_and_time_range(
         self):
     schedule_script_now(self.head_teacher_group.name,
                         slug=self.teachers_weekly_script.slug)
     check_progress(self.teachers_weekly_script)
     fake_incoming("20 boys", self.emis_reporter1)
     fake_incoming("10 boys", self.emis_reporter2)
     result = get_numeric_data([self.p3_boys_absent_poll],
                               [self.kampala_district], self.term_range)
     self.assertEqual(30, result)
 def test_should_send_feedbacks_to_smc(self):
     schedule_script_now(grp= self.smc_group.name, slug=self.smc_weekly_script.slug)
     check_progress(self.smc_weekly_script)
     fake_incoming("yes", self.emis_reporter3)
     check_progress(self.smc_weekly_script)
     # self.assertEqual(2,Message.objects.filter(direction='O',connection=self.emis_reporter3.connection_set.all()[0]).count())
     self.assertEqual(1,Message.objects.filter(direction='O',connection=self.emis_reporter3.connection_set.all()[0]).count())#paisong feedback
     expected='Thank you for your report. Please continue to visit your school and report on what is happening.'
     # self.assertTrue(expected in Message.objects.filter(direction='O',connection=self.emis_reporter3.connection_set.all()[0]).values_list('text',flat=True))
     self.assertFalse(expected in Message.objects.filter(direction='O',connection=self.emis_reporter3.connection_set.all()[0]).values_list('text',flat=True))#pausing feedback
    def fake_incoming_message_and_check_script_progress(self, incoming_message_text):
        self.fakeIncoming(incoming_message_text, self.connection1)

        self.assertEquals(ScriptProgress.objects.count(), 1)

        registration_script_progress = ScriptProgress.objects.all().order_by('pk')[0]

        check_progress(registration_script_progress.script)

        return registration_script_progress
示例#25
0
 def test_should_return_none_if_all_messages_are_valid(self):
     schedule_script_now(grp=self.smc_group.name,slug='edtrac_head_teachers_weekly')
     check_progress(self.head_teachers_script)
     self.fake_incoming("2", self.emis_reporter6)
     self.fake_incoming("3", self.emis_reporter7)
     self.fake_incoming("2", self.emis_reporter8)
     request = self.factory.get('/customer/messages/?error_msgs=True')
     request.user = self.admin_user
     resp = messages(request)
     self.assertEqual(0,resp.count())
 def test_should_resend_poll_question_on_invalid_responses(self):
     schedule_script_now(grp=self.head_teacher_group.name,slug=self.teachers_weekly_script.slug)
     check_progress(self.teachers_weekly_script)
     fake_incoming("invalid response",self.emis_reporter1)
     check_progress(self.teachers_weekly_script)
     self.assertEqual(3,Message.objects.filter(direction='O',connection=self.emis_reporter1.connection_set.all()[0]).count())
     outgoing_messages = list(Message.objects.filter(direction='O',
                                               connection=self.emis_reporter1.connection_set.all()[0]).values_list(
         'text', flat=True))
     self.assertEqual(2,outgoing_messages.count(self.p3_boys_absent_poll.question))
 def test_should_return_0_given_no_reporter_responds_to_boys_enrollment_poll(
         self):
     schedule_script_now(grp=self.head_teacher_group.name,
                         slug=self.head_teachers_termly_script.slug)
     check_progress(self.head_teachers_termly_script)
     enrolled_boys = get_enrolled_pupils(
         self.emis_reporter1.connection_set.all()[0],
         self.p6_boys_enroll_poll.name, settings.SCHOOL_TERM_START,
         settings.SCHOOL_TERM_END)
     self.assertEqual(0, enrolled_boys)
示例#28
0
    def test_aggregated_report_has_school_id(self):
        schedule_script_now(self.head_teacher_group.name, slug=self.head_teachers_termly_script.slug)
        check_progress(self.head_teachers_termly_script)
        fake_incoming("10 boys", self.emis_reporter1)

        config_list = get_polls_for_keyword('all')

        collective_result, chart_results_model, school_percent,tooltip = \
            get_aggregated_report_for_district([self.kampala_district], [self.term_range], config_list)

        self.assertEqual(self.kampala_school_lubaga.id, collective_result['UMHS Lubaga']['id'])
示例#29
0
 def test_should_convert_error_messages_to_json(self):
     schedule_script_now(grp=self.smc_group.name, slug='edtrac_head_teachers_weekly')
     check_progress(self.head_teachers_script)
     self.fake_incoming("NO one in school today", self.emis_reporter7)
     self.fake_incoming("NO one in school today", self.emis_reporter8)
     request = self.factory.get('/edtrac/error_messages/')
     request.user = self.admin_user
     response = error_messages_as_json(request)
     error_messages = Message.objects.filter(direction="I").order_by('-date')
     error_messages_json = serialize("json", error_messages)
     self.assertEqual(response.content, error_messages_json)
示例#30
0
 def test_should_send_message_if_number_too_large(self):
     schedule_script_now(grp=self.head_teacher_group.name,
                         slug=self.teachers_weekly_script.slug)
     check_progress(self.teachers_weekly_script)
     fake_incoming("5001 boys", self.emis_reporter1)
     check_progress(self.teachers_weekly_script)
     expected = 'The answer you have provided is not in the correct format. Use figures like 3 to answer the question'
     self.assertTrue(expected in Message.objects.filter(
         direction='O',
         connection=self.emis_reporter1.connection_set.all()
         [0]).values_list('text', flat=True))
 def reschedule(self):
     roster = {
         'edtrac_p3_teachers_weekly':
         [self.poll_response_current_week_date.date()]
     }
     get_day = lambda: self.poll_response_current_week_date.date(
     ) - timedelta(days=1)
     schedule(self.connection1, self.script, roster=roster, get_day=get_day)
     schedule(self.connection2, self.script, roster=roster, get_day=get_day)
     schedule(self.connection3, self.script, roster=roster, get_day=get_day)
     check_progress(self.script)
示例#32
0
 def assertScriptSkips(self, connection, role, initial_question, final_question):
     connection = Connection.objects.create(identity=connection, backend=self.backend)
     script = Script.objects.get(slug='emis_autoreg')
     script_prog = ScriptProgress.objects.create(script=script, connection=connection, step=script.steps.get(poll__name=initial_question), status='C', num_tries=1)
     script_prog.set_time(datetime.datetime.now() - datetime.timedelta(1))
     self.fake_script_dialog(script_prog, connection, [\
         ('emis_role', role)
     ], emit_signal=False)
     check_progress(connection)
     script_prog = ScriptProgress.objects.get(connection=connection)
     self.assertEquals(script_prog.step.poll.name, final_question)
    def fake_incoming_message_and_check_script_progress(self, incoming_message_text, connection=None):
        connection = self.connection1 if connection is None else connection
        self.fakeIncoming(incoming_message_text, connection)

        self.assertEquals(ScriptProgress.objects.count(), 1)

        registration_script_progress = ScriptProgress.objects.all().order_by('-pk')[0]

        check_progress(registration_script_progress.script)

        return registration_script_progress
示例#34
0
 def test_should_give_head_teachers_absenteeism_percent(self):
     schedule_script_now(grp=self.smc_group.name,slug='edtrac_smc_weekly')
     check_progress(self.head_teachers_script)
     locations = [self.kampala_district]
     # self.head_teachers_poll.start()
     self.fake_incoming('no', self.emis_reporter5)
     self.fake_incoming('yes', self.emis_reporter6)
     config = get_polls_for_keyword('MaleHeadTeachers')
     result_by_location, result_by_time,school_percent = get_head_teachers_absent_over_time(locations,config[0], self.date_week)
     self.assertEqual(50, result_by_location.get('Kampala'))
     self.assertIn(50, result_by_time)
     self.assertEqual(25,school_percent) #n four weeks only once replies were sent
 def test_should_return_4_given_reporter_responds_4_to_girls_enrollment_poll(self):
     self.head_teachers_termly_script.steps.all().delete()
     self.head_teachers_termly_script.steps.add(
         ScriptStep.objects.create(script=self.head_teachers_termly_script, poll=self.p6_girls_enroll_poll, order=0,
         rule=ScriptStep.WAIT_MOVEON, start_offset=0, giveup_offset=7200))
     schedule_script_now(grp = self.head_teacher_group.name, slug = self.head_teachers_termly_script.slug)
     check_progress(self.head_teachers_termly_script)
     fake_incoming("4", self.emis_reporter1)
     check_progress(self.head_teachers_termly_script)
     enrolled_girls = get_enrolled_pupils(self.emis_reporter1.connection_set.all()[0],
         self.p6_girls_enroll_poll.name, settings.SCHOOL_TERM_START, settings.SCHOOL_TERM_END)
     self.assertEqual(4, enrolled_girls)
示例#36
0
    def testStrictRules(self):
        step = ScriptStep.objects.get(script__slug='test_autoreg', order=2)
        # modify setUp() ScriptStep 2 to be LENIENT
        step.rule = ScriptStep.STRICT_MOVEON
        step.num_tries = 2
        step.retry_offset = 60
        step.giveup_offset = 0
        step.save()

        # dummy progress, the question for step two has been sent out, now we check
        # that any response (even erroneous) advances progress
        connection = Connection.objects.all()[0]
        script = Script.objects.get(slug="test_autoreg")
        step = ScriptStep.objects.get(script__slug='test_autoreg', order=2)
        prog = ScriptProgress.objects.create(connection=connection, script=script, step=step, status='P')
        # create a dummy session
        session = ScriptSession.objects.create(connection=connection, script=script)
        incomingmessage = self.fakeIncoming('Jack cheese is a cheese that I like')
        response_message = incoming_progress(incomingmessage)
        self.assertEquals(response_message, "We didn't understand your response and it's very important to know about your cheese desires.  Please resend.")
        self.assertEquals(Response.objects.count(), 1)

        # refresh progress
        prog = ScriptProgress.objects.get(connection=connection)
        # check that this erroneous poll response DID update the progress,
        # since the rule is now lenient
        r = Response.objects.order_by('-date')[0]
        self.failUnless(r.has_errors)
        self.assertEquals(prog.step.order, 2)
        self.assertEquals(prog.status, 'P')
        self.assertEquals(prog.num_tries, 1)

        incomingmessage = self.fakeIncoming('Well, I also like cheddar')
        response_message = incoming_progress(incomingmessage)
        self.assertEquals(response_message, "We didn't understand your response and it's very important to know about your cheese desires.  Please resend.")
        self.assertEquals(Response.objects.count(), 2)

        # refresh progress
        prog = ScriptProgress.objects.get(connection=connection)
        # check that this erroneous poll response DID update the progress,
        # since the rule is now lenient
        r = Response.objects.order_by('-date')[0]
        self.failUnless(r.has_errors)
        self.assertEquals(prog.step.order, 2)
        self.assertEquals(prog.status, 'P')
        self.assertEquals(prog.num_tries, 2)

        check_progress(self.script)
        # refresh progress
        prog = ScriptProgress.objects.get(connection=connection)
        self.assertEquals(prog.step.order, 2)
        self.assertEquals(prog.status, 'C')
示例#37
0
    def fake_incoming_message_and_check_script_progress(
            self, incoming_message_text, connection=None):
        connection = self.connection1 if connection is None else connection
        self.fakeIncoming(incoming_message_text, connection)

        self.assertEquals(ScriptProgress.objects.count(), 1)

        registration_script_progress = ScriptProgress.objects.all().order_by(
            '-pk')[0]

        check_progress(registration_script_progress.script)

        return registration_script_progress
示例#38
0
    def test_aggregated_report_has_school_id(self):
        schedule_script_now(self.head_teacher_group.name,
                            slug=self.head_teachers_termly_script.slug)
        check_progress(self.head_teachers_termly_script)
        fake_incoming("10 boys", self.emis_reporter1)

        config_list = get_polls_for_keyword('all')

        collective_result, chart_results_model, school_percent,tooltip = \
            get_aggregated_report_for_district([self.kampala_district], [self.term_range], config_list)

        self.assertEqual(self.kampala_school_lubaga.id,
                         collective_result['UMHS Lubaga']['id'])
示例#39
0
 def test_should_return_top_5_error_messages_given_6_incoming_error_messages(self):
     schedule_script_now(grp=self.smc_group.name, slug='edtrac_head_teachers_weekly')
     check_progress(self.head_teachers_script)
     self.fake_incoming("No one in school today", self.emis_reporter7)
     self.fake_incoming("No one in school today", self.emis_reporter8)
     self.fake_incoming("No one in school today", self.emis_reporter6)
     self.fake_incoming("No one in school today", self.emis_reporter6)
     self.fake_incoming("No one in school today", self.emis_reporter6)
     self.fake_incoming("No one in school today", self.emis_reporter6)
     request = self.factory.get('/edtrac/error_messages/')
     request.user = self.admin_user
     response = error_messages(request)
     self.assertEquals(5, response.count())
 def test_should_check_message_string_for_teachers(self):
     schedule_script_now(grp= self.head_teacher_group.name, slug=self.head_teachers_weekly_script.slug)
     check_progress(self.head_teachers_weekly_script)
     fake_incoming("10", self.emis_reporter1)
     check_progress(self.head_teachers_weekly_script)
     fake_incoming("10", self.emis_reporter1)
     check_progress(self.head_teachers_weekly_script)
     fake_incoming("9", self.emis_reporter1)
     check_progress(self.head_teachers_weekly_script)
     fake_incoming("4", self.emis_reporter1)
     check_progress(self.head_teachers_weekly_script)
     expected ='Thankyou, Attendance for male teacher have been improved by 40percent Attendance for female teachers have been improved by 40percent'
     # self.assertTrue(expected in Message.objects.filter(direction='O',connection=self.emis_reporter1.connection_set.all()[0]).values_list('text',flat=True))
     self.assertFalse(expected in Message.objects.filter(direction='O',connection=self.emis_reporter1.connection_set.all()[0]).values_list('text',flat=True))#pausing feedbacks
示例#41
0
    def test_get_aggregated_report_data_single_indicator(self):
        schedule_script_now(self.head_teacher_group.name,
                            slug=self.head_teachers_termly_script.slug)
        check_progress(self.head_teachers_termly_script)
        fake_incoming("10 boys", self.emis_reporter1)
        check_progress(self.head_teachers_termly_script)
        fake_incoming("5 girls", self.emis_reporter1)
        schedule_script_now(self.head_teacher_group.name,
                            slug=self.teachers_weekly_script.slug)

        check_progress(self.teachers_weekly_script)
        fake_incoming("8 boys", self.emis_reporter1)
        check_progress(self.teachers_weekly_script)
        fake_incoming("1 girls", self.emis_reporter1)

        config_list = get_polls_for_keyword('P3Boys')
        collective_result, chart_results_model, school_percent,tooltip = \
            get_aggregated_report_data_single_indicator([self.kampala_district], [self.term_range], config_list)

        self.assertEqual(20.0, collective_result['P3 Boys'][0].values()[0])

        config_list = get_polls_for_keyword('P3Girls')
        collective_result, chart_results_model, school_percent, tooltip = get_aggregated_report_data_single_indicator(
            [self.kampala_district], [self.term_range], config_list)

        self.assertEqual(80.0, collective_result['P3 Girls'][0].values()[0])
示例#42
0
 def test_should_send_alert_messages_on_invalid_and_partial_responses(self):
     # 5 outgoing messages (1st) step 0 poll, (2nd) error msg alert (3rd) resend error poll (4th) step 1 msg (5th) Script completion alert
     schedule_script_now(grp=self.head_teacher_group.name,
                         slug=self.teachers_weekly_script.slug)
     check_progress(self.teachers_weekly_script)
     fake_incoming("Invalid", self.emis_reporter1)
     check_progress(self.teachers_weekly_script)
     expected = 'The answer you have provided is not in the correct format. Use figures like 3 to answer the question'
     self.assertTrue(expected in Message.objects.filter(
         direction='O',
         connection=self.emis_reporter1.connection_set.all()
         [0]).values_list('text', flat=True))
     time.sleep(3)
     check_progress(self.teachers_weekly_script)
     fake_incoming("3", self.emis_reporter1)
     check_progress(self.teachers_weekly_script)
     # self.assertEqual(5, Message.objects.filter(direction='O',connection=self.emis_reporter1.connection_set.all()[0]).count())
     self.assertEqual(
         4,
         Message.objects.filter(
             direction='O',
             connection=self.emis_reporter1.connection_set.all()
             [0]).count())  #pausing feedback
     expected = 'Thank you for participating. Remember to answer all your questions next Thursday.'
     # self.assertTrue(expected in Message.objects.filter(direction='O',connection=self.emis_reporter1.connection_set.all()[0]).values_list('text',flat=True))
     self.assertFalse(expected in Message.objects.filter(
         direction='O',
         connection=self.emis_reporter1.connection_set.all()
         [0]).values_list('text', flat=True))  #pausing feedback
 def testTransporterScript(self):
     #upload excel, this should result into creation of a delivery
    upload_file = open(os.path.join(os.path.join(os.path.realpath(os.path.dirname(__file__)),'fixtures'),'excel.xls'), 'rb')
    file_dict = {'excel_file': SimpleUploadedFile(upload_file.name, upload_file.read())}
    form = UploadForm({},file_dict)
    self.assertTrue(form.is_valid())
    msg = handle_excel_file(form.cleaned_data['excel_file'])
    
    #wait one day and upload another excel
    progress = ScriptProgress.objects.get(connection=Contact.objects.get(name='3ways shipping').default_connection)
    self.elapseTime(progress, 86401)
    upload_file = open(os.path.join(os.path.join(os.path.realpath(os.path.dirname(__file__)),'fixtures'),'excel2.xls'), 'rb')
    file_dict = {'excel_file': SimpleUploadedFile(upload_file.name, upload_file.read())}
    form = UploadForm({},file_dict)
    self.assertTrue(form.is_valid())
    msg = handle_excel_file(form.cleaned_data['excel_file'])
    
    #transporter has different shipments in shipped status
    self.assertEquals(Delivery.objects.filter(transporter=Contact.objects.get(name='3ways shipping'),status='S').count(), 4)
    
    #transporter does not advance to step 0 before the start_offset time has expired
    transporter_script=Script.objects.get(slug='transporter')
    default_connection = Contact.objects.get(name='3ways shipping').default_connection
    transporter_connection = default_connection.pk
    response = check_progress(transporter_connection)
    self.assertEquals(progress.step, None)
    self.assertEquals(response, None)
    
    #elapse 3 days
    self.elapseTime(progress, 259201)
    
    #transporter should advance to step 0 of transporter script for deliveries uploaded 3 or more days ago
    response = check_progress(transporter_connection)
    progress = ScriptProgress.objects.get(connection=transporter_connection, script=transporter_script)
    self.assertEquals(progress.step.order, 0)
    response_msg = Template(response)
    self.assertEquals(response_msg.render(Context(transporter_connection)), 'Has the consignment been delivered?')
    self.assertEquals(Delivery.objects.filter(transporter=Contact.objects.get(name='3ways shipping'), status='S').count(), 4)
    self.assertEquals(DeliveryBackLog.objects.get(delivery__waybill='kp/wb11/00037'), Delivery.objects.get(waybill='kp/wb11/00037'))
    
    #transporter sending delivery message does not affect delivery status
    incomingmessage = self.fakeIncoming('kp/wb11/00034 Delivered')
    response_message = incoming_progress(incomingmessage)
    self.assertEquals(response_message, "Thanks for your response")
    progress = ScriptProgress.objects.get(connection=transporter_connection, script=transporter_script)
    self.assertEquals(Delivery.objects.get(waybill='kp/wb11/00034').status, 'S')
    #new delivery objects are thrown into backlog since there is already an active script progression for admins
    self.assertEquals(DeliveryBackLog.objects.get(delivery__waybill='kp/wb11/00037'), Delivery.objects.get(waybill='kb/wb11/00037'))
示例#44
0
    def waitFlow(self, giveup=False):
        step = ScriptStep.objects.get(script__slug='test_autoreg', order=2)
        if giveup:
            step.rule = ScriptStep.WAIT_GIVEUP
        else:
            step.rule = ScriptStep.WAIT_MOVEON
        step.giveup_offset = 3600
        step.save()

        # dummy progress, the question for step two has been sent out, now we check
        # that any response (even erroneous) advances progress
        connection = Connection.objects.all()[0]
        script = Script.objects.get(slug="test_autoreg")
        prog = ScriptProgress.objects.create(connection=connection,
                                             script=script,
                                             step=step,
                                             status='P')
        session = ScriptSession.objects.create(connection=connection,
                                               script=script)
        # elapse past the moveon time
        self.elapseTime(prog, 3601)
        check_progress(self.script)
        # refresh progress
        if giveup:
            self.assertEquals(ScriptProgress.objects.count(), 0)
        else:
            prog = ScriptProgress.objects.get(connection=connection)
            self.assertEquals(prog.step.order, 2)
            self.assertEquals(prog.status, 'C')

            # elapse past the start time of the next step
            self.elapseTime(prog, 3610)
            res_count = Message.objects.filter(direction='O',
                                               connection=connection).count()
            check_progress(self.script)
            response = Message.objects.filter(direction='O',
                                              connection=connection)
            if response.exists() and not res_count == response.count():
                response = response.latest('date').text
            else:
                response = None
            self.assertEquals(response,
                              prog.step.script.steps.get(order=3).message)

            prog = ScriptProgress.objects.get(connection=connection)
            self.assertEquals(prog.step.order, 3)
            self.assertEquals(prog.status, 'P')
    def handle(self, **options):

        current = datetime.datetime.now()
        recipients = getattr(settings, 'ADMINS', None)
        if recipients:
            recipients = [email for name, email in recipients]
        if current.hour in range(int(options['e']), int(options['l'])):
            try:
                for script in Script.objects.filter(enabled=True):
                    check_progress(script)
                transaction.commit()
            except Exception, exc:
                transaction.rollback()
                print traceback.format_exc(exc)
                logger.debug(str(exc))
                if recipients:
                    send_mail('[Django] Error: check_script_progress cron', str(traceback.format_exc(exc)), '*****@*****.**', recipients, fail_silently=True)
 def testConsigneeScript(self):
    #upload excel, this should result into creation of a delivery
    upload_file = open(os.path.join(os.path.join(os.path.realpath(os.path.dirname(__file__)),'fixtures'),'excel.xls'), 'rb')
    file_dict = {'excel_file': SimpleUploadedFile(upload_file.name, upload_file.read())}
    form = UploadForm({},file_dict)
    self.assertTrue(form.is_valid())
    msg = handle_excel_file(form.cleaned_data['excel_file'])
    
    #wait one day and upload another excel
    self.elapseTime(progress[0], 86401)
    upload_file = open(os.path.join(os.path.join(os.path.realpath(os.path.dirname(__file__)),'fixtures'),'excel2.xls'), 'rb')
    file_dict = {'excel_file': SimpleUploadedFile(upload_file.name, upload_file.read())}
    form = UploadForm({},file_dict)
    self.assertTrue(form.is_valid())
    msg = handle_excel_file(form.cleaned_data['excel_file'])
    
    #consignee has different shipments in shipped status
    self.assertEquals(Delivery.objects.filter(consignee=Contact.objects.get(name='action against hunger', status='S')).count(), 2)
    
    #consignee has not yet advanced into the script (step 0)
    consignee_script=Script.objects.get(slug='consignee')
    consignee_connection = Contact.objects.get(name='action against hunger').default_connection
    progress = ScriptProgress.objects.create(connection=consignee_connection, script=consignee_script)
    response = check_progress(consignee_connection)
    self.assertEquals(progress.step, None)
    self.assertEquals(response, None)
    
    #elapse 3 days
    self.elapseTime(progress, 259201)
    
    #consignee should advance to step 0 of consignee script for deliveries uploaded 3 more days ago
    response = check_progress(consignee_connection)
    progress = ScriptProgress.objects.get(connection=consignee_connection, script=consignee_script)
    self.assertEquals(progress.step.order, 0)
    self.assertEquals(response, 'Has the consignment been delivered?')
    self.assertEquals(Delivery.objects.filter(consignee=Contact.objects.get(name='action against hunger', status='S')).count(), 2)
    self.assertEquals(DeliveryBackLog.objects.get(delivery__waybill='kp/wb11/00037'), Delivery.objects.get(waybill='kp/wb11/00037'))
    
    #consignee sending in a delivery message should complete the script for transporter and consignee and mark orders as delivered
    incomingmessage = self.fakeIncoming('kp/wb11/00034 COMPLETE kb/wb11/00037 COMPLETE')
    response_message = incoming_progress(incomingmessage)
    self.assertEquals(response_message, "Thanks for your response")
    progress = ScriptProgress.objects.get(connection=consignee_connection, script=consignee_script)
    self.assertEquals(Delivery.objects.filter(consignee=Contact.objects.get(name='action against hunger', status='D')).count(), 2)
    self.assertEquals(DeliveryBackLog.objects.filter(delivery__consignee=Contact.objects.get(name='action against hunger')), None)
     def testAdminScript(self):

        admin_script = Script.objects.get(slug='hq_supply_staff')
        admins = Contact.objects.filter(groups=Group.objects.filter(name='supply_admin'))
        progress = []
        for admin in admins:
            progress.append(ScriptProgress.objects.create(connection=admin.default_connection, script=admin_script))
        response = check_progress(admins[0].default_connection)
        progress[0] = ScriptProgress.objects.get(connection=admins[0].default_connection, script=admin_script)
        self.assertEquals(progress[0].step.order, 0)
        subject = Template(response.subject)
        self.assertEquals(subject.render(Context(admins[0].default_connection)), 'SupplyTracking: Reminder to Upload Consignments Excel Sheet')
        
        #wait for one day, the script should re-send the reminder to the admins to upload excel
        self.elapseTime(progress[0], 86401)
        response = check_progress(admins[0].default_connection)
        self.assertEquals(progress[0].step.order, 0)
        subject = Template(response.subject)
        self.assertEquals(subject.render(Context(admins[0].default_connection)), 'SupplyTracking: Reminder to Upload Consignments Excel Sheet')
        
        #upload a sheet we expect delivery objects to be created but not necessary trigger off any scripts
        upload_file = open(os.path.join(os.path.join(os.path.realpath(os.path.dirname(__file__)),'fixtures'),'excel.xls'), 'rb')
        file_dict = {'excel_file': SimpleUploadedFile(upload_file.name, upload_file.read())}
        form = UploadForm({},file_dict)
        self.assertTrue(form.is_valid())
        msg = handle_excel_file(form.cleaned_data['excel_file'])
        
        response = check_progress(admins[0].default_connection)
        progress[0] = ScriptProgress.objects.get(connection=admins[0].default_connection, script=admin_script)
        self.assertEquals(progress[0].step.order, 0)
        
        #wait for one day, the script should re-send the reminder to the admins to upload excel
        self.elapseTime(progress[0], 86401)
        response = check_progress(admins[0].default_connection)
        self.assertEquals(progress[0].step.order, 0)
        subject = Template(response.subject)
        self.assertEquals(subject.render(Context(admins[0].default_connection)), 'SupplyTracking: Reminder to Upload Consignments Excel Sheet')
        
        #wait for one day, upload another excel
        self.elapseTime(progress[0], 86401)
        upload_file = open(os.path.join(os.path.join(os.path.realpath(os.path.dirname(__file__)),'fixtures'),'excel2.xls'), 'rb')
        file_dict = {'excel_file': SimpleUploadedFile(upload_file.name, upload_file.read())}
        form = UploadForm({},file_dict)
        self.assertTrue(form.is_valid())
        msg = handle_excel_file(form.cleaned_data['excel_file'])
示例#48
0
 def test_should_check_message_string_for_teachers(self):
     schedule_script_now(grp=self.head_teacher_group.name,
                         slug=self.head_teachers_weekly_script.slug)
     check_progress(self.head_teachers_weekly_script)
     fake_incoming("10", self.emis_reporter1)
     check_progress(self.head_teachers_weekly_script)
     fake_incoming("10", self.emis_reporter1)
     check_progress(self.head_teachers_weekly_script)
     fake_incoming("9", self.emis_reporter1)
     check_progress(self.head_teachers_weekly_script)
     fake_incoming("4", self.emis_reporter1)
     check_progress(self.head_teachers_weekly_script)
     expected = 'Thankyou, Attendance for male teacher have been improved by 40percent Attendance for female teachers have been improved by 40percent'
     # self.assertTrue(expected in Message.objects.filter(direction='O',connection=self.emis_reporter1.connection_set.all()[0]).values_list('text',flat=True))
     self.assertFalse(expected in Message.objects.filter(
         direction='O',
         connection=self.emis_reporter1.connection_set.all()
         [0]).values_list('text', flat=True))  #pausing feedbacks
示例#49
0
    def test_get_count_for_yes_no_response_by_school(self):
        params = {
            "description": "A response value for a Poll with expected text responses",
            "datatype": "text",
            "enum_group": None,
            "required": False,
            "type": None,
            "slug": "poll_text_value",
            "name": "Text"
        }
        Attribute.objects.get_or_create(**params)

        schedule_script_now(self.smc_group.name, slug=self.head_teacher_weekly_script.slug)
        check_progress(self.head_teacher_weekly_script)
        fake_incoming("yes", self.emis_reporter3)

        yes, no = get_count_for_yes_no_response_by_school([self.head_teacher_monitoring_poll], [self.kampala_district], self.term_range)
        self.assertEqual({self.kampala_school.id : 1}, yes)
        self.assertEqual({}, no)
    def handle(self, **options):

        current = datetime.datetime.now()
        recipients = getattr(settings, 'ADMINS', None)
        if recipients:
            recipients = [email for name, email in recipients]
        if current.hour in range(int(options['e']), int(options['l'])):
            for script in Script.objects.filter(enabled=True):
                try:
                    check_progress(script)
                    transaction.commit()
                except Exception, exc:
                    transaction.rollback()
                    print traceback.format_exc(exc)
                    logger.debug(str(exc))
                    if recipients:
                        send_mail('[Django] Error: check_script_progress cron', str(traceback.format_exc(exc)), '*****@*****.**', recipients, fail_silently=True)
            else:
                transaction.rollback()
示例#51
0
 def test_should_send_feedbacks_to_smc(self):
     schedule_script_now(grp=self.smc_group.name,
                         slug=self.smc_weekly_script.slug)
     check_progress(self.smc_weekly_script)
     fake_incoming("yes", self.emis_reporter3)
     check_progress(self.smc_weekly_script)
     # self.assertEqual(2,Message.objects.filter(direction='O',connection=self.emis_reporter3.connection_set.all()[0]).count())
     self.assertEqual(
         1,
         Message.objects.filter(
             direction='O',
             connection=self.emis_reporter3.connection_set.all()
             [0]).count())  #paisong feedback
     expected = 'Thank you for your report. Please continue to visit your school and report on what is happening.'
     # self.assertTrue(expected in Message.objects.filter(direction='O',connection=self.emis_reporter3.connection_set.all()[0]).values_list('text',flat=True))
     self.assertFalse(expected in Message.objects.filter(
         direction='O',
         connection=self.emis_reporter3.connection_set.all()
         [0]).values_list('text', flat=True))  #pausing feedback
示例#52
0
 def test_should_resend_poll_question_on_invalid_responses(self):
     schedule_script_now(grp=self.head_teacher_group.name,
                         slug=self.teachers_weekly_script.slug)
     check_progress(self.teachers_weekly_script)
     fake_incoming("invalid response", self.emis_reporter1)
     check_progress(self.teachers_weekly_script)
     self.assertEqual(
         3,
         Message.objects.filter(
             direction='O',
             connection=self.emis_reporter1.connection_set.all()
             [0]).count())
     outgoing_messages = list(
         Message.objects.filter(
             direction='O',
             connection=self.emis_reporter1.connection_set.all()
             [0]).values_list('text', flat=True))
     self.assertEqual(
         2, outgoing_messages.count(self.p3_boys_absent_poll.question))
 def test_registration_process_for_gem(self):
     self.create_attribute()
     self.create_role_categories()
     Script.objects.filter(slug='edtrac_autoreg').update(enabled=True)
     self.fake_incoming('join')
     check_progress(self.auto_reg_script)
     self.assertEqual(self.role_poll.question,Message.objects.filter(direction='O').order_by('-date')[0].text)
     self.fake_incoming('4')
     #self.create_response_category('4',self.gem_category)
     check_progress(self.auto_reg_script)
     self.assertEqual(self.district_poll.question,Message.objects.filter(direction='O').order_by('-date')[0].text)
     self.fake_incoming('Kamapala')
     check_progress(self.auto_reg_script)
     self.assertEqual(self.subcounty_poll.question,Message.objects.filter(direction='O').order_by('-date')[0].text)
     self.fake_incoming('Kampala')
     check_progress(self.auto_reg_script)
     self.assertEqual(self.name_poll.question,Message.objects.filter(direction='O').order_by('-date')[0].text)
     self.fake_incoming('test mctester')
     check_progress(self.auto_reg_script)
     self.assertEqual(self.welcome_step.message,Message.objects.filter(direction='O').order_by('-date')[0].text)
 def test_should_return_4_given_reporter_responds_4_to_girls_enrollment_poll(
         self):
     self.head_teachers_termly_script.steps.all().delete()
     self.head_teachers_termly_script.steps.add(
         ScriptStep.objects.create(script=self.head_teachers_termly_script,
                                   poll=self.p6_girls_enroll_poll,
                                   order=0,
                                   rule=ScriptStep.WAIT_MOVEON,
                                   start_offset=0,
                                   giveup_offset=7200))
     schedule_script_now(grp=self.head_teacher_group.name,
                         slug=self.head_teachers_termly_script.slug)
     check_progress(self.head_teachers_termly_script)
     fake_incoming("4", self.emis_reporter1)
     check_progress(self.head_teachers_termly_script)
     enrolled_girls = get_enrolled_pupils(
         self.emis_reporter1.connection_set.all()[0],
         self.p6_girls_enroll_poll.name, settings.SCHOOL_TERM_START,
         settings.SCHOOL_TERM_END)
     self.assertEqual(4, enrolled_girls)