Пример #1
0
 def test_should_raise_exception_if_form_code_already_exists_on_creation(self):
     question1 = TextField(name="entity_question", code="ID", label="What is associated entity",
                           language="eng", entity_question_flag=True, ddtype=self.default_ddtype)
     form_model = FormModel(self.dbm, entity_type=self.entity_type, name="aids", label="Aids form_model",
                            form_code="1", type='survey', fields=[question1])
     with self.assertRaises(DataObjectAlreadyExists):
         form_model.save()
Пример #2
0
    def test_subject_index_dict(self):
        dbm = Mock(spec=DatabaseManager)
        entity_type = ['entity_type']

        with patch('datawinners.search.index_utils.get_entity_type_fields'
                   ) as get_entity_type:
            with patch('datawinners.search.index_utils.tabulate_data'
                       ) as tabulate_data:
                get_entity_type.return_value = ['name1', 'name2'
                                                ], ['label1', 'label2'
                                                    ], ['code1', 'code2']
                mock_entity = Mock(spec=Entity)
                mock_entity.is_void.return_value = False
                tabulate_data.return_value = {'cols': ['ans1', 'ans2']}
                with patch.object(Entity, 'get') as get:
                    get.return_value = mock_entity
                    form_model = FormModel(dbm=dbm,
                                           entity_type=entity_type,
                                           is_registration_model=True)
                    form_model._doc = Mock(form_code="abc", id='form_id')
                    entity_doc = Mock()

                    result = subject_dict(entity_type, entity_doc, dbm,
                                          form_model)

                    expected = {
                        'form_id_code1': 'ans1',
                        'form_id_code2': 'ans2',
                        'entity_type': ['entity_type'],
                        'void': False
                    }
                    self.assertEquals(result, expected)
Пример #3
0
def form_model_change_handler(form_model_doc, dbm, old_form_model_doc=None):
    form_model = FormModel.new_from_doc(dbm, form_model_doc)
    old_form_model = None
    if old_form_model_doc:
        old_form_model = FormModel.new_from_doc(dbm, old_form_model_doc)
    if form_model.form_code != 'delete':
        create_submission_mapping(dbm, form_model, old_form_model)
Пример #4
0
 def __init__(self,
              dbm,
              form_code=None,
              name=None,
              goals="",
              devices=None,
              sender_group=None,
              language='en',
              fields=[]):
     FormModel.__init__(self,
                        dbm=dbm,
                        form_code=form_code,
                        is_registration_model=False,
                        label="",
                        language=language,
                        name=name,
                        fields=fields)
     if self._doc:
         self._doc.goals = goals
         self._doc.devices = devices
         self._doc.sender_group = sender_group
         self._doc.reminder_and_deadline = {
             "deadline_type": "Following",
             "should_send_reminder_to_all_ds": False,
             "has_deadline": True,
             "deadline_month": "5",
             "frequency_period": "month"
         }
Пример #5
0
 def __init__(self,
              dbm,
              form_code=None,
              name=None,
              goals="",
              devices=None,
              sender_group=None,
              is_poll=False,
              end_date=None,
              active=None,
              language='en',
              fields=[]):
     FormModel.__init__(self,
                        dbm=dbm,
                        form_code=form_code,
                        is_registration_model=False,
                        label="",
                        language=language,
                        name=name,
                        fields=fields)
     if self._doc:
         self._doc.goals = goals
         self._doc.devices = devices
         self._doc.sender_group = sender_group
         self._doc.reminder_and_deadline = default_reminder_and_deadline
         self._doc.is_poll = is_poll
         self._doc.end_date = end_date
         self._doc.active = active
Пример #6
0
def SaveQuestionnaire(dbm):
    entity_type = ['school']
    if not entity_type_already_defined(dbm, entity_type):
        define_type(dbm, entity_type)

    #default_ddtype
    default_ddtype = DataDictType(dbm, name='Default String Datadict Type', slug='string_default',
        primitive_type='string')
    #questions
    question0 = TextField(name="Q0", code="ID", label="What is your id?", entity_question_flag=True,
        ddtype=default_ddtype)
    question1 = TextField(name="Q1", code="FIRSTNAME", label="What is your first name?", entity_question_flag=False,
        ddtype=default_ddtype)
    question2 = TextField(name="Q2", code="LASTNAME", label="What is your last name?", entity_question_flag=False,
        ddtype=default_ddtype)
    question3 = DateField(name="Q3", code="BIRTHDATE", date_format='mm.yyyy', label="What is your birth date?",
        ddtype=default_ddtype)
    question4 = TextField(name="Q4", code="COMMENT", label="What do you want to add?", entity_question_flag=False,
        ddtype=default_ddtype)
    #form_model
    form_model = FormModel(dbm, entity_type=entity_type, name="Personal information Survey", label="Basic Info Survey",
        form_code="PISurvey", type='survey', fields=[question0, question1, question2, question3, question4])
    try:
        qid = form_model.save()
    except DataObjectAlreadyExists as e:
        get_form_model_by_code(dbm, "PISurvey").delete()
        qid = form_model.save()
    return form_model
Пример #7
0
 def _create_form_model_for_project(self, project):
     ddtype = DataDictType(self.dbm,
                           name='Default String Datadict Type',
                           slug='string_default',
                           primitive_type='string')
     question1 = TextField(name="entity_question",
                           code="ID",
                           label="What is associated entity",
                           language="eng",
                           entity_question_flag=True,
                           ddtype=ddtype)
     question2 = TextField(name="question1_Name",
                           code="Q1",
                           label="What is your name",
                           defaultValue="some default value",
                           language="eng",
                           length=TextConstraint(5, 10),
                           ddtype=ddtype)
     self.form_model = FormModel(self.dbm,
                                 name=self.project1.name,
                                 form_code="abc",
                                 fields=[question1, question2],
                                 entity_type=["Clinic"],
                                 state=attributes.INACTIVE_STATE)
     qid = self.form_model.save()
     project.qid = qid
     project.save(self.dbm)
Пример #8
0
    def test_should_save_submitted_sms_for_activity_report(self):
        question1 = TextField(name="entity_question", code="EID", label="What is associated entity",
                              language="eng", entity_question_flag=True, ddtype=self.entity_id_type)
        question2 = TextField(name="Name", code="NAME", label="Clinic Name",
                              defaultValue="some default value", language="eng", length=TextConstraint(4, 15),
                              ddtype=self.name_type)
        question3 = IntegerField(name="Arv stock", code="ARV", label="ARV Stock",
                                 range=NumericConstraint(min=15, max=120), ddtype=self.stock_type)
        activity_report = FormModel(self.dbm, entity_type=["reporter"], name="report", label="reporting form_model",
                                    form_code="acp", type='survey', fields=[question1, question2, question3])
        activity_report.save()

        text = "acp +name tester +ARV 50 "

        response = self.send_sms(text)

        self.assertTrue(response.success)
        self.assertEqual(u"Test_reporter",response.reporters[0].get(NAME_FIELD))

        data_record_id = response.datarecord_id
        data_record = self.dbm._load_document(id=data_record_id, document_class=DataRecordDocument)
        self.assertEqual(self.name_type.slug, data_record.data["Name"]["type"]["slug"])
        self.assertEqual(self.stock_type.slug, data_record.data["Arv stock"]["type"]["slug"])
        self.assertEqual("acp", data_record.submission['form_code'])
        data = self.reporter.values({"Name": "latest", "Arv stock": "latest"})
        self.assertEquals(data["Arv stock"], 50)
        self.assertEquals(data["Name"], "tester")
        submission_log = self.dbm._load_document(response.submission_id, SubmissionLogDocument)
        self.assertEquals(data_record_id, submission_log.data_record_id)
Пример #9
0
 def setUp(self):
     self.data = [
         [
             "What is the reporting period for the activity?\n\n Answer must be a date in the following format: day.month.year\n\n Example: 25.12.2011"
         ],
         ["12.12.2012"],
         ["11.11.2012"],
         ["12.10.2012"],
     ]
     self.user = Mock(User)
     self.dbm = Mock(spec=DatabaseManager)
     self.default_ddtype = DataDictType(self.dbm,
                                        name='Default String Datadict Type',
                                        slug='string_default',
                                        primitive_type='string')
     fields = \
         [TextField(name="Q1", code="EID", label="What is the reporter ID?", entity_question_flag=True,
                    ddtype=self.default_ddtype),
          TextField(name="Q2", code="DATE", label="What is the reporting period for the activity?",
                    entity_question_flag=False, ddtype=self.default_ddtype)]
     self.form_model = FormModel(self.dbm,
                                 "abc",
                                 "abc",
                                 entity_type=["clinic"],
                                 form_code="cli001",
                                 fields=fields,
                                 type="survey")
     self.project = Mock(Project)
 def test_should_update_submission_index_date_field_with_current_format(
         self):
     dd_type = Mock(spec=DataDictType)
     fields = [
         TextField(name="entity_question",
                   code="EID",
                   label="What is associated entity",
                   entity_question_flag=True,
                   ddtype=dd_type),
         DateField("date", "date", "Date", "dd.mm.yyyy", dd_type)
     ]
     form_model = FormModel(dbm=Mock(spec=DatabaseManager),
                            form_code="001",
                            type="survey",
                            name="form",
                            entity_type=["clinic"],
                            fields=fields)
     form_model._doc.entity_type = ["clinic"]
     values = {'eid': 'cid005', 'date': '12.21.2012'}
     submission_doc = SurveyResponseDocument(values=values,
                                             status="success",
                                             form_model_revision="rev1")
     search_dict = {}
     form_model._doc = Mock(spec=FormModelDocument)
     form_model._doc.rev = "rev2"
     form_model._snapshots = {
         "rev1": [DateField("date", "date", "Date", "mm.dd.yyyy", dd_type)]
     }
     with patch('datawinners.search.submission_index.lookup_entity_name'
                ) as lookup_entity_name:
         lookup_entity_name.return_value = 'Test'
         search_dict = _update_with_form_model_fields(
             Mock(spec=DatabaseManager), submission_doc, search_dict,
             form_model)
         self.assertEquals("21.12.2012", search_dict.get("date"))
Пример #11
0
 def _create_summary_form_model(self):
     question1 = TextField(
         name="question1_Name",
         code="Q1",
         label="What is your name",
         defaultValue="some default value",
         constraints=[TextLengthConstraint(5, 10),
                      RegexConstraint("\w+")],
         ddtype=self.default_ddtype)
     question2 = IntegerField(
         name="Father's age",
         code="Q2",
         label="What is your Father's Age",
         constraints=[NumericRangeConstraint(min=15, max=120)],
         ddtype=self.default_ddtype)
     question3 = SelectField(name="Color",
                             code="Q3",
                             label="What is your favourite color",
                             options=[("RED", 1), ("YELLOW", 2)],
                             ddtype=self.default_ddtype)
     self.summary_form_model = FormModel(
         self.manager,
         entity_type=["reporter"],
         name="aids",
         label="Aids form_model",
         form_code=FORM_CODE_2,
         type="survey",
         fields=[question1, question2, question3])
     self.summary_form_model__id = self.summary_form_model.save()
Пример #12
0
 def create_form_for_entity_type(self):
     string_data_type = get_or_create_data_dict(self.manager,
                                                name='Name',
                                                slug='name',
                                                primitive_type='string')
     school_name_field = TextField(name="name",
                                   code="q1",
                                   label="What's the name?",
                                   ddtype=string_data_type)
     address_field = TextField(name="address",
                               code="q2",
                               label="Where is the clinic?",
                               ddtype=string_data_type)
     unique_id_field = TextField(
         name="unique_id",
         code="q3",
         label="What is the clinic's Unique ID Number?",
         ddtype=string_data_type,
         entity_question_flag=True)
     form_model = FormModel(
         self.manager,
         "clinic",
         form_code=FORM_CODE,
         entity_type=["clinic"],
         is_registration_model=True,
         fields=[school_name_field, address_field, unique_id_field])
     form_model.save()
    def test_should_assert_activity_report(self):

        question1 = TextField(name="question1_Name", code="Q1", label="What is your name",
                              defaultValue="some default value", language="eng", length=TextConstraint(5, 10),
                              ddtype=self.ddtype_mock)
        activity_report = FormModel(self.dbm, entity_type=["reporter"], name="aids", label="Aids form_model",
                                        form_code="1", type='survey', fields=[question1])
        self.assertTrue(activity_report.entity_defaults_to_reporter())
Пример #14
0
    def build(self):
        if not entity_type_already_defined(self._manager, self._entity_type):
            define_type(self._manager, self._entity_type)

        self.form_model = FormModel(self._manager, name=self._name, label=self._label,
            form_code=self._form_code, fields=self._fields, is_registration_model=self._is_reg)
        form_model_id = self.form_model.save()
        return FormModel.get(self._manager, form_model_id)
Пример #15
0
 def create_form_for_entity_type(self):
     school_name_field = TextField(name="name", code="q1", label="What's the name?")
     address_field = TextField(name="address", code="q2", label="Where is the clinic?")
     unique_id_field = UniqueIdField('clinic',name="unique_id", code="q3", label="What is the clinic's Unique ID Number?")
     form_model = FormModel(self.manager, "clinic", form_code=FORM_CODE, entity_type=["clinic"],
                            is_registration_model=True,
                            fields=[school_name_field, address_field, unique_id_field])
     form_model.save()
    def setUp(self):
        self.dbm = Mock(spec=DatabaseManager)
        self.datadict_patcher = patch(
            "mangrove.form_model.form_model.get_or_create_data_dict")
        self.datadict_mock = self.datadict_patcher.start()
        self.ddtype_mock = Mock(spec=DataDictType)
        self.datadict_mock.return_value = self.ddtype_mock

        q1 = TextField(name="entity_question",
                       code="ID",
                       label="What is associated entity",
                       language="eng",
                       entity_question_flag=True,
                       ddtype=self.ddtype_mock)
        q2 = TextField(name="question1_Name",
                       code="Q1",
                       label="What is your name",
                       defaultValue="some default value",
                       language="eng",
                       length=TextConstraint(5, 10),
                       ddtype=self.ddtype_mock)
        q3 = IntegerField(name="Father's age",
                          code="Q2",
                          label="What is your Father's Age",
                          range=NumericConstraint(min=15, max=120),
                          ddtype=self.ddtype_mock)
        q4 = SelectField(name="Color",
                         code="Q3",
                         label="What is your favourite color",
                         options=[("RED", 1), ("YELLOW", 2)],
                         ddtype=self.ddtype_mock)
        q5 = TextField(name="Desc",
                       code="Q4",
                       label="Description",
                       ddtype=self.ddtype_mock)

        self.form_model = FormModel(
            self.dbm,
            entity_type=["XYZ"],
            name="aids",
            label="Aids form_model",
            form_code="1",
            type='survey',
            fields=[  #        expected_short_code = "dog3"
                #        self.assertEqual(response.short_code, expected_short_code)
                #        b = get_by_short_code(self.dbm, expected_short_code, ["dog"])
                #        self.assertEqual(b.short_code, expected_short_code)
                q1,
                q2,
                q3,
                q4,
                q5
            ])
    def CreateSchoolByFormModel(self):
        field1 = TextField(name="entity_question", code="i", label="What is scholl entity",language="en", entity_question_flag=True, ddtype=self.default_ddtype)
        field2 = TextField(name="School_name", code="n", label="What is scholl name",language="en", ddtype=self.default_ddtype)
        field3 = TextField(name="school_location", code="g", label="What is scholl location",language="en", ddtype=self.default_ddtype)
        field4 = TextField(name="school_type", code="t", label="What is scholl type",language="en", ddtype=self.default_ddtype)

        model = FormModel(self.manager, name="school", label="fds", form_code="School", entity_type=self.entity_type, is_registration_model=True, fields=[field1, field2, field3, field4])
        model.save()

        FormSubmission(model, OrderedDict({"i": "bh1", "n": "beihang", "g": ["beijing"], "t": "university"})).save(self.manager)
        FormSubmission(model, OrderedDict({"i": "qh1", "n": "qinghua", "g": ["beijing"], "t": "university"})).save(self.manager)
        FormSubmission(model, OrderedDict({"i": "bd1", "n": "beida", "g": ["beijing"], "t": "university"})).save(self.manager)
Пример #18
0
 def test_should_call_submission_mapping_if_not_registration_form_model(
         self):
     dbm = Mock(spec=DatabaseManager)
     form_model_document = Mock(spec=FormModelDocument)
     with patch("mangrove.form_model.form_model.FormModel.new_from_doc"
                ) as new_from_doc:
         with patch("datawinners.search.mapping.create_submission_mapping"
                    ) as create_submission_mapping:
             form_model = FormModel(dbm, form_code='clinic')
             form_model._doc = form_model_document
             new_from_doc.return_value = form_model
             form_model_change_handler(form_model_document, dbm)
             assert create_submission_mapping.called
Пример #19
0
 def test_should_raise_exception_if_form_code_already_exists_on_creation(
         self):
     question1 = UniqueIdField('clinic',
                               name="entity_question",
                               code="ID",
                               label="What is associated entity")
     form_model = FormModel(self.manager,
                            name="aids",
                            label="Aids form_model",
                            form_code="1",
                            fields=[question1])
     with self.assertRaises(DataObjectAlreadyExists):
         form_model.save()
Пример #20
0
    def test_should_save_submitted_sms_for_activity_report(self):
        question1 = TextField(name="entity_question",
                              code="EID",
                              label="What is associated entity",
                              language="eng",
                              entity_question_flag=True,
                              ddtype=self.entity_id_type)
        question2 = TextField(name="Name",
                              code="NAME",
                              label="Clinic Name",
                              defaultValue="some default value",
                              language="eng",
                              length=TextConstraint(4, 15),
                              ddtype=self.name_type)
        question3 = IntegerField(name="Arv stock",
                                 code="ARV",
                                 label="ARV Stock",
                                 range=NumericConstraint(min=15, max=120),
                                 ddtype=self.stock_type)
        activity_report = FormModel(self.dbm,
                                    entity_type=["reporter"],
                                    name="report",
                                    label="reporting form_model",
                                    form_code="acp",
                                    type='survey',
                                    fields=[question1, question2, question3])
        activity_report.save()

        text = "acp +name tester +ARV 50 "

        response = self.send_sms(text)

        self.assertTrue(response.success)
        self.assertEqual(u"Test_reporter",
                         response.reporters[0].get(NAME_FIELD))

        data_record_id = response.datarecord_id
        data_record = self.dbm._load_document(
            id=data_record_id, document_class=DataRecordDocument)
        self.assertEqual(self.name_type.slug,
                         data_record.data["Name"]["type"]["slug"])
        self.assertEqual(self.stock_type.slug,
                         data_record.data["Arv stock"]["type"]["slug"])
        self.assertEqual("acp", data_record.submission['form_code'])
        data = self.reporter.values({"Name": "latest", "Arv stock": "latest"})
        self.assertEquals(data["Arv stock"], 50)
        self.assertEquals(data["Name"], "tester")
        submission_log = self.dbm._load_document(response.submission_id,
                                                 SubmissionLogDocument)
        self.assertEquals(data_record_id, submission_log.data_record_id)
 def test_should_create_media_detail_document(self):
     form_model = FormModel(self.manager,
                            "name",
                            form_code="code",
                            fields=[])
     form_model.save()
     media_submission_service = MediaSubmissionService(
         self.manager, {}, "code")
     count = next(media_submission_service._get_count())
     self.assertEquals(1, count)
     media_submission_service.create_media_details_document(
         1000000, "new_image")
     count = next(media_submission_service._get_count())
     self.assertEquals(2, count)
Пример #22
0
    def test_should_set_field_initial_value_as_none_if_not_populated(self):
        empty_field = TextField(name="text",
                                code="code",
                                label="what is ur name")
        empty_field.value = None
        form_model = FormModel(Mock(spec=DatabaseManager))
        form_model.add_field(empty_field)

        mock_subject = Mock(spec=Entity)
        type(mock_subject).data = PropertyMock(return_value={})

        initialize_values(form_model, mock_subject)

        self.assertEquals(None, empty_field.value)
Пример #23
0
 def _create_sample_questionnaire(self):
     entity_type = []
     question3 = IntegerField(
         name="Father's age",
         code="Q2",
         label="What is your Father's Age",
         constraints=[NumericRangeConstraint(min=15, max=120)])
     form_model = FormModel(self.manager,
                            name='New survey',
                            label='Survey122',
                            form_code='S122',
                            fields=[question3],
                            is_registration_model=False)
     form_model_id = form_model.save()
     return form_model_id
Пример #24
0
    def setUp(self):
        self.dbm = Mock(spec=DatabaseManager)

        q1 = UniqueIdField('clinic',
                           name="entity_question",
                           code="ID",
                           label="What is associated entity")
        q2 = TextField(name="question1_Name",
                       code="Q1",
                       label="What is your name",
                       defaultValue="some default value",
                       constraints=[TextLengthConstraint(5, 10)],
                       required=False)
        q3 = IntegerField(
            name="Father's age",
            code="Q2",
            label="What is your Father's Age",
            constraints=[NumericRangeConstraint(min=15, max=120)],
            required=False)
        q4 = SelectField(name="Color",
                         code="Q3",
                         label="What is your favourite color",
                         options=[("RED", 'a'), ("YELLOW", 'b')],
                         required=False)
        q5 = TextField(name="Desc",
                       code="Q4",
                       label="Description",
                       required=False)
        self.event_time_field_code = "Q6"
        q6 = DateField(name="Event time",
                       code=self.event_time_field_code,
                       label="Event time field",
                       date_format="%m.%d.%Y",
                       required=False)
        q7 = GeoCodeField(name="My Location",
                          code="loc",
                          label="Geo Location Field",
                          required=False)
        self.form_model = FormModel(self.dbm,
                                    name="aids",
                                    label="Aids form_model",
                                    form_code="1",
                                    fields=[q1, q2, q3, q4, q5, q6, q7])

        self.form_model_patch = patch(
            'mangrove.form_model.form_model.FormModel')
        self.form_model_document_patch = patch(
            'mangrove.form_model.form_model.FormModelDocument')
Пример #25
0
def get_questions_paginated_or_by_ids(request):
    manager = get_database_manager(request.user)
    start = int(request.GET.get('start', '0'))
    length = int(request.GET.get('length', '10'))
    ids = request.GET.getlist('ids')

    if ids:
        projects = [
            _project_details(manager, project_id) for project_id in ids
        ]
        projects = list(filter(lambda x: x != None, projects))
        return response_json_cors(projects)

    project_list = []
    rows = manager.load_all_rows_in_view('all_projects', descending=True)
    for row in rows:
        questionnaire = FormModel.get(manager, row['id'])
        if questionnaire.xform:
            project_temp = dict(name=questionnaire.name,
                                project_uuid=questionnaire.id,
                                version=questionnaire._doc.rev)
            project_list.append(project_temp)

    return response_json_cors({
        "projects": project_list[start:start + length],
        "total": len(project_list),
        "start": start,
        "length": length
    })
Пример #26
0
def get_projects_status(request):
    response_projects = []
    manager = get_database_manager(request.user)
    client_projects = json.loads(request.POST['projects'])

    for client_project in client_projects:
        try:
            server_project = FormModel.get(manager, client_project['id'])
            if (server_project._doc.void):
                response_projects.appened({
                    'id': client_project['id'],
                    'status': 'server-deleted'
                })
            elif server_project.revision != client_project['rev']:
                response_projects.append({
                    'id': server_project.id,
                    'status': 'outdated'
                })
        except Exception:
            response_projects.append({
                'id': client_project['id'],
                'status': 'server-deleted'
            })

    return response_json_cors(response_projects)
Пример #27
0
def convert_field_code_to_lower_case(db_name):
    logger = logging.getLogger(db_name)
    try:
        dbm = get_db_manager(db_name)
        rows = dbm.load_all_rows_in_view('questionnaire', reduce=False)
        for row in rows:
            form_model = FormModel.new_from_doc(
                dbm, FormModelDocument.wrap(row['value']))
            is_upper = False
            for field in form_model.fields:
                if re.match(r".*[A-Z]+.*", field.code):
                    logger.info("doc id: %s, field code: %s", form_model.id,
                                field.code)
                    is_upper = True
                    field._dict['code'] = field.code.lower()
            if is_upper:
                form_model.save()
                survey_responses = survey_responses_by_form_code(
                    dbm, form_model.form_code)
                for survey_response in survey_responses:
                    convert_dict_keys_to_lowercase(survey_response.values)
                    survey_response.save()
                    logger.info("Modified survey response id: %s" %
                                survey_response.uuid)
    except Exception as e:
        logger.exception(e.message)
    mark_as_completed(db_name)
Пример #28
0
    def _build_fixtures(self):
        entity_type = ["clinic"]
        fields = []
        fields.append(IntegerField('beds', 'BEDS', 'beds label'))
        fields.append(IntegerField('meds', 'MEDS', 'meds label'))
        fields.append(TextField('doctor', 'DOCTOR', 'doctor label'))
        fields.append(ShortCodeField('clinic', 'ID', 'clinic label'))

        try:
            self.form_model = EntityFormModel(self.manager,
                                              entity_type=entity_type,
                                              name='form_model_name',
                                              label='form_model_label',
                                              form_code='clf12',
                                              type='form_model_type',
                                              fields=fields,
                                              is_registration_model=True)
            form_model_id = self.form_model.save()
            self.form_model = FormModel.get(self.manager, form_model_id)
        except DataObjectAlreadyExists:
            pass

        [
            EntityBuilder(self.manager, entity_type,
                          'cl00%d' % i).build().save() for i in range(1, 6)
        ]
    def setUp(self):
        self.dbm = Mock(spec=DatabaseManager)
        self.datadict_patcher = patch("mangrove.form_model.form_model.get_or_create_data_dict")
        self.datadict_mock = self.datadict_patcher.start()
        self.ddtype_mock = Mock(spec=DataDictType)
        self.datadict_mock.return_value = self.ddtype_mock

        q1 = TextField(name="entity_question", code="ID", label="What is associated entity",
                              language="eng", entity_question_flag=True, ddtype=self.ddtype_mock)
        q2 = TextField(name="question1_Name", code="Q1", label="What is your name",
                              defaultValue="some default value", language="eng", length=TextConstraint(5, 10),
                              ddtype=self.ddtype_mock)
        q3 = IntegerField(name="Father's age", code="Q2", label="What is your Father's Age",
                                 range=NumericConstraint(min=15, max=120), ddtype=self.ddtype_mock)
        q4 = SelectField(name="Color", code="Q3", label="What is your favourite color",
                                options=[("RED", 1), ("YELLOW", 2)], ddtype=self.ddtype_mock)
        q5 = TextField(name="Desc", code="Q4", label="Description", ddtype=self.ddtype_mock)

        self.form_model = FormModel(self.dbm, entity_type=["XYZ"], name="aids", label="Aids form_model",
                                    form_code="1", type='survey', fields=[#        expected_short_code = "dog3"
#        self.assertEqual(response.short_code, expected_short_code)
#        b = get_by_short_code(self.dbm, expected_short_code, ["dog"])
#        self.assertEqual(b.short_code, expected_short_code)

                    q1, q2, q3, q4, q5])
def merge_project_and_form_model_for(dbm, logger):
    for row in dbm.database.query(list_all_projects, include_docs=True):
        try:
            project_data = row.doc
            form_model = FormModel.get(dbm, project_data.get("qid"))
            form_model_doc = form_model._doc

            form_model_doc['goals'] = project_data['goals']
            form_model_doc['name'] = project_data['name']
            form_model_doc['devices'] = project_data['devices']
            form_model_doc['data_senders'] = project_data['data_senders']
            form_model_doc['reminder_and_deadline'] = project_data[
                'reminder_and_deadline']
            form_model_doc['sender_group'] = project_data['sender_group']
            try:
                del form_model_doc['state']
            except KeyError as e:
                logger.warn(e)
            dbm._save_document(form_model_doc)

            update_reminders(dbm, project_data, logger)
            logger.info("Deleting project with id: %s", row.id)
            dbm.database.delete(row.doc)
        except Exception as e:
            logger.error(
                'Merging project and form_model failed for database : %s, project_doc with id: %s',
                dbm.database_name, row.id)
            logger.error(e)
Пример #31
0
 def test_get_form_model(self):
     form = FormModel.get(self.manager, self.form_model_id)
     self.assertIsNotNone(form.id)
     constraints = form.fields[1].constraints
     self.assertEqual(10, constraints[0].max)
     self.assertEqual(5, constraints[0].min)
     self.assertEqual("\w+", constraints[1].pattern)
Пример #32
0
def delete_project(manager, project, void=True):
    project_id, qid = project.id, project.qid
    [reminder.void(void) for reminder in (Reminder.objects.filter(project_id=project_id))]
    questionnaire = FormModel.get(manager, qid)
    [submission.void(void) for submission in get_submissions(manager, questionnaire.form_code, None, None)]
    questionnaire.void(void)
    project.set_void(manager, void)
Пример #33
0
def xform_for(dbm, form_id, reporter_id):
    questionnaire = FormModel.get(dbm, form_id)

    xform = questionnaire.xform
    if xform:
        xform_cleaned = re.sub(
            r"\s+", " ",
            re.sub(r"\n", "",
                   questionnaire.xform_with_unique_ids_substituted()))
        questionnaire.name = escape(questionnaire.name)
        #so that in the smartphone repeat questions have atleast one group pre added
        xform_cleaned = re.sub(
            r"<html:title>.*</html:title>",
            r"<html:title>" + questionnaire.name + "</html:title>",
            xform_cleaned)
        xform_cleaned = re.sub(
            r"<html:title />",
            r"<html:title>" + questionnaire.name + "</html:title>",
            xform_cleaned)
        return re.sub('ns2:template=""', "", xform_cleaned)

    _escape_special_characters(questionnaire)
    ui_fields = []
    for field in questionnaire.fields:
        if isinstance(field, UniqueIdField):
            ui_fields.append(UniqueIdUIField(field, dbm))
        else:
            ui_fields.append(field)
    template = env.get_template('reporter_entity_form.xml')
    return template.render(questionnaire=questionnaire,
                           fields=ui_fields,
                           field_xmls=field_xmls,
                           reporter_id=reporter_id,
                           field_types=field_types,
                           default_template=env.get_template('text_field.xml'))
Пример #34
0
    def test_should_add_snapshot_when_modifying(self):
        original_form = self.form_model

        original_form.create_snapshot()
        original_form.save()
        updated_form = FormModel.get(self.manager, self.form_model_id)
        self.assertTrue(len(updated_form.snapshots) == 1)
Пример #35
0
 def _create_data_submission_form(self):
     question1 = UniqueIdField('clinic',name="entity_question", code="ID", label="What is associated entity")
     question2 = TextField(name="Name", code="Q1", label="What is your name",
                           defaultValue="some default value")
     return FormModel(self.dbm, name="aids", label="Aids form_model",
                      form_code="AIDS",
                      fields=[question1, question2])
Пример #36
0
 def test_should_create_a_questionnaire_from_dictionary(self):
     #entityQ = UniqueIdField('reporter', name="What are you reporting on?", code="eid",
     #                        label="Entity being reported on", )
     ageQ = IntegerField(
         name="What is your age?",
         code="AGE",
         label="",
         constraints=[NumericRangeConstraint(min=0, max=10)],
         required=False)
     placeQ = SelectField(name="Where do you live?",
                          code="PLC",
                          label="",
                          options=[{
                              "text": "Pune"
                          }, {
                              "text": "Bangalore"
                          }],
                          single_select_flag=False,
                          required=False)
     questions = [ageQ, placeQ]
     document = self.get_form_model_doc()
     questionnaire = FormModel.new_from_doc(self.manager, document)
     self.maxDiff = None
     self.assertListEqual(questionnaire.entity_type, [])
     self.assertEqual(questionnaire.name, "New Project")
     for i in range(len(questions)):
         self.assertEqual(questionnaire.fields[i]._to_json(),
                          questions[i]._to_json())
Пример #37
0
 def _create_form_model_for_project(self,project):
     ddtype = DataDictType(self.dbm, name='Default String Datadict Type', slug='string_default',
                           primitive_type='string')
     question1 = TextField(name="entity_question", code="ID", label="What is associated entity",
                           language="eng", entity_question_flag=True, ddtype=ddtype)
     question2 = TextField(name="question1_Name", code="Q1", label="What is your name",
                           defaultValue="some default value", language="eng", length=TextConstraint(5, 10),
                           ddtype=ddtype)
     self.form_model = FormModel(self.dbm, name=self.project1.name, form_code="abc", fields=[question1, question2],
                            entity_type=["Clinic"], state=attributes.INACTIVE_STATE)
     qid = self.form_model.save()
     project.qid = qid
     project.save(self.dbm)
Пример #38
0
 def test_should_not_raise_exception_if_form_code_is_updated(self):
     question1 = TextField(name="entity_question", code="ID", label="What is associated entity",
                           language="eng", entity_question_flag=True, ddtype=self.default_ddtype)
     form_model2 = FormModel(self.dbm, entity_type=self.entity_type, name="aids", label="Aids form_model",
                             form_code="2", type='survey', fields=[question1])
     form_model2.save()
     form_model2.form_code = "2"
     form_model2.save()
Пример #39
0
    def setUp(self):
        self.dbm = get_db_manager(database='mangrove-test')
        initializer.run(self.dbm)
        define_type(self.dbm, ["dog"])
        self.entity_type = ["healthfacility", "clinic"]
        define_type(self.dbm, self.entity_type)
        self.name_type = DataDictType(self.dbm, name='Name', slug='name', primitive_type='string')
        self.telephone_number_type = DataDictType(self.dbm, name='telephone_number', slug='telephone_number',
                                                  primitive_type='string')
        self.entity_id_type = DataDictType(self.dbm, name='Entity Id Type', slug='entity_id', primitive_type='string')
        self.stock_type = DataDictType(self.dbm, name='Stock Type', slug='stock', primitive_type='integer')
        self.color_type = DataDictType(self.dbm, name='Color Type', slug='color', primitive_type='string')

        self.name_type.save()
        self.telephone_number_type.save()
        self.stock_type.save()
        self.color_type.save()

        self.entity = create_entity(self.dbm, entity_type=self.entity_type,
                                    location=["India", "Pune"], aggregation_paths=None, short_code="cli1",
                                    )

        self.data_record_id = self.entity.add_data(data=[("Name", "Ruby", self.name_type)],
                                                   submission=dict(submission_id="1"))

        self.reporter = create_entity(self.dbm, entity_type=["reporter"],
                                      location=["India", "Pune"], aggregation_paths=None, short_code="rep1",
                                      )

        self.reporter.add_data(data=[(MOBILE_NUMBER_FIELD, '1234', self.telephone_number_type),
                (NAME_FIELD, "Test_reporter", self.name_type)], submission=dict(submission_id="2"))

        question1 = TextField(name="entity_question", code="EID", label="What is associated entity",
                              language="eng", entity_question_flag=True, ddtype=self.entity_id_type)
        question2 = TextField(name="Name", code="NAME", label="Clinic Name",
                              defaultValue="some default value", language="eng", length=TextConstraint(4, 15),
                              ddtype=self.name_type)
        question3 = IntegerField(name="Arv stock", code="ARV", label="ARV Stock",
                                 range=NumericConstraint(min=15, max=120), ddtype=self.stock_type)
        question4 = SelectField(name="Color", code="COL", label="Color",
                                options=[("RED", 1), ("YELLOW", 2)], ddtype=self.color_type)

        self.form_model = FormModel(self.dbm, entity_type=self.entity_type, name="aids", label="Aids form_model",
                                    form_code="clinic", type='survey', fields=[question1, question2, question3])
        self.form_model.add_field(question4)
        self.form_model__id = self.form_model.save()

        self.submission_handler = SubmissionHandler(self.dbm)
        self.sms_player = SMSPlayer(self.dbm, self.submission_handler, LocationTree())
    def CreateFormModel(self):
        question1 = TextField(name="entity_question", code="ID", label="What is the school reported on?", language="eng",entity_question_flag=True, ddtype=self.default_ddtype)
        question2 = TextField(name="Your Name", code="Q1", label="What is your name", defaultValue="some default value", language="eng", ddtype=self.default_ddtype)
        question3 = IntegerField(name="Your Age", code="Q2", label="What is your age", ddtype=self.default_ddtype)
        question4 = SelectField(name="Color", code="Q3", label="What is your favourite color", options=[("RED", 1), ("YELLOW", 2)], ddtype=self.integer_ddtype)

        form_code = "form001"
        self.form_model = FormModel(self.manager, entity_type=self.entity_type, name="SCHOOL_FORM_MODEL", label="School form_model", form_code=form_code, type='survey',fields=[question1, question2, question3, question4])

        try:
            qid = self.form_model.save()
        except DataObjectAlreadyExists as e:
            get_form_model_by_code(self.manager, form_code).delete()
            qid = self.form_model.save()

        return form_code, qid
Пример #41
0
 def _create_form_model(self):
     self.entity_type = ["HealthFacility", "Clinic"]
     define_type(self.dbm, ["HealthFacility", "Clinic"])
     self.default_ddtype = DataDictType(self.dbm, name='Default String Datadict Type', slug='string_default',
                                        primitive_type='string')
     self.default_ddtype.save()
     question1 = TextField(name="entity_question", code="ID", label="What is associated entity",
                           language="eng", entity_question_flag=True, ddtype=self.default_ddtype)
     question2 = TextField(name="question1_Name", code="Q1", label="What is your name",
                           defaultValue="some default value", language="eng", length=TextConstraint(5, 10),
                           ddtype=self.default_ddtype)
     question3 = IntegerField(name="Father's age", code="Q2", label="What is your Father's Age",
                              range=NumericConstraint(min=15, max=120), ddtype=self.default_ddtype)
     question4 = SelectField(name="Color", code="Q3", label="What is your favourite color",
                             options=[("RED", 1), ("YELLOW", 2)], ddtype=self.default_ddtype)
     self.form_model = FormModel(self.dbm, entity_type=self.entity_type, name="aids", label="Aids form_model",
                                 form_code="1", type='survey', fields=[
             question1, question2, question3, question4])
     self.form_model__id = self.form_model.save()
Пример #42
0
 def test_should_create_a_questionnaire_from_dictionary(self):
     fields = [
             {
             "name": "What are you reporting on?",
             "defaultValue": "",
             "label": {
                 "eng": "Entity being reported on"
             },
             "entity_question_flag": True,
             "type": "text",
             "ddtype": self.default_ddtype.to_json(),
             "code": "eid",
             "length": {"min": 1, "max": 10},
             },
             {
             "range": {
                 "max": 10,
                 "min": 0
             },
             "label": {"eng": ""},
             "type": "integer",
             "ddtype": self.default_ddtype.to_json(),
             "name": "What is your age?",
             "code": "AGE"
         },
             {
             "choices": [
                     {
                     "text": {"eng": "Pune"}
                 },
                     {
                     "text": {"eng": "Bangalore"}
                 }
             ],
             "label": {"eng": ""},
             "type": "select",
             "ddtype": self.default_ddtype.to_json(),
             "name": "Where do you live?",
             "code": "PLC"
         }]
     document = FormModelDocument()
     document.json_fields = fields
     document.entity_type = ["Reporter"]
     document.document_type = "FormModel"
     document.form_code = "F1"
     document.name = "New Project"
     document.type = "survey"
     document.type = "survey"
     entityQ = TextField(name="What are you reporting on?", code="eid",
                         label="Entity being reported on", entity_question_flag=True,
                         length=TextConstraint(min=1, max=10), ddtype=self.default_ddtype)
     ageQ = IntegerField(name="What is your age?", code="AGE", label="",
                         range=NumericConstraint(min=0, max=10), ddtype=self.default_ddtype)
     placeQ = SelectField(name="Where do you live?", code="PLC", label="",
                          options=[{"text": {"eng": "Pune"}}, {"text": {"eng": "Bangalore"}}],
                          single_select_flag=False, ddtype=self.default_ddtype)
     questions = [entityQ, ageQ, placeQ]
     questionnaire = FormModel.new_from_doc(self.dbm, document)
     self.maxDiff = None
     self.assertListEqual(questionnaire.entity_type, ["Reporter"])
     self.assertEqual(questionnaire.name, "New Project")
     self.assertEqual(questionnaire.type, "survey")
     for i in range(len(questions)):
         self.assertEqual(questionnaire.fields[i]._to_json(), questions[i]._to_json())
Пример #43
0
class TestShouldSaveSMSSubmission(unittest.TestCase):
    def setUp(self):
        self.dbm = get_db_manager(database='mangrove-test')
        initializer.run(self.dbm)
        define_type(self.dbm, ["dog"])
        self.entity_type = ["healthfacility", "clinic"]
        define_type(self.dbm, self.entity_type)
        self.name_type = DataDictType(self.dbm, name='Name', slug='name', primitive_type='string')
        self.telephone_number_type = DataDictType(self.dbm, name='telephone_number', slug='telephone_number',
                                                  primitive_type='string')
        self.entity_id_type = DataDictType(self.dbm, name='Entity Id Type', slug='entity_id', primitive_type='string')
        self.stock_type = DataDictType(self.dbm, name='Stock Type', slug='stock', primitive_type='integer')
        self.color_type = DataDictType(self.dbm, name='Color Type', slug='color', primitive_type='string')

        self.name_type.save()
        self.telephone_number_type.save()
        self.stock_type.save()
        self.color_type.save()

        self.entity = create_entity(self.dbm, entity_type=self.entity_type,
                                    location=["India", "Pune"], aggregation_paths=None, short_code="cli1",
                                    )

        self.data_record_id = self.entity.add_data(data=[("Name", "Ruby", self.name_type)],
                                                   submission=dict(submission_id="1"))

        self.reporter = create_entity(self.dbm, entity_type=["reporter"],
                                      location=["India", "Pune"], aggregation_paths=None, short_code="rep1",
                                      )

        self.reporter.add_data(data=[(MOBILE_NUMBER_FIELD, '1234', self.telephone_number_type),
                (NAME_FIELD, "Test_reporter", self.name_type)], submission=dict(submission_id="2"))

        question1 = TextField(name="entity_question", code="EID", label="What is associated entity",
                              language="eng", entity_question_flag=True, ddtype=self.entity_id_type)
        question2 = TextField(name="Name", code="NAME", label="Clinic Name",
                              defaultValue="some default value", language="eng", length=TextConstraint(4, 15),
                              ddtype=self.name_type)
        question3 = IntegerField(name="Arv stock", code="ARV", label="ARV Stock",
                                 range=NumericConstraint(min=15, max=120), ddtype=self.stock_type)
        question4 = SelectField(name="Color", code="COL", label="Color",
                                options=[("RED", 1), ("YELLOW", 2)], ddtype=self.color_type)

        self.form_model = FormModel(self.dbm, entity_type=self.entity_type, name="aids", label="Aids form_model",
                                    form_code="clinic", type='survey', fields=[question1, question2, question3])
        self.form_model.add_field(question4)
        self.form_model__id = self.form_model.save()

        self.submission_handler = SubmissionHandler(self.dbm)
        self.sms_player = SMSPlayer(self.dbm, self.submission_handler, LocationTree())

    def tearDown(self):
        _delete_db_and_remove_db_manager(self.dbm)

    def send_sms(self, text):
        transport_info = TransportInfo(transport="sms", source="1234", destination="5678")
        response = self.sms_player.accept(Request(transportInfo=transport_info, message=text))
        return response

    def test_should_save_submitted_sms(self):
        text = "clinic +EID %s +name CLINIC-MADA +ARV 50 +COL a" % self.entity.short_code

        response = self.send_sms(text)

        self.assertTrue(response.success)

        data_record_id = response.datarecord_id
        data_record = self.dbm._load_document(id=data_record_id, document_class=DataRecordDocument)
        self.assertEqual(self.name_type.slug, data_record.data["Name"]["type"]["slug"])
        self.assertEqual(self.stock_type.slug, data_record.data["Arv stock"]["type"]["slug"])
        self.assertEqual(self.color_type.slug, data_record.data["Color"]["type"]["slug"])
        self.assertEqual("clinic", data_record.submission['form_code'])
        self.assertEqual(u"Test_reporter",response.reporters[0].get(NAME_FIELD))

        data = self.entity.values({"Name": "latest", "Arv stock": "latest", "Color": "latest"})
        self.assertEquals(data["Arv stock"], 50)
        self.assertEquals(data["Name"], "CLINIC-MADA")
        submission_log = self.dbm._load_document(response.submission_id, SubmissionLogDocument)
        self.assertEquals(data_record_id, submission_log.data_record_id)

    def test_should_save_submitted_sms_for_activity_report(self):
        question1 = TextField(name="entity_question", code="EID", label="What is associated entity",
                              language="eng", entity_question_flag=True, ddtype=self.entity_id_type)
        question2 = TextField(name="Name", code="NAME", label="Clinic Name",
                              defaultValue="some default value", language="eng", length=TextConstraint(4, 15),
                              ddtype=self.name_type)
        question3 = IntegerField(name="Arv stock", code="ARV", label="ARV Stock",
                                 range=NumericConstraint(min=15, max=120), ddtype=self.stock_type)
        activity_report = FormModel(self.dbm, entity_type=["reporter"], name="report", label="reporting form_model",
                                    form_code="acp", type='survey', fields=[question1, question2, question3])
        activity_report.save()

        text = "acp +name tester +ARV 50 "

        response = self.send_sms(text)

        self.assertTrue(response.success)
        self.assertEqual(u"Test_reporter",response.reporters[0].get(NAME_FIELD))

        data_record_id = response.datarecord_id
        data_record = self.dbm._load_document(id=data_record_id, document_class=DataRecordDocument)
        self.assertEqual(self.name_type.slug, data_record.data["Name"]["type"]["slug"])
        self.assertEqual(self.stock_type.slug, data_record.data["Arv stock"]["type"]["slug"])
        self.assertEqual("acp", data_record.submission['form_code'])
        data = self.reporter.values({"Name": "latest", "Arv stock": "latest"})
        self.assertEquals(data["Arv stock"], 50)
        self.assertEquals(data["Name"], "tester")
        submission_log = self.dbm._load_document(response.submission_id, SubmissionLogDocument)
        self.assertEquals(data_record_id, submission_log.data_record_id)

    def test_should_give_error_for_wrong_integer_value(self):
        text = "clinic +EID %s +ARV 150 " % self.entity.id
        response = self.send_sms(text)
        self.assertFalse(response.success)
        self.assertEqual(len(response.errors), 1)

    def test_should_give_error_for_wrong_text_value(self):
        text = "clinic +EID CID001 +NAME ABC"

        response = self.send_sms(text)
        self.assertFalse(response.success)
        self.assertEqual(len(response.errors), 1)

    def test_get_submissions_for_form(self):
        self.dbm._save_document(SubmissionLogDocument(channel="transport", source=1234,
                                                      destination=12345, form_code="abc",
                                                      values={'Q1': 'ans1', 'Q2': 'ans2'},
                                                      status=False, error_message="", data_record_id='2345678'))
        self.dbm._save_document(SubmissionLogDocument(channel="transport", source=1234,
                                                      destination=12345, form_code="abc",
                                                      values={'Q1': 'ans12', 'Q2': 'ans22'},
                                                      status=False, error_message="", data_record_id='1234567'))
        self.dbm._save_document(SubmissionLogDocument(channel="transport", source=1234,
                                                      destination=12345, form_code="def",
                                                      values={'defQ1': 'defans12', 'defQ2': 'defans22'},
                                                      status=False, error_message="", data_record_id='345678'))

        oneDay = datetime.timedelta(days=1)
        tomorrow = datetime.datetime.now() + oneDay
        submission_list, ids = get_submissions_made_for_form(self.dbm, "abc", 0,
                                                             int(mktime(tomorrow.timetuple())) * 1000)
        self.assertEquals(2, len(submission_list))
        self.assertEquals({'Q1': 'ans12', 'Q2': 'ans22'}, submission_list[0]['values'])
        self.assertEquals({'Q1': 'ans1', 'Q2': 'ans2'}, submission_list[1]['values'])
        self.assertEquals(2, len(ids))
        self.assertListEqual(['1234567', '2345678'], ids)

    def test_error_messages_are_being_logged_in_submissions(self):
        text = "clinic +EID %s +ARV 150 " % self.entity.id
        self.send_sms(text)
        oneDay = datetime.timedelta(days=1)
        tomorrow = datetime.datetime.now() + oneDay
        submission_list, ids = get_submissions_made_for_form(self.dbm, "clinic", 0,
                                                             int(mktime(tomorrow.timetuple())) * 1000)
        self.assertEquals(1, len(submission_list))
        self.assertEquals(u"Answer 150 for question ARV is greater than allowed.", submission_list[0]['error_message'])


    def test_should_register_new_entity(self):
        message1 = """reg +t  dog +n  Clinic in Diégo–Suarez +l  Diégo–Suarez +g  -12.35  49.3  +d This is a Clinic in
        Diégo–Suarez + m
        87654325
        """
        response = self.send_sms(message1)
        self.assertTrue(response.success)
        self.assertIsNotNone(response.datarecord_id)
        expected_short_code = "dog1"
        self.assertEqual(response.short_code, expected_short_code)
        a = get_by_short_code(self.dbm, expected_short_code, ["dog"])
        self.assertEqual(a.short_code, expected_short_code)

        text = "reg +N buddy +S bud +T dog +G 80 80 +D its a dog! +M 45557"

        response = self.send_sms(text)
        self.assertTrue(response.success)
        self.assertIsNotNone(response.datarecord_id)
        self.assertEqual(response.short_code, "bud", ["dog"])
        a = get_by_short_code(self.dbm, "bud", ["dog"])
        self.assertEqual(a.short_code, "bud")

        text = "reg +N buddy2 +T dog +L 80 80 +D its another dog! +M 78541"

        response = self.send_sms(text)
        self.assertTrue(response.success)
        self.assertIsNotNone(response.datarecord_id)
        expected_short_code = "dog3"
        self.assertEqual(response.short_code, expected_short_code)
        b = get_by_short_code(self.dbm, expected_short_code, ["dog"])
        self.assertEqual(b.short_code, expected_short_code)

    def test_should_return_error_for_registration_having_invalid_geo_data(self):
        INVALID_LATITUDE = 380
        text = "reg +N buddy2 +T dog +G %s 80 +D its another dog! +M 78541" % (INVALID_LATITUDE,)

        response = self.send_sms(text)
        self.assertFalse(response.success)
        self.assertEqual({'g': 'The answer 380 must be between -90 and 90'}, response.errors)

        INVALID_LONGITUDE = -184
        text = "reg +N buddy2 +T dog +G 80 %s +D its another dog! +M 78541" % (INVALID_LONGITUDE,)

        response = self.send_sms(text)
        self.assertFalse(response.success)
        self.assertEqual({'g': 'The answer -184 must be between -180 and 180'}, response.errors)

    def test_should_log_submission(self):
        transport_info = TransportInfo(transport="sms", source="1234", destination="5678")
        request = Request(transportInfo=transport_info, message="reg +N buddy +S DOG3 +T dog")

        response = self.sms_player.accept(request)
        submission_log = self.dbm._load_document(response.submission_id, SubmissionLogDocument)
        self.assertIsInstance(submission_log, SubmissionLogDocument)
        self.assertEquals(transport_info.transport, submission_log.channel)
        self.assertEquals(transport_info.source, submission_log.source)
        self.assertEquals(transport_info.destination, submission_log.destination)
        self.assertEquals(True, submission_log. status)
        self.assertEquals("reg", submission_log.form_code)
        self.assertEquals({'n': 'buddy', 's': 'DOG3', 't': 'dog', 'l':None}, submission_log.values)
        self.assertEquals(transport_info.destination, submission_log.destination)
        self.assertEquals(response.datarecord_id, submission_log.data_record_id)


    def test_should_throw_error_if_entity_with_same_short_code_exists(self):
        text = "reg +N buddy +S DOG3 +T dog +G 80 80 +D its a dog! +M 123456"
        self.send_sms(text)
        text = "reg +N buddy2 +S dog3 +T dog +L 80 80 +D its a dog! +M 123456"
        with self.assertRaises(DataObjectAlreadyExists):
            self.send_sms(text)

    def test_should_throw_error_if_reporter_with_same_phone_number_exists(self):
        text = "reg +N buddy +T reporter +G 80 80 +M 1@23456"
        self.send_sms(text)
        with self.assertRaises(MultipleReportersForANumberException):
            text = "reg +N buddy2 +T reporter +L 80 80 +M 123456"
            self.send_sms(text)

    def test_should_throw_error_if_reporter_registration_submission_has_no_mobile_number(self):
        with self.assertRaises(MobileNumberMissing):
            text = "reg +N buddy2 +T reporter +L 80 80"
            self.send_sms(text)

    def test_should_throw_error_if_entityType_doesnt_exist(self):
        with self.assertRaises(EntityTypeDoesNotExistsException):
            text = "reg +N buddy1 +S DOG3 +T cat +L 80 80 +D its another dog! +M 1234567"
            self.send_sms(text)

    def test_entity_instance_is_case_insensitive(self):
        text = "clinic +EID %s +name CLINIC-MADA +ARV 50 +COL a" % "CLI1"

        response = self.send_sms(text)

        self.assertTrue(response.success)

    def test_questionnaire_code_is_case_insensitive(self):
        text = "CLINIC +EID %s +name CLINIC-MADA +ARV 50 +COL a" % "cli1"
        response = self.send_sms(text)
        self.assertTrue(response.success)

    def test_entity_type_is_case_insensitive_in_registration(self):
        text = "reg +n buddy +T DOG +G 80 80 +M 123456"
        response = self.send_sms(text)
        self.assertTrue(response.success)
        data_record = self.dbm._load_document(response.datarecord_id, DataRecordDocument)
        actual_type = data_record["entity"]["aggregation_paths"]["_type"]
        self.assertEquals(["dog"], actual_type)

    def test_should_accept_unicode_submissions(self):
        text = "reg +s Āgra +n Agra +m 080 +t clinic +g 45 56"
        with self.assertRaises(EntityTypeDoesNotExistsException):
            self.send_sms(text)

    def test_should_accept_unicode_submissions_and_invalidate_wrong_GPS(self):
        text = "reg +s Āgra +n Agra +m 080 +t clinic +g 45Ö 56"
        with self.assertRaises(GeoCodeFormatException):
            self.send_sms(text)

    def test_should_raise_exception_for_inactive_form_model(self):
        self.form_model.deactivate()
        self.form_model.save()
        text = "clinic +EID %s +name CLINIC-MADA +ARV 50 +COL a" % self.entity.short_code
        with self.assertRaises(InactiveFormModelException):
            self.send_sms(text)

    def test_should_set_submission_log_as_Test_for_form_model_in_test_mode(self):
        self.form_model.set_test_mode()
        self.form_model.save()
        text = "clinic +EID %s +name CLINIC-MADA +ARV 50 +COL a" % self.entity.short_code
        response = self.send_sms(text)

        self.assertTrue(response.success)
        self.assertIsNotNone(response.datarecord_id)
        self.assertIsNotNone(response.submission_id)
        submission_log = self.dbm._load_document(response.submission_id, SubmissionLogDocument)
        self.assertTrue(submission_log.test)


    def test_should_register_entity_with_geo_code(self):
        message1 = """reg +t dog +n Dog in Diégo–Suarez +g -12.35  49.3  +d This is a Dog in
        Diégo–Suarez + m
        87654325
        """
        response = self.send_sms(message1)
        self.assertTrue(response.success)
        self.assertIsNotNone(response.datarecord_id)
        expected_short_code = 'dog1'
        self.assertEqual(response.short_code, expected_short_code)
        dog = get_by_short_code(self.dbm, expected_short_code, ["dog"])
        self.assertEqual([-12.35 , 49.3] ,dog.geometry.get("coordinates"))

    def test_should_register_entity_with_geocode_if_only_location_provided(self):
        message1 = """reg +t dog +n Dog in AMPIZARANTANY +l AMPIZARANTANY +d This is a Dog in
        AMPIZARANTANY + m
        87654325
        """
        response = self.send_sms(message1)
        self.assertTrue(response.success)
        self.assertIsNotNone(response.datarecord_id)
        expected_short_code = 'dog1'
        self.assertEqual(response.short_code, expected_short_code)
        dog = get_by_short_code(self.dbm, expected_short_code, ["dog"])
        self.assertEqual([-12, 60] ,dog.geometry.get("coordinates"))

    def test_should_register_entity_with_geocode_and_location_provided(self):
        message1 = """reg +t dog +n Dog in AMPIZARANTANY +l AMPIZARANTANY +g 10 10 +d This is a Dog in
        AMPIZARANTANY + m
        87654325
        """
        response = self.send_sms(message1)
        self.assertTrue(response.success)
        self.assertIsNotNone(response.datarecord_id)
        expected_short_code = 'dog1'
        self.assertEqual(response.short_code, expected_short_code)
        dog = get_by_short_code(self.dbm, expected_short_code, ["dog"])
        self.assertEqual([10, 10] ,dog.geometry.get("coordinates"))
        self.assertEqual(["ampizarantany"] ,dog.location_path)
class TestFormModel(unittest.TestCase):
    def setUp(self):
        self.dbm = Mock(spec=DatabaseManager)
        self.datadict_patcher = patch("mangrove.form_model.form_model.get_or_create_data_dict")
        self.datadict_mock = self.datadict_patcher.start()
        self.ddtype_mock = Mock(spec=DataDictType)
        self.datadict_mock.return_value = self.ddtype_mock

        q1 = TextField(name="entity_question", code="ID", label="What is associated entity",
                              language="eng", entity_question_flag=True, ddtype=self.ddtype_mock)
        q2 = TextField(name="question1_Name", code="Q1", label="What is your name",
                              defaultValue="some default value", language="eng", length=TextConstraint(5, 10),
                              ddtype=self.ddtype_mock)
        q3 = IntegerField(name="Father's age", code="Q2", label="What is your Father's Age",
                                 range=NumericConstraint(min=15, max=120), ddtype=self.ddtype_mock)
        q4 = SelectField(name="Color", code="Q3", label="What is your favourite color",
                                options=[("RED", 1), ("YELLOW", 2)], ddtype=self.ddtype_mock)
        q5 = TextField(name="Desc", code="Q4", label="Description", ddtype=self.ddtype_mock)

        self.form_model = FormModel(self.dbm, entity_type=["XYZ"], name="aids", label="Aids form_model",
                                    form_code="1", type='survey', fields=[#        expected_short_code = "dog3"
#        self.assertEqual(response.short_code, expected_short_code)
#        b = get_by_short_code(self.dbm, expected_short_code, ["dog"])
#        self.assertEqual(b.short_code, expected_short_code)

                    q1, q2, q3, q4, q5])


    def tearDown(self):
        self.datadict_patcher.stop()

    def test_should_create_registration_form_mode(self):
        form = _construct_registration_form(self.dbm)
        self.assertEqual(7, len(form.fields))
        self.assertEqual(REGISTRATION_FORM_CODE, form.form_code)

    def test_registration_form_should_have_entity_type_field(self):
        form = _construct_registration_form(self.dbm)
        field = form.get_field_by_code("T")
        self.assertIsNotNone(field)


    def test_should_validate_for_valid_integer_value(self):
        answers = {"ID": "1", "Q2": "16"}
        cleaned_answers, errors = self.form_model._is_valid(answers)
        self.assertTrue(len(errors) == 0)

    def test_should_return_error_for_invalid_integer_value(self):
        answers = {"id": "1", "q2": "200"}
        cleaned_answers, errors = self.form_model._is_valid(answers)
        self.assertEqual(len(errors), 1)
        self.assertEqual({'q2': 'Answer 200 for question Q2 is greater than allowed.'}, errors)
        self.assertEqual({'ID': '1'}, cleaned_answers)

    def test_should_ignore_field_validation_if_the_answer_is_not_present(self):
        answers = {"id": "1", "q1": "Asif Momin", "q2": "20"}
        expected_result = {"ID": "1", "Q1": "Asif Momin", "Q2": 20}
        cleaned_answers, errors = self.form_model._is_valid(answers)
        self.assertTrue(len(errors) == 0)
        self.assertEqual(cleaned_answers, expected_result)

    def test_should_ignore_field_validation_if_the_answer_blank(self):
        answers = {"id": "1", "q1": "Asif Momin", "q2": ""}
        expected_result = {"ID": "1", "Q1": "Asif Momin"}
        cleaned_answers, errors = self.form_model._is_valid(answers)
        self.assertTrue(len(errors) == 0)
        self.assertEqual(cleaned_answers, expected_result)

    def test_should_validate_for_valid_text_value(self):
        answers = {"ID": "1", "Q1": "Asif Momin"}
        cleaned_answers, errors = self.form_model._is_valid(answers)
        self.assertTrue(len(errors) == 0)

    def test_should_return_errors_for_invalid_text_and_integer(self):
        answers = {"id": "1", "q1": "Asif", "q2": "200", "q3": "a"}
        cleaned_answers, errors = self.form_model._is_valid(answers)
        self.assertEqual(len(errors), 2)
        self.assertEqual({'q1': 'Answer Asif for question Q1 is shorter than allowed.',
                          'q2': 'Answer 200 for question Q2 is greater than allowed.'}, errors)
        self.assertEqual({'Q3': ['RED'], 'ID': '1'}, cleaned_answers)

    def test_should_strip_whitespaces(self):
        answers = {"id": "1", "q1": "   My Name", "q2": "  40 ", "q3": "a     ", "q4": "    "}
        expected_cleaned_data = {'ID': '1', "Q1": "My Name", "Q2": 40,
                                 "Q3": ["RED"]}
        cleaned_answers, errors = self.form_model._is_valid(answers)
        self.assertTrue(len(errors) == 0)
        self.assertEqual(0, len(errors))
        self.assertEqual(cleaned_answers, expected_cleaned_data)

    def test_give_error_for_no_entity_short_code(self):
        with self.assertRaises(EntityQuestionCodeNotSubmitted):
            answers = {"Q2": "10"}
            self.form_model._is_valid(answers)

    def test_should_validate_field_case_insensitive(self):
        answers = {"Id": "1", "Q1": "Asif Momin", "q2": "40"}
        cleaned_answers, errors = self.form_model._is_valid(answers)
        self.assertTrue(len(errors) == 0)
        self.assertEqual({}, errors)


    def test_should_return_valid_form_submission(self):
        answers = {"ID": "1", "Q2": "16"}
        form_submission = self.form_model.validate_submission(answers)
        self.assertTrue(form_submission.is_valid)
        self.assertEqual("1", form_submission.short_code)
        self.assertEqual({"Q2": 16.0, 'ID': '1'}, form_submission.cleaned_data)
        self.assertEqual(0, len(form_submission.errors))

    def test_should_return_invalid_form_submission(self):
        answers = {"ID": "1", "Q2": "non number value"}
        form_submission = self.form_model.validate_submission(answers)
        self.assertFalse(form_submission.is_valid)
        self.assertEqual("1", form_submission.short_code)
        self.assertEqual({'ID': '1'}, form_submission.cleaned_data)
        self.assertEqual(1, len(form_submission.errors))

    def test_should_assert_activity_report(self):

        question1 = TextField(name="question1_Name", code="Q1", label="What is your name",
                              defaultValue="some default value", language="eng", length=TextConstraint(5, 10),
                              ddtype=self.ddtype_mock)
        activity_report = FormModel(self.dbm, entity_type=["reporter"], name="aids", label="Aids form_model",
                                        form_code="1", type='survey', fields=[question1])
        self.assertTrue(activity_report.entity_defaults_to_reporter())

    def test_form_model_is_active_when_created(self):
        self.assertTrue(self.form_model.is_active())

    def test_should_be_able_to_deactivate_the_form_model(self):
        self.form_model.deactivate()
        self.assertFalse(self.form_model.is_active())

    def test_should_be_able_to_activate_the_form_model(self):
        self.form_model.deactivate()
        self.assertFalse(self.form_model.is_active())
        self.form_model.activate()
        self.assertTrue(self.form_model.is_active())

    def test_should_be_able_to_put_the_form_model_in_test_mode(self):
        self.form_model.set_test_mode()
        self.assertTrue(self.form_model.is_in_test_mode())

    def test_create_form_submission_with_entity_type_as_lowercase_list_of_string(self):
        answers = {"s": "1", "t": "Reporter"}
        registration_form = _construct_registration_form(self.dbm)
        form_submission = registration_form.validate_submission(answers)
        self.assertEqual(["reporter"], form_submission.entity_type)

        answers = {"s": "1", "t": ["Reporter"]}
        form_submission = registration_form.validate_submission(answers)
        self.assertEqual(["reporter"], form_submission.entity_type)
class AssignmentTestCase(unittest.TestCase):
    def InitDb(self, server, database):
        self.manager = get_db_manager(server=server, database=database)
        _delete_db_and_remove_db_manager(self.manager)
        self.manager = get_db_manager(server=server, database=database)
        initializer.run(self.manager)


    def setUp(self):
        self.InitDb(server="http://localhost:5984", database="assignment")
        print "Connected to %s/%s" % (self.manager.url, self.manager.database_name)

        self.entity_type = ["School"]
        self.reporter_type=['reporter']
        self.phone_number_type = DataDictType(self.manager, name='Telephone Number', slug='telephone_number', primitive_type='string')
        self.first_name_type = DataDictType(self.manager, name='First Name', slug='first_name', primitive_type='string')
        self.default_ddtype = DataDictType(self.manager, name='Default String Datadict Type', slug='string_default', primitive_type='string')
        self.integer_ddtype = DataDictType(self.manager, name='Default Ingeger Datadict Type', slug='integer_default', primitive_type='number')
#        self.default_ddtype.save()

    def tearDown(self):
#        _delete_db_and_remove_db_manager(self.manager)
        pass


    def test_db_initializer(self):
        self.assertEqual("http://localhost:5984", self.manager.url)
        self.assertEqual("assignment", self.manager.database_name)


    def CreateSchoolEntityType(self):
        define_type(self.manager, self.entity_type)
        print "Entity Type is", self.entity_type

    def test_create_entity_type_named_school(self):
        paths = AggregationTree.get(self.manager, ENTITY_TYPE_TREE_ID, get_or_create=True).get_paths()
        self.assertNotIn(self.entity_type, paths)
        self.assertIn(['reporter'], paths)
        self.CreateSchoolEntityType()

        paths = AggregationTree.get(self.manager, ENTITY_TYPE_TREE_ID, get_or_create=True).get_paths()
        self.assertIn(self.entity_type, paths)

    def CreateSchool(self, data, id, short_code):
        school = Entity(self.manager, self.entity_type, data, id=id, short_code=short_code)
        school_id = school.save()
        school.add_data(data=[("SchoolID", id, self.default_ddtype),
                            ("SchollName", short_code, self.default_ddtype),
                            ("SchoolLocation", data, self.default_ddtype)])

        return school_id

    def CreateSchoolByFormModel(self):
        field1 = TextField(name="entity_question", code="i", label="What is scholl entity",language="en", entity_question_flag=True, ddtype=self.default_ddtype)
        field2 = TextField(name="School_name", code="n", label="What is scholl name",language="en", ddtype=self.default_ddtype)
        field3 = TextField(name="school_location", code="g", label="What is scholl location",language="en", ddtype=self.default_ddtype)
        field4 = TextField(name="school_type", code="t", label="What is scholl type",language="en", ddtype=self.default_ddtype)

        model = FormModel(self.manager, name="school", label="fds", form_code="School", entity_type=self.entity_type, is_registration_model=True, fields=[field1, field2, field3, field4])
        model.save()

        FormSubmission(model, OrderedDict({"i": "bh1", "n": "beihang", "g": ["beijing"], "t": "university"})).save(self.manager)
        FormSubmission(model, OrderedDict({"i": "qh1", "n": "qinghua", "g": ["beijing"], "t": "university"})).save(self.manager)
        FormSubmission(model, OrderedDict({"i": "bd1", "n": "beida", "g": ["beijing"], "t": "university"})).save(self.manager)

    def CreateSchoolByGlobalFormModel(self):
        global_form = get_form_model_by_code(self.manager, REGISTRATION_FORM_CODE)
        submission = OrderedDict({"t": self.entity_type, "n": "beihang-global", "s": "bh-g", "l": ["Global","China"],"m": "12345678987654321","g":(1,1)})
#        GlobalRegistrationFormSubmission(global_form, submission, errors=None).save(self.manager)

        FormSubmissionFactory().get_form_submission(global_form, submission).save(self.manager)

    def test_create_school_entity(self):
        school = self.CreateSchool(data=['China', 'Beijing', 'HaiDian'], id='BeiHang', short_code="bh")

        school = get_by_short_code(self.manager, "bh", self.entity_type)
        self.assertEqual(beihang_id, 'BeiHang')
        self.assertEqual(school.short_code, 'bh')


    def CreateReporter(self):
        reporter = Entity(self.manager, location=["China", "Beijing"], short_code="rpt_bj", id="Reporter001",
            entity_type=self.reporter_type)
        reporter.add_data(data=[(MOBILE_NUMBER_FIELD, "1234567890", self.phone_number_type),(NAME_FIELD, "001s", self.first_name_type)])
        reporter_id = reporter.save()
        return reporter_id, reporter

    def test_create_reporter(self):
        reporter_id,r = self.CreateReporter()
        self.assertEqual(reporter_id, 'Reporter001')

        reporter = get_by_short_code(self.manager, "rpt_bj", self.reporter_type)
        self.assertEqual(reporter.short_code, "rpt_bj")


    def CreateFormModel(self):
        question1 = TextField(name="entity_question", code="ID", label="What is the school reported on?", language="eng",entity_question_flag=True, ddtype=self.default_ddtype)
        question2 = TextField(name="Your Name", code="Q1", label="What is your name", defaultValue="some default value", language="eng", ddtype=self.default_ddtype)
        question3 = IntegerField(name="Your Age", code="Q2", label="What is your age", ddtype=self.default_ddtype)
        question4 = SelectField(name="Color", code="Q3", label="What is your favourite color", options=[("RED", 1), ("YELLOW", 2)], ddtype=self.integer_ddtype)

        form_code = "form001"
        self.form_model = FormModel(self.manager, entity_type=self.entity_type, name="SCHOOL_FORM_MODEL", label="School form_model", form_code=form_code, type='survey',fields=[question1, question2, question3, question4])

        try:
            qid = self.form_model.save()
        except DataObjectAlreadyExists as e:
            get_form_model_by_code(self.manager, form_code).delete()
            qid = self.form_model.save()

        return form_code, qid

    def test_create_form_model(self):
        form_code, qid = self.CreateFormModel()

        form = get_form_model_by_code(self.manager, form_code)
        self.assertTrue(qid)
        self.assertEqual(form.form_code, form_code)

    def SendSubmission(self, message):
        sms_player = SMSPlayer(self.manager, location_tree=["China", "Beijing"], parser=(OrderSMSParser(self.manager)))
        transport_info = TransportInfo(transport="sms", source="1234567890", destination="5678")
        request = Request(message=message, transportInfo=transport_info)

        return sms_player.accept(request)

    def PrintResult(self, response):
        print "Submission: ", response.entity_type, response.form_code
        print "  Reporter:", response.reporters[0]['name']
        print "  Errors:",
        for questionid, error in response.errors.items():
            print questionid, error

        print "Accepted Answers:"
        for qid, value in response.processed_data.items():
            print qid, value

        print "  For school:", response.short_code
        print "Successfully!" if response.success else "Failed~"



    def test_sms_player(self):
        self.CreateSchoolEntityType()

        bh = self.CreateSchool(data=['China', 'Beijing', 'HaiDian'], id='BeiHang', short_code="bh")
        bh = get_by_short_code(self.manager, "bh", self.entity_type)
        print "Create School:", bh.short_code, bh.id

        bd_id = self.CreateSchool(data=['China', 'Beijing', 'HaiDian'], id='BeiDa', short_code="bd")
        bd = get_by_short_code(self.manager, "bd", self.entity_type)
        print "Create School:", bd.short_code, bd.id

        qh_id = self.CreateSchool(data=['China', 'Beijing', 'HaiDian'], id='QingHua', short_code="qh")
        qh = get_by_short_code(self.manager, "qh", self.entity_type)
        print "Create School:", qh.short_code, qh.id

        self.CreateSchoolByFormModel()
        self.CreateSchoolByGlobalFormModel()

        rpt_id, reporter = self.CreateReporter()
        print "Create Reporter:", reporter.short_code, reporter.id

        form_code, form_id = self.CreateFormModel()
        print "Create Questionnaire:", form_code, form_id

        self.PrintResult(self.SendSubmission("form001 bh zhangsan 22 RED"))

        self.PrintResult(self.SendSubmission("form001 bh lisi 23 2"))
        self.PrintResult(self.SendSubmission("form001 bd wangwu 27 1"))
        self.PrintResult(self.SendSubmission("form001 bd zhaoliu 25 1"))
        self.PrintResult(self.SendSubmission("form001 qh zhouqi 24 2"))
        self.PrintResult(self.SendSubmission("form001 qh zhengba 30 1"))

        count = submission_count(self.manager, "form001", None, None)
        self.assertEqual(6, count)
Пример #46
0
class TestFormModel(unittest.TestCase):
    def setUp(self):
        self.dbm = get_db_manager(database='mangrove-test')
        self._create_form_model()

    def tearDown(self):
        _delete_db_and_remove_db_manager(self.dbm)

    def test_create_form_model(self):
        self.assertTrue(self.form_model__id)

    def test_should_create_registration_form_model(self):
        form = create_default_reg_form_model(self.dbm)
        self.assertEqual(7, len(form.fields))
        self.assertEqual(REGISTRATION_FORM_CODE, form.form_code)
        self.assertEqual('string', form.fields[3].ddtype.primitive_type)

    def test_get_form_model(self):
        e = self.dbm.get(self.form_model__id, FormModel)
        self.assertTrue(e.id)
        self.assertTrue(e.type == "survey")


    def test_should_add_name_of_form_model(self):
        saved = self.dbm.get(self.form_model__id, FormModel)
        self.assertTrue(saved.name == "aids")


    def test_should_add_label(self):
        saved = self.dbm.get(self.form_model__id, FormModel)
        self.assertTrue(saved.label['eng'] == "Aids form_model")

    def test_should_add_short_ids(self):
        saved = self.dbm.get(self.form_model__id, FormModel)
        self.assertTrue(saved.form_code == "1")

    def test_should_add_entity_id(self):
        saved = self.dbm.get(self.form_model__id, FormModel)
        self.assertListEqual(saved.entity_type, self.entity_type)

    def test_should_add_fields(self):
        saved = self.dbm.get(self.form_model__id, FormModel)
        self.assertTrue(len(saved.fields) == 4)
        self.assertTrue(saved.fields[1].name == "question1_Name")
        self.assertTrue(saved.fields[2].name == "Father's age")

    def test_should_add_integer_field_with_constraints(self):
        integer_question = self.dbm.get(self.form_model__id, FormModel).fields[2]
        range_constraint = integer_question.range
        self.assertTrue(integer_question.name == "Father's age")
        self.assertTrue(range_constraint.get("min"), 15)
        self.assertTrue(range_constraint.get("max"), 120)

    def test_should_add_select1_field(self):
        select_question = self.dbm.get(self.form_model__id, FormModel).fields[3]
        option_constraint = select_question.options

        self.assertEquals(len(option_constraint), 2)
        self.assertEquals(option_constraint[0].get("val"), 1)

    def test_should_add_new_field(self):
        form_model = self.dbm.get(self.form_model__id, FormModel)
        question = TextField(name="added_question", code="Q4", label="How are you", ddtype=self.default_ddtype)
        form_model.add_field(question)
        form_model.save()

        added_question = self.dbm.get(self.form_model__id, FormModel).fields[4]
        self.assertEquals(added_question.code, "Q4")

    def test_should_delete_field(self):
        form_model = self.dbm.get(self.form_model__id, FormModel)
        form_model.delete_field(code="Q3")
        form_model.save()
        form_model = self.dbm.get(self.form_model__id, FormModel)
        self.assertEquals(len(form_model.fields), 3)

    def test_should_add_english_as_default_langauge(self):
        activeLangauges = self.form_model.activeLanguages
        self.assertTrue("eng" in activeLangauges)

    def test_should_add_language_to_form_model(self):
        self.form_model.add_language(language="fra", label="French Aids form_model")
        activeLangauges = self.form_model.activeLanguages
        self.assertEquals(len(activeLangauges), 2)
        self.assertTrue("fra" in activeLangauges)
        self.assertEquals(self.form_model.label['fra'], u'French Aids form_model')

    def test_should_delete_all_fields_from_document(self):
        form_model = self.dbm.get(self.form_model__id, FormModel)
        form_model.delete_all_fields()
        self.assertEquals(len(form_model.fields), 0)

    def test_should_delete_all_fields_from_questions(self):
        form_model = self.dbm.get(self.form_model__id, FormModel)
        form_model.delete_all_fields()
        self.assertEquals(len(form_model.fields), 0)

    def test_should_raise_exception_if_entity_field_already_exist(self):
        with self.assertRaises(EntityQuestionAlreadyExistsException):
            form_model = self.dbm.get(self.form_model__id, FormModel)
            question = TextField(name="added_question", code="Q5", label="How are you",
                                 entity_question_flag=True, ddtype=self.default_ddtype)
            form_model.add_field(question)
            form_model.save()

    def test_should_raise_exception_if_code_is_not_unique(self):
        with self.assertRaises(QuestionCodeAlreadyExistsException):
            form_model = self.dbm.get(self.form_model__id, FormModel)
            question = TextField(name="added_question", code="q1", label="How are you",
                                 ddtype=self.default_ddtype)
            form_model.add_field(question)
            form_model.save()

    def test_should_set_form_code(self):
        form_model = self.dbm.get(self.form_model__id, FormModel)
        form_model.form_code = "xyz"
        self.assertEquals(form_model.form_code, "xyz")

    def test_should_persist_ddtype(self):
        form_model = self.dbm.get(self.form_model__id, FormModel)

        self.assertEqual(form_model.fields[0].ddtype.slug, self.default_ddtype.slug)
        self.assertEqual(form_model.fields[0].ddtype.id, self.default_ddtype.id)
        self.assertEqual(form_model.fields[0].ddtype.name, self.default_ddtype.name)

        self.assertEqual(form_model.fields[1].ddtype.slug, self.default_ddtype.slug)
        self.assertEqual(form_model.fields[1].ddtype.id, self.default_ddtype.id)
        self.assertEqual(form_model.fields[1].ddtype.name, self.default_ddtype.name)

        self.assertEqual(form_model.fields[2].ddtype.slug, self.default_ddtype.slug)
        self.assertEqual(form_model.fields[2].ddtype.id, self.default_ddtype.id)
        self.assertEqual(form_model.fields[2].ddtype.name, self.default_ddtype.name)

        self.assertEqual(form_model.fields[3].ddtype.slug, self.default_ddtype.slug)
        self.assertEqual(form_model.fields[3].ddtype.id, self.default_ddtype.id)
        self.assertEqual(form_model.fields[3].ddtype.name, self.default_ddtype.name)

    def test_should_set_entity_type(self):
        form_model = self.dbm.get(self.form_model__id, FormModel)
        form_model.entity_id = "xyz"
        self.assertEquals(form_model.entity_id, "xyz")


    def test_should_create_a_questionnaire_from_dictionary(self):
        fields = [
                {
                "name": "What are you reporting on?",
                "defaultValue": "",
                "label": {
                    "eng": "Entity being reported on"
                },
                "entity_question_flag": True,
                "type": "text",
                "ddtype": self.default_ddtype.to_json(),
                "code": "eid",
                "length": {"min": 1, "max": 10},
                },
                {
                "range": {
                    "max": 10,
                    "min": 0
                },
                "label": {"eng": ""},
                "type": "integer",
                "ddtype": self.default_ddtype.to_json(),
                "name": "What is your age?",
                "code": "AGE"
            },
                {
                "choices": [
                        {
                        "text": {"eng": "Pune"}
                    },
                        {
                        "text": {"eng": "Bangalore"}
                    }
                ],
                "label": {"eng": ""},
                "type": "select",
                "ddtype": self.default_ddtype.to_json(),
                "name": "Where do you live?",
                "code": "PLC"
            }]
        document = FormModelDocument()
        document.json_fields = fields
        document.entity_type = ["Reporter"]
        document.document_type = "FormModel"
        document.form_code = "F1"
        document.name = "New Project"
        document.type = "survey"
        document.type = "survey"
        entityQ = TextField(name="What are you reporting on?", code="eid",
                            label="Entity being reported on", entity_question_flag=True,
                            length=TextConstraint(min=1, max=10), ddtype=self.default_ddtype)
        ageQ = IntegerField(name="What is your age?", code="AGE", label="",
                            range=NumericConstraint(min=0, max=10), ddtype=self.default_ddtype)
        placeQ = SelectField(name="Where do you live?", code="PLC", label="",
                             options=[{"text": {"eng": "Pune"}}, {"text": {"eng": "Bangalore"}}],
                             single_select_flag=False, ddtype=self.default_ddtype)
        questions = [entityQ, ageQ, placeQ]
        questionnaire = FormModel.new_from_doc(self.dbm, document)
        self.maxDiff = None
        self.assertListEqual(questionnaire.entity_type, ["Reporter"])
        self.assertEqual(questionnaire.name, "New Project")
        self.assertEqual(questionnaire.type, "survey")
        for i in range(len(questions)):
            self.assertEqual(questionnaire.fields[i]._to_json(), questions[i]._to_json())

    def test_should_set_name(self):
        self.form_model.name = 'test_name'
        self.assertEquals(self.form_model.name, 'test_name')


    def test_should_set_entity_type_in_doc(self):
        self.form_model.entity_type = ["WaterPoint", "Dam"]
        self.assertEqual(self.form_model.entity_type, ["WaterPoint", "Dam"])

    def test_should_raise_exception_if_form_code_already_exists_on_creation(self):
        question1 = TextField(name="entity_question", code="ID", label="What is associated entity",
                              language="eng", entity_question_flag=True, ddtype=self.default_ddtype)
        form_model = FormModel(self.dbm, entity_type=self.entity_type, name="aids", label="Aids form_model",
                               form_code="1", type='survey', fields=[question1])
        with self.assertRaises(DataObjectAlreadyExists):
            form_model.save()


    def test_should_raise_exception_if_form_code_already_exists_on_updation(self):
        question1 = TextField(name="entity_question", code="ID", label="What is associated entity",
                              language="eng", entity_question_flag=True, ddtype=self.default_ddtype)
        form_model2 = FormModel(self.dbm, entity_type=self.entity_type, name="aids", label="Aids form_model",
                                form_code="2", type='survey', fields=[question1])
        form_model2.save()
        with self.assertRaises(DataObjectAlreadyExists):
            form_model2.form_code = "1"

    def test_should_not_raise_exception_if_form_code_is_updated(self):
        question1 = TextField(name="entity_question", code="ID", label="What is associated entity",
                              language="eng", entity_question_flag=True, ddtype=self.default_ddtype)
        form_model2 = FormModel(self.dbm, entity_type=self.entity_type, name="aids", label="Aids form_model",
                                form_code="2", type='survey', fields=[question1])
        form_model2.save()
        form_model2.form_code = "2"
        form_model2.save()

    def test_to_html(self):
        expected_html ="""<input id=id_entity_question name=entity_question class=class_entity_question type="text"/><input id=id_question1_Name name=question1_Name class=class_question1_Name type="text"/><input id=id_Father's age name=Father's age class=class_Father's age type="text"/><select name="Color" ><option value="1">RED</option><option value="2">YELLOW</option></select>"""
        self.assertEqual(expected_html, to_html(self.form_model))

    def _create_form_model(self):
        self.entity_type = ["HealthFacility", "Clinic"]
        define_type(self.dbm, ["HealthFacility", "Clinic"])
        self.default_ddtype = DataDictType(self.dbm, name='Default String Datadict Type', slug='string_default',
                                           primitive_type='string')
        self.default_ddtype.save()
        question1 = TextField(name="entity_question", code="ID", label="What is associated entity",
                              language="eng", entity_question_flag=True, ddtype=self.default_ddtype)
        question2 = TextField(name="question1_Name", code="Q1", label="What is your name",
                              defaultValue="some default value", language="eng", length=TextConstraint(5, 10),
                              ddtype=self.default_ddtype)
        question3 = IntegerField(name="Father's age", code="Q2", label="What is your Father's Age",
                                 range=NumericConstraint(min=15, max=120), ddtype=self.default_ddtype)
        question4 = SelectField(name="Color", code="Q3", label="What is your favourite color",
                                options=[("RED", 1), ("YELLOW", 2)], ddtype=self.default_ddtype)
        self.form_model = FormModel(self.dbm, entity_type=self.entity_type, name="aids", label="Aids form_model",
                                    form_code="1", type='survey', fields=[
                question1, question2, question3, question4])
        self.form_model__id = self.form_model.save()
def create_clinic_projects(CLINIC_ENTITY_TYPE, manager):
    name_type = create_data_dict(manager, name='Name', slug='Name', primitive_type='string')
    # Entity id is a default type in the system.
    entity_id_type = get_datadict_type_by_slug(manager, slug='entity_id')
    age_type = create_data_dict(manager, name='Age Type', slug='age', primitive_type='integer')
    date_type = create_data_dict(manager, name='Report Date', slug='date', primitive_type='date')
    select_type = create_data_dict(manager, name='Choice Type', slug='choice', primitive_type='select')
    geo_code_type = create_data_dict(manager, name='GeoCode Type', slug='geo_code', primitive_type='geocode')
    question1 = TextField(label="entity_question", code="EID", name="What is associated entity?",
                          language="eng", entity_question_flag=True, ddtype=entity_id_type,
                          length=TextConstraint(min=1, max=12))
    question2 = TextField(label="Name", code="NA", name="What is your name?",
                          length=TextConstraint(min=1, max=10),
                          defaultValue="some default value", language="eng", ddtype=name_type)
    question3 = IntegerField(label="Father age", code="FA", name="What is age of father?",
                             range=NumericConstraint(min=18, max=100), ddtype=age_type)
    question4 = DateField(label="Report date", code="RD", name="What is reporting date?",
                          date_format="dd.mm.yyyy", ddtype=date_type)
    question5 = SelectField(label="Blood Group", code="BG", name="What is your blood group?",
                            options=[("O+", "a"), ("O-", "b"), ("AB", "c"), ("B+", "d")], single_select_flag=True,
                            ddtype=select_type)
    question6 = SelectField(label="Symptoms", code="SY", name="What are symptoms?",
                            options=[("Rapid weight loss", "a"), ("Dry cough", "b"), ("Pneumonia", "c"),
                                     ("Memory loss", "d"), ("Neurological disorders ", "e")], single_select_flag=False,
                            ddtype=select_type)
    question7 = GeoCodeField(name="What is the GPS code for clinic", code="GPS", label="What is the GPS code for clinic?",
                             language="eng", ddtype=geo_code_type)
    form_model = FormModel(manager, name="AIDS", label="Aids form_model",
                           form_code="cli001", type='survey',
                           fields=[question1, question2, question3, question4, question5, question6, question7],
                           entity_type=CLINIC_ENTITY_TYPE
    )
    try:
        qid = form_model.save()
    except DataObjectAlreadyExists as e:
        get_form_model_by_code(manager, "cli001").delete()
        qid = form_model.save()
    project = Project(name="Clinic Test Project", goals="This project is for automation", project_type="survey",
                      entity_type=CLINIC_ENTITY_TYPE[-1], devices=["sms"], activity_report='no',sender_group="close")
    project.qid = qid
    project.state = ProjectState.ACTIVE
    try:
        project.save(manager)
    except Exception:
        pass
    form_model2 = FormModel(manager, name="AIDS", label="Aids form_model",
                            form_code="cli002", type='survey',
                            fields=[question1, question2, question3, question4, question5, question6, question7],
                            entity_type=CLINIC_ENTITY_TYPE)
    try:
        qid2 = form_model2.save()
    except DataObjectAlreadyExists as e:
        get_form_model_by_code(manager, "cli002").delete()
        qid2 = form_model2.save()
    project2 = Project(name="Clinic2 Test Project", goals="This project is for automation", project_type="survey",
                       entity_type=CLINIC_ENTITY_TYPE[-1], devices=["sms"], activity_report='no', sender_group="close")
    project2.qid = qid2
    project2.state = ProjectState.ACTIVE
    try:
        project2.save(manager)
    except Exception:
        pass
Пример #48
0
class TestProjectModel(unittest.TestCase):
    def setUp(self):
        self.dbm = get_db_manager(database='mangrove-test')
        create_views(self.dbm)
        self.project1 = Project(name="Test1", goals="Testing", project_type="Survey", entity_type="Clinic",
                                devices=['web'])
        self.project1_id = self.project1.save(self.dbm)
        self.project2 = Project(name="Test2", goals="Testing", project_type="Survey", entity_type="Clinic",
                                devices=['web'])
        self.project2_id = self.project2.save(self.dbm)

        self._create_form_model_for_project(self.project1)


    def tearDown(self):
        _delete_db_and_remove_db_manager(self.dbm)

    def test_get_all_projects(self):
        projects = get_all_projects(self.dbm)
        self.assertEquals(len(projects), 2)

    def test_get_one_project(self):
        self.assertEquals(get_project(self.project1_id, self.dbm)['_id'], self.project1_id)

    def test_should_update_project(self):
        self.project1.update(dict(name='Test1', devices=['web', 'sms'], goals="New goals"))
        self.project1.save(self.dbm)
        self.assertEquals(self.project1.name, 'test1')
        self.assertEquals(self.project1.goals, 'New goals')
        self.assertEquals(self.project1.devices, ['web', 'sms'])

    def test_project_name_should_be_unique(self):
        project = Project(name="Test2", goals="Testing", project_type="Survey", entity_type="Clinic", devices=['web'])
        with self.assertRaises(DataObjectAlreadyExists):
            project.save(self.dbm)

    def test_project_name_should_be_case_insensitively_unique(self):
        project = Project(name="tEsT2", goals="Testing", project_type="Survey", entity_type="Clinic", devices=['web'])
        with self.assertRaises(DataObjectAlreadyExists):
            project.save(self.dbm)

    def test_should_check_for_unique_name_while_update_project(self):
        self.project1.update(dict(name='Test2', devices=['web', 'sms'], goals="New goals"))
        with self.assertRaises(DataObjectAlreadyExists):
            self.project1.save(self.dbm)

    def _create_form_model_for_project(self,project):
        ddtype = DataDictType(self.dbm, name='Default String Datadict Type', slug='string_default',
                              primitive_type='string')
        question1 = TextField(name="entity_question", code="ID", label="What is associated entity",
                              language="eng", entity_question_flag=True, ddtype=ddtype)
        question2 = TextField(name="question1_Name", code="Q1", label="What is your name",
                              defaultValue="some default value", language="eng", length=TextConstraint(5, 10),
                              ddtype=ddtype)
        self.form_model = FormModel(self.dbm, name=self.project1.name, form_code="abc", fields=[question1, question2],
                               entity_type=["Clinic"], state=attributes.INACTIVE_STATE)
        qid = self.form_model.save()
        project.qid = qid
        project.save(self.dbm)

    def test_should_update_questionnaire(self):
        self.project1.name = "New Name"
        self.project1.update_questionnaire(self.dbm)
        form_model = self.dbm.get(self.project1.qid, FormModel)
        self.assertEqual("New Name", form_model.name)

    def test_should_activate_form_on_project_activate(self):
        form_model = self.dbm.get(self.project1.qid, FormModel)
        self.assertFalse(form_model.is_active())
        self.project1.activate(self.dbm)
        form_model = self.dbm.get(self.project1.qid, FormModel)
        self.assertTrue(form_model.is_active())
        self.assertEquals(ProjectState.ACTIVE,self.project1.state)

    def test_should_deactivate_form_on_project_deactivate(self):
        project = Project(state=ProjectState.ACTIVE)
        dbm = Mock(spec=DatabaseManager)
        form_model_mock = Mock(spec=FormModel)
        dbm.get.return_value = form_model_mock

        with patch("datawinners.project.models.Project.save") as project_save_mock:
            project.deactivate(dbm)

            form_model_mock.deactivate.assert_called_once_with()
            form_model_mock.save.assert_called_once_with()
            project_save_mock.assert_called_once_with(dbm)

        self.assertEqual( ProjectState.INACTIVE, project.state)

    def test_should_set_form_to_test_on_project_set_to_test(self):
        project = Project(state=ProjectState.ACTIVE)
        dbm = Mock(spec=DatabaseManager)
        form_model_mock = Mock(spec=FormModel)
        dbm.get.return_value = form_model_mock

        with patch("datawinners.project.models.Project.save") as project_save_mock:
            project.to_test_mode(dbm)

            form_model_mock.set_test_mode.assert_called_once_with()
            form_model_mock.save.assert_called_once_with()
            project_save_mock.assert_called_once_with(dbm)

        self.assertEqual( ProjectState.TEST, project.state)