예제 #1
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)
        ]
예제 #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 = EntityFormModel(dbm=dbm,
                                                 entity_type=entity_type)
                    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 test_should_get_entity_form_model(self):
     entity_form_model = EntityFormModel(
         self.manager,
         name='entity_form_model',
         label='Entity Form Model',
         form_code='entity_form_code',
         fields=[TextField('name', 'code', 'label')],
         language="en",
         is_registration_model=True,
         enforce_unique_labels=True,
         entity_type=['clinic'])
     id = entity_form_model.save()
     saved_entity = EntityFormModel.get(self.manager, id)
     self.assertEquals(saved_entity.entity_type, ['clinic'])
예제 #4
0
    def test_should_batch_get_form_models(self):
        fields = [ShortCodeField('name', 'eid', 'label')]
        form = EntityFormModel(
            self.manager,
            'test_form',
            'label',
            'form_code1',
            fields=fields,
            entity_type=['Clinic'],
            validators=[
                MandatoryValidator(),
                MobileNumberValidationsForReporterRegistrationValidator()
            ])
        form.save()

        fields = [ShortCodeField('name', 'eid', 'label')]
        form = EntityFormModel(
            self.manager,
            'test_form',
            'label',
            'form_code2',
            fields=fields,
            entity_type=['Clinic'],
            validators=[
                MandatoryValidator(),
                MobileNumberValidationsForReporterRegistrationValidator()
            ])
        form.save()

        forms = list_form_models_by_code(self.manager,
                                         ['form_code1', 'form_code2'])

        self.assertEqual(2, len(forms))
        self.assertEqual('form_code1', forms[0].form_code)
        self.assertEqual('form_code2', forms[1].form_code)
예제 #5
0
 def test_should_call_subject_mapping_update_for_registration_form_model(
         self):
     dbm = Mock(spec=DatabaseManager)
     form_model_document = Mock(spec=EntityFormModelDocument)
     form_model_document.form_code = "clinic"
     with patch(
             "mangrove.form_model.form_model.EntityFormModel.new_from_doc"
     ) as new_from_doc:
         with patch("datawinners.search.mapping.create_subject_mapping"
                    ) as create_subject_mapping:
             entity_form_model = EntityFormModel(dbm)
             entity_form_model._doc = form_model_document
             new_from_doc.return_value = entity_form_model
             entity_form_model_change_handler(form_model_document, dbm)
             assert create_subject_mapping.called
예제 #6
0
class FilePlayerTest(TestCase):

    fixtures = ['test_data.json']

    def setUp(self):
        organization = Organization.objects.get(pk=DEFAULT_TEST_ORG_ID)
        self.manager = utils.get_database_manager_for_org(organization)

    @attr('functional_test')
    def test_should_import_xls_file(self):
        self._init_xls_data()
        self._build_fixtures()

        with open(self.file_name) as f:
            response = FilePlayer(self.manager, self.parser,
                                  Channel.XLS).accept(file_contents=f.read())

        self.assertEqual([True, True, False, True, True],
                         [item.success for item in response])
        self._cleanup_xls_data()

    def _init_xls_data(self):
        self.parser = XlsParser()
        self.file_name = 'test.xls'
        wb = xlwt.Workbook()
        ws = wb.add_sheet('test')
        for row_number, row in enumerate(UPLOAD_DATA.split('\n')):
            for col_number, val in enumerate(row.split(',')):
                ws.write(row_number, col_number, val)
        wb.save(self.file_name)

    def _cleanup_xls_data(self):
        os.remove(self.file_name)

    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',
                                              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)
        ]
예제 #7
0
    def test_regex_field_created_for_entity_question(self):
        entity_field = ShortCodeField("reporting on", "rep_on", "rep")
        form_model = EntityFormModel(self.dbm, 'some form', 'some', 'form_code_1', fields=[entity_field],
                               entity_type=['Clinic'])

        form = SubjectRegistrationForm(form_model)
        self.assertEquals(type(form.fields['rep_on']), RegexField)
        self.assertEquals(form.short_code_question_code, 'rep_on')
예제 #8
0
def entity_form_model_change_handler(entity_form_model_doc,
                                     dbm,
                                     old_form_model=None):
    entity_form_model = EntityFormModel.new_from_doc(dbm,
                                                     entity_form_model_doc)
    if entity_form_model.form_code == REGISTRATION_FORM_CODE:
        create_ds_mapping(dbm, entity_form_model)
    else:
        create_subject_mapping(dbm, entity_form_model)
예제 #9
0
    def test_append_country_to_location(self):
        location_field = TextField(LOCATION_TYPE_FIELD_NAME, "location_code", "some label")
        form_model = EntityFormModel(self.dbm, 'some form', 'some', 'form_code_1', fields=[location_field],
                               entity_type=['Clinic'])

        form = SubjectRegistrationForm(form_model,
                                       data={'location_code': "Bangalore", 'form_code': 'form_code_1', 't': ['Clinic']},
                                       country='India')
        form.is_valid()
        self.assertEquals(form.cleaned_data['location_code'], 'Bangalore,India')
예제 #10
0
def _construct_global_deletion_form(manager):
    question1 = HierarchyField(name=ENTITY_TYPE_FIELD_NAME, code=ENTITY_TYPE_FIELD_CODE,
        label="What is the entity type" , instruction="Enter a type for the entity")

    question2 = ShortCodeField(name=SHORT_CODE_FIELD, code=SHORT_CODE, label="What is the entity's Unique ID Number",
        defaultValue="some default value" ,
        instruction="Enter the id of the entity you want to delete", constraints=[])

    form_model = EntityFormModel(manager, name=ENTITY_DELETION_FORM_CODE, form_code=ENTITY_DELETION_FORM_CODE, fields=[
        question1, question2], entity_type=["deletion"],
        validators=[MandatoryValidator(), EntityShouldExistValidator()])
    return form_model
예제 #11
0
 def test_should_save_form_model_with_validators(self):
     fields = [ShortCodeField('name', 'eid', 'label')]
     form = EntityFormModel(
         self.manager,
         'test_form',
         'label',
         'foo',
         fields=fields,
         entity_type=['Clinic'],
         validators=[
             MandatoryValidator(),
             MobileNumberValidationsForReporterRegistrationValidator()
         ])
     form.save()
     form = get_form_model_by_code(self.manager, 'foo')
     self.assertEqual(2, len(form.validators))
     self.assertTrue(isinstance(form.validators[0], MandatoryValidator))
     self.assertTrue(
         isinstance(
             form.validators[1],
             MobileNumberValidationsForReporterRegistrationValidator))
예제 #12
0
def get_projects_by_unique_id_type(dbm, unique_id_type):
    projects = []
    for row in dbm.load_all_rows_in_view('projects_by_subject_type',
                                         key=unique_id_type[0],
                                         include_docs=True):
        if row['doc']['is_registration_model']:
            questionnaire = EntityFormModel.new_from_doc(
                dbm, EntityFormModelDocument.wrap(row['doc']))
        else:
            questionnaire = Project.new_from_doc(
                dbm, ProjectDocument.wrap(row['doc']))
        projects.append(questionnaire)
    return projects
예제 #13
0
    def test_create_entity_list_for_subjects(self):
        with patch ("datawinners.project.questionnaire_fields.EntityField._subject_choice_fields") as subject_choice_fields:

            choices = ChoiceField(choices=[('sub1', 'one_subject'), ('sub2', 'another_subject')])
            subject_choice_fields.return_value = choices
            project = EntityFormModel(dbm=Mock(spec=DatabaseManager), entity_type=["some_subject"])

            subject_field = EntityField(Mock(spec=DatabaseManager), project)
            question_field = Mock(spec=TextField)
            question_code = PropertyMock(return_value="eid")
            type(question_field).code = question_code

            result_field = subject_field.create(question_field, 'some_subject')

            self.assertEquals(result_field.get('eid'), choices)
예제 #14
0
    def test_subject_index_dict(self):
        dbm = Mock(spec=DatabaseManager)
        entity_type = ['entity_type']

        mock_entity = Entity(dbm=dbm, entity_type=entity_type)
        mock_entity.add_data(data=[('name1', 'ans1'), ('name2', 'ans2')])

        with patch.object(Entity, 'get') as get:
            get.return_value = mock_entity
            form_model = EntityFormModel(dbm=dbm, entity_type=entity_type)
            form_model.add_field(TextField('name1', 'code1', 'label1'))
            form_model.add_field(TextField('name2', 'code2', 'label2'))
            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)
예제 #15
0
def _create_registration_form(manager, entity_name, no_of_questions):
    entity_type = [entity_name]
    code_generator = question_code_generator()
    form_code = random_string()
    questions = []
    for a in range(no_of_questions - 2):
        code = code_generator.next()
        question = TextField(name=code,
                             code=code,
                             label=random_string(15),
                             defaultValue="some default value",
                             instruction="Enter a %(entity_type)s first name" %
                             {'entity_type': entity_name})
        questions.append(question)

    question = TextField(name=NAME_FIELD,
                         code=code_generator.next(),
                         label=random_string(15),
                         defaultValue="some default value",
                         instruction="Enter a %(entity_type)s first name" %
                         {'entity_type': entity_name})
    questions.append(question)

    question = ShortCodeField(
        name=SHORT_CODE_FIELD,
        code=code_generator.next(),
        label="What is the %(entity_type)s's Unique ID Number?" %
        {'entity_type': entity_name},
        defaultValue="some default value",
        instruction=unicode("Enter an id, or allow us to generate it"),
        required=False)
    questions.append(question)

    form_model = EntityFormModel(manager,
                                 name=entity_name,
                                 form_code=form_code,
                                 fields=questions,
                                 is_registration_model=True,
                                 entity_type=entity_type)
    return form_model
예제 #16
0
def construct_global_registration_form(manager):
    question1 = HierarchyField(name=ENTITY_TYPE_FIELD_NAME,
                               code=ENTITY_TYPE_FIELD_CODE,
                               label="What is associated subject type?",
                               instruction="Enter a type for the subject")

    question2 = TextField(name=NAME_FIELD,
                          code=NAME_FIELD_CODE,
                          label="What is the subject's name?",
                          defaultValue="some default value",
                          instruction="Enter a subject name",
                          constraints=[TextLengthConstraint(max=80)],
                          required=False)
    question3 = ShortCodeField(
        name=SHORT_CODE_FIELD,
        code=SHORT_CODE,
        label="What is the subject's Unique ID Number",
        defaultValue="some default value",
        instruction="Enter a id, or allow us to generate it",
        constraints=[
            TextLengthConstraint(max=12),
            ShortCodeRegexConstraint(reg='^[a-zA-Z0-9]+$')
        ],
        required=False)
    question4 = HierarchyField(
        name=LOCATION_TYPE_FIELD_NAME,
        code=LOCATION_TYPE_FIELD_CODE,
        label="What is the subject's location?",
        instruction="Enter a region, district, or commune",
        required=False)
    question5 = GeoCodeField(name=GEO_CODE_FIELD_NAME,
                             code=GEO_CODE,
                             label="What is the subject's GPS co-ordinates?",
                             instruction="Enter lat and long. Eg 20.6, 47.3",
                             required=False)
    question6 = TelephoneNumberField(
        name=MOBILE_NUMBER_FIELD,
        code=MOBILE_NUMBER_FIELD_CODE,
        label="What is the mobile number associated with the subject?",
        defaultValue="some default value",
        instruction="Enter the subject's number",
        constraints=(_create_constraints_for_mobile_number()),
        required=True)
    question7 = TextField(name=EMAIL_FIELD,
                          code=EMAIL_FIELD,
                          label="What is the subject's email",
                          defaultValue="",
                          instruction="Enter email id",
                          constraints=[TextLengthConstraint(max=50)],
                          required=False)
    question8 = BooleanField(name=IS_DATASENDER_FIELD_CODE,
                             code=IS_DATASENDER_FIELD_CODE,
                             label="Am I a data sender",
                             defaultValue=True,
                             required=False)
    form_model = EntityFormModel(
        manager,
        name=GLOBAL_REGISTRATION_FORM_CODE,
        form_code=REGISTRATION_FORM_CODE,
        fields=[
            question1, question2, question3, question4, question5, question6,
            question7, question8
        ],
        is_registration_model=True,
        entity_type=["registration"],
        validators=[
            MandatoryValidator(),
            MobileNumberValidationsForReporterRegistrationValidator()
        ])
    return form_model
예제 #17
0
def _create_registration_form(manager,
                              entity_name=None,
                              form_code=None,
                              entity_type=None):
    code_generator = question_code_generator()

    question1 = TextField(
        name=FIRSTNAME_FIELD,
        code=code_generator.next(),
        label=_("What is the %(entity_type)s's first name?") %
        {'entity_type': entity_name},
        defaultValue="some default value",
        instruction=_("Enter a %(entity_type)s first name") %
        {'entity_type': entity_name})

    question2 = TextField(name=NAME_FIELD,
                          code=code_generator.next(),
                          label=_("What is the %(entity_type)s's last name?") %
                          {'entity_type': entity_name},
                          defaultValue="some default value",
                          instruction=_("Enter a %(entity_type)s last name") %
                          {'entity_type': entity_name})
    question3 = HierarchyField(
        name=LOCATION_TYPE_FIELD_NAME,
        code=code_generator.next(),
        label=_("What is the %(entity_type)s's location?") %
        {'entity_type': entity_name},
        instruction=unicode(_("Enter a region, district, or commune")))
    question4 = GeoCodeField(
        name=GEO_CODE_FIELD_NAME,
        code=code_generator.next(),
        label=_("What is the %(entity_type)s's GPS co-ordinates?") %
        {'entity_type': entity_name},
        instruction=unicode(
            _("Answer must be GPS coordinates in the following format (latitude,longitude). Example: -18.1324,27.6547"
              )))
    question5 = TelephoneNumberField(
        name=MOBILE_NUMBER_FIELD,
        code=code_generator.next(),
        label=_("What is the %(entity_type)s's mobile telephone number?") %
        {'entity_type': entity_name},
        defaultValue="some default value",
        instruction=
        _("Enter the (%(entity_type)s)'s number with the country code and telephone number. Example: 261333745269"
          ) % {'entity_type': entity_name},
        constraints=(_create_constraints_for_mobile_number()))
    question6 = ShortCodeField(
        name=SHORT_CODE_FIELD,
        code=code_generator.next(),
        label=_("What is the %(entity_type)s's Unique ID Number?") %
        {'entity_type': entity_name},
        defaultValue="some default value",
        instruction=unicode(_("Enter an id, or allow us to generate it")),
        required=False)
    questions = [
        question1, question2, question3, question4, question5, question6
    ]

    form_model = EntityFormModel(manager,
                                 name=entity_name,
                                 form_code=form_code,
                                 fields=questions,
                                 is_registration_model=True,
                                 entity_type=entity_type)
    return form_model
예제 #18
0
    def setUpClass(cls):
        cls.dbm = create_db(uniq('mangrove-test'))
        initializer.initial_data_setup(cls.dbm)
        cls.entity_type = ["healthfacility", "clinic"]
        safe_define_type(cls.dbm, cls.entity_type)

        cls.entity_short_code = "cli" + str(int(random.random() * 10000))
        cls.entity = create_entity(
            cls.dbm,
            entity_type=cls.entity_type,
            location=["India", "Pune"],
            aggregation_paths=None,
            short_code=cls.entity_short_code,
        )
        cls.entity.save()
        cls.reporter_id = "rep" + str(int(random.random() * 10000))
        cls.reporter = create_contact(cls.dbm,
                                      location=["India", "Pune"],
                                      aggregation_paths=None,
                                      short_code=cls.reporter_id)
        cls.reporter.save()

        cls.phone_number = str(int(random.random() * 10000000))
        cls.reporter.add_data(data=[(MOBILE_NUMBER_FIELD, cls.phone_number),
                                    (NAME_FIELD, "Test_reporter")],
                              submission=dict(submission_id="2"))

        question1 = ShortCodeField(
            name="entity_question",
            code="EID",
            label="What is associated entity",
            constraints=[TextLengthConstraint(min=1, max=20)])
        question2 = TextField(name="Name",
                              code="NAME",
                              label="Clinic Name",
                              defaultValue="some default value",
                              constraints=[TextLengthConstraint(4, 15)],
                              required=False)
        question3 = IntegerField(
            name="Arv stock",
            code="ARV",
            label="ARV Stock",
            constraints=[NumericRangeConstraint(min=15, max=120)],
            required=False)
        question4 = SelectField(name="Color",
                                code="COL",
                                label="Color",
                                options=[("RED", 'a'), ("YELLOW", 'a')],
                                required=False)

        try:
            cls.form_model = get_form_model_by_code(cls.dbm, "clinic")
        except FormModelDoesNotExistsException:
            cls.form_model = EntityFormModel(
                cls.dbm,
                entity_type=cls.entity_type,
                name="aids",
                label="Aids form_model",
                form_code="clinic",
                fields=[question1, question2, question3],
                is_registration_model=True)
            cls.form_model.add_field(question4)
            cls.form_model.save()
        cls.sms_player = SMSPlayer(cls.dbm, LocationTree())
        cls.sms_ordered_message_player = SMSPlayer(cls.dbm, LocationTree())
예제 #19
0
    def _create_project(self):
        registration_form = construct_global_registration_form(self.manager)
        registration_form.save()

        self.check_uniqueness_patch = patch.object(
            Project, '_check_if_project_name_unique')
        self.check_uniqueness_patch.start()
        clinic_form_model = EntityFormModel(
            self.manager,
            name='clinic',
            label='Entity Form Model',
            form_code='clin',
            fields=[TextField('name', 'code', 'label')],
            language="en",
            is_registration_model=True,
            enforce_unique_labels=True,
            entity_type=['clinic'])
        clinic_form_model.save()

        hf_form_model = EntityFormModel(self.manager,
                                        name='health',
                                        label='Entity Form Model',
                                        form_code='hf1',
                                        fields=[
                                            TextField('name', 'code', 'label'),
                                            TextField('location', 'loc',
                                                      'Where is it?')
                                        ],
                                        language="en",
                                        is_registration_model=True,
                                        enforce_unique_labels=True,
                                        entity_type=['healthfacility'])
        hf_form_model.save()

        entity_type = ["HealthFacility", "Clinic"]
        question1 = UniqueIdField('clinic',
                                  name="entity_question",
                                  code="ID",
                                  label="What is associated Clinic")
        question2 = TextField(
            name="question1_Name",
            code="Q1",
            label="What is your name",
            defaultValue="some default value",
            constraints=[TextLengthConstraint(5, 10),
                         RegexConstraint("\w+")])
        question3 = IntegerField(
            name="Father's age",
            code="Q2",
            label="What is your Father's Age",
            constraints=[NumericRangeConstraint(min=15, max=120)])
        question4 = SelectField(name="Color",
                                code="Q3",
                                label="What is your favourite color",
                                options=[("RED", 'a'), ("YELLOW", 'b')])
        question5 = UniqueIdField('healthfacility',
                                  name="health facility",
                                  code="hf",
                                  label="For which HF is it?")
        fields = [question1, question2, question3, question4, question5]
        project = Project(self.manager,
                          name='test project',
                          form_code='test01',
                          fields=fields)

        project.save()
        return project
예제 #20
0
 def test_should_set_entity_type_in_doc(self):
     entity_form_model = EntityFormModel(self.manager)
     entity_form_model._doc = FormModelDocument()
     entity_form_model.entity_type = ["WaterPoint", "Dam"]
     self.assertEqual(entity_form_model.entity_type, ["WaterPoint", "Dam"])