Beispiel #1
0
    def _save_user(self, data):
        user = User.objects.filter(openid=data['openid'])
        # 没有则存储用户数据,有返回用户数据的字典
        if 0 == user.count():
            user_data = {
                'nickname':
                data['nickname'].encode('iso8859-1').decode('utf-8'),
                'openid': data['openid'],
                'headimgurl': data['headimgurl'],
                'sex': data['sex'],
                'city': data['city'].encode('iso8859-1').decode('utf-8'),
                'country': data['country'].encode('iso8859-1').decode('utf-8')
            }

            if 'unionid' in data:
                user_data.update('unionid', data.unionid)

            try:
                new_user = User(**user_data)
                new_user.save()

                user_data.update({'id': new_user.id})
                return json.dumps(user_data)
                # return user_data
            except Exception as e:
                print(e)

            return None
        else:
            # print(len(user))
            return UserSerializer.toString(user[0])
Beispiel #2
0
class BulkMessageProcessor(object):
    def __init__(self):
        self.questionnaire = None
        
    def parse_and_create_user(self, message, connection):
        answers = []
        message_parts = message.split(" ")

        self.user = User(connection = connection, governorate = connection.governorate, district = connection.district, active = True)

        try:
            self.user.age = int(message_parts[1])
            self.user.gender = message_parts[2]
        except ValueError:
            return "bulk_response_error"

        answers.append(message_parts[3])
        answers.append(" ".join(message_parts[4:7]))
        answers.append(message_parts[7])
        
        return answers

    def save_user_and_responses(self, answers):
        self.user.save()
        self._set_default_questionnaire()

        questions = Question.objects.filter(questionnaire = self.questionnaire).order_by('id')

        matching_choices = []

        for (counter, question) in enumerate(questions):
            choices_for_one_question = question.matching_choices(answers[counter])

            matching_choices.append(choices_for_one_question)

            if len(choices_for_one_question) < 1:
                return "bulk_response_error"

        for (counter, question) in enumerate(questions):
            for choice in matching_choices[counter]:
                UserResponse(user = self.user, question = question, choice = choice).save()

        return "thanks"
    
    def _set_default_questionnaire(self):
        if not self.questionnaire:
            self.questionnaire = Questionnaire.objects.all().order_by('pk')[0]
Beispiel #3
0
 def parse(userStr):
     data = json.loads(userStr)
     user_data = {
         'nickname': data['nickname'],
         'openid': data['openid'],
         'headimgurl': data['headimgurl'],
         'sex': data['sex'],
         'city': data['city'],
         'country': data['country'],
         'id': data['id']
     }
     # if 'unionid' in data:
     #     user_data.update('unionid', data.unionid)
     user = User(**user_data)
     return user
Beispiel #4
0
    def parse_and_create_user(self, message, connection):
        answers = []
        message_parts = message.split(" ")

        self.user = User(connection = connection, governorate = connection.governorate, district = connection.district, active = True)

        try:
            self.user.age = int(message_parts[1])
            self.user.gender = message_parts[2]
        except ValueError:
            return "bulk_response_error"

        answers.append(message_parts[3])
        answers.append(" ".join(message_parts[4:7]))
        answers.append(message_parts[7])
        
        return answers
Beispiel #5
0
    def setUp(self):
        Question.objects.all().delete()
        self.backend = PersistantBackend(slug="MockBackend")
        self.backend.save()
        self.reporter = Reporter(alias="ReporterName")
        self.reporter.save()
        self.pconnection = PersistantConnection(backend=self.backend, reporter=self.reporter, identity="1000")
        self.pconnection.save()

        self.pconnection1 = PersistantConnection(backend=self.backend, reporter=self.reporter, identity="10001")
        self.pconnection1.save()

        self.reporter.connections.add(self.pconnection)

        self.question1 = Question(text="question1")
        self.question1.is_first = True
        self.question1.save()
        self.question2 = Question(text="question2")
        self.question2.save()
        self.question3 = Question(text="question3")
        self.question3.save()

        self.question1.next_question = self.question2
        self.question2.next_question = self.question3

        self.question1.save()
        self.question2.save()
        self.question3.save()

        self.setup_choices(self.question1)
        self.setup_choices(self.question2)
        self.setup_choices(self.question3)

        q = Questionnaire(trigger="trigger", max_retries=3)
        q.save()
        DemographicParser(questionnaire=q, name="age", regex="[0-9]+", order=1, type="i").save()
        DemographicParser(questionnaire=q, name="gender", regex="m|f|male|female", order=2, type="c").save()
        self.user = User(connection=self.pconnection)
        self.user.save()

        r = Registration(governorate=3, district=4, phone=self.pconnection)
        r.save()
Beispiel #6
0
class UserSessionTest(TestCase):
    apps = (poll_App,)

    def setUp(self):
        Question.objects.all().delete()
        self.backend = PersistantBackend(slug="MockBackend")
        self.backend.save()
        self.reporter = Reporter(alias="ReporterName")
        self.reporter.save()
        self.pconnection = PersistantConnection(backend=self.backend, reporter=self.reporter, identity="1000")
        self.pconnection.save()

        self.pconnection1 = PersistantConnection(backend=self.backend, reporter=self.reporter, identity="10001")
        self.pconnection1.save()

        self.reporter.connections.add(self.pconnection)

        self.question1 = Question(text="question1")
        self.question1.is_first = True
        self.question1.save()
        self.question2 = Question(text="question2")
        self.question2.save()
        self.question3 = Question(text="question3")
        self.question3.save()

        self.question1.next_question = self.question2
        self.question2.next_question = self.question3

        self.question1.save()
        self.question2.save()
        self.question3.save()

        self.setup_choices(self.question1)
        self.setup_choices(self.question2)
        self.setup_choices(self.question3)

        q = Questionnaire(trigger="trigger", max_retries=3)
        q.save()
        DemographicParser(questionnaire=q, name="age", regex="[0-9]+", order=1, type="i").save()
        DemographicParser(questionnaire=q, name="gender", regex="m|f|male|female", order=2, type="c").save()
        self.user = User(connection=self.pconnection)
        self.user.save()

        r = Registration(governorate=3, district=4, phone=self.pconnection)
        r.save()

    def setup_choices(self, question):
        choice1 = Choice(code="a", question=question, text="a")
        choice2 = Choice(code="b", question=question, text="a")
        choice3 = Choice(code="c", question=question, text="a")
        choice1.save()
        choice2.save()
        choice3.save()

    def test_open_new_session(self):
        session = UserSession.open(self.pconnection)
        self.assertEquals(session.question, None)

    def test_respond_with_first_question_on_new_session_for_any_message(self):
        session = UserSession.open(self.pconnection)
        self.assertEquals(session.respond("text"), str(self.question1))

    def test_correct_response_to_question_sends_next_question(self):
        session = UserSession.open(self.pconnection)
        self.assertEquals(session.question, None)
        response1 = session.respond("text")
        self.assertEquals(session.question, self.question1)
        response2 = session.respond("a")
        self.assertEquals(response2, str(self.question2))
        self.assertEquals(session.question, self.question2)

    def test_wrong_response_to_question_sends_error(self):
        session = UserSession.open(self.pconnection)
        self.assertEquals(session.question, None)
        response1 = session.respond("text")
        self.assertEquals(session.question, self.question1)
        response2 = session.respond("django")
        self.assertEquals(response2, "error_parsing_response")
        self.assertEquals(session.question, self.question1)

    def test_retrieve_ongoing_session_at_question2(self):
        session = UserSession.open(self.pconnection)
        session.user = self.user
        session.question = self.question2
        session.save()
        session = UserSession.open(self.pconnection)
        self.assertEquals(session.respond("b"), str(self.question3))
        self.assertEquals(session.question, self.question3)

    def test_close_ongoing_session_at_trigger(self):
        session = UserSession.open(self.pconnection)
        session.user = self.user
        session.question = self.question2
        session.save()
        session = UserSession.open(self.pconnection)
        self.assertEquals(session.respond("c"), str(self.question3))
        self.assertEquals(session.question, self.question3)

        self.assertEquals(session.respond("trigger 13 m"), str(self.question1))
        self.assertEquals(session.question, self.question1)

    def test_close_session_on_last_answer(self):
        session = UserSession.open(self.pconnection)
        session.question = self.question3
        session.user = self.user
        self.assertEquals(session.respond("c"), "thanks")
        self.assertEquals(session.question, None)

    def test_user_interaction_is_saved_when_successful(self):
        initial_number_of_responses = len(UserResponse.objects.all())
        initial_number_of_users = len(User.objects.all())

        session = UserSession.open(self.pconnection1)
        session.respond("trigger 14 f")
        self.assertEquals(len(User.objects.all()), initial_number_of_users + 1)
        session.respond("a")
        self.assertEquals(len(UserResponse.objects.all()), initial_number_of_responses + 1)

    def test_end_session_on_reaching_max_num_allowed_retries(self):
        session = UserSession.open(self.pconnection1)
        session.question = self.question1
        session.user = self.user
        session.respond("t")
        session.respond("t")
        session.respond("t")
        self.assertEquals(session.question, None)

    def test_user_demographics_saved_when_present(self):
        session = UserSession.open(self.pconnection1)
        session.respond("trigger 13 f")
        latest_user = User.objects.all().order_by("-id")[0]
        self.assertEquals(latest_user.age, 13)
        self.assertEquals(latest_user.gender, "f")

    def test_user_location_from_registration(self):
        session = UserSession.open(self.pconnection)
        session.respond("trigger 14 f")
        latest_user = User.objects.all().order_by("-id")[0]
        self.assertEquals(latest_user.governorate, 3)
        self.assertEquals(latest_user.district, 4)

    def test_junk_trigger_message(self):
        backend = PersistantBackend(slug="MockBackend1")
        backend.save()
        reporter = Reporter(alias="ReporterName1")
        reporter.save()
        pconnection = PersistantConnection(backend=backend, reporter=reporter, identity="1001")
        pconnection.save()
        session = UserSession.open(pconnection)

        self.assertEquals(session.respond("trigger junk"), TRIGGER_INCORRECT_MESSAGE)

    def test_junk_message(self):
        backend = PersistantBackend(slug="MockBackend1")
        backend.save()
        reporter = Reporter(alias="ReporterName1")
        reporter.save()
        pconnection = PersistantConnection(backend=backend, reporter=reporter, identity="1001")
        pconnection.save()
        session = UserSession.open(pconnection)

        self.assertEquals(session.respond("junk"), TRIGGER_INCORRECT_MESSAGE)