Beispiel #1
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)
class TestEntityShouldExistValidator(TestCase):
    def setUp(self):
        self.dbm = Mock(spec=DatabaseManager)
        self.get_by_short_code_patcher = patch(
            'mangrove.contrib.delete_validators.get_by_short_code')
        self.get_by_short_code_mock = self.get_by_short_code_patcher.start()

        self.validator = EntityShouldExistValidator()
        self.field1 = HierarchyField('a', 'entity_type', 'a')
        self.field2 = ShortCodeField('b', 'entity_id', 'b')
        self.field1.set_value('clinic')
        self.field2.set_value('cli01')
        self.fields = [self.field1, self.field2]

        self.entity_type = 'clinic'
        self.entity_id = 'cli01'
        self.values = {
            'entity_type': self.entity_type,
            'entity_id': self.entity_id
        }

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

    def test_should_give_error_if_entity_does_not_exist(self):
        self.get_by_short_code_mock.side_effect = DataObjectNotFound(
            'Entity', "Unique Identification Number (ID)", self.entity_id)
        exception = DataObjectNotFound("Entity",
                                       "Unique Identification Number (ID)",
                                       self.entity_id)
        errors = OrderedDict()
        errors['entity_type'] = exception.message
        errors['entity_id'] = exception.message
        self.assertEqual(
            errors, self.validator.validate(self.values, self.fields,
                                            self.dbm))
        self.get_by_short_code_mock.assert_called_once_with(
            self.dbm, self.entity_id, [self.entity_type])

    def test_should_not_give_error_if_entity_exist(self):
        self.assertEqual(
            OrderedDict(),
            self.validator.validate(self.values, self.fields, self.dbm))
        self.get_by_short_code_mock.assert_called_once_with(
            self.dbm, self.entity_id, [self.entity_type])

    def test_should_create_entity_should_exist_validator_from_json(self):
        validator_json = {'cls': ValidatorTypes.ENTITY_SHOULD_EXIST}
        self.assertTrue(
            isinstance(validator_factory(validator_json),
                       EntityShouldExistValidator))

    def test_entity_should_exist_validators_should_be_serializable(self):
        expected_json = {'cls': ValidatorTypes.ENTITY_SHOULD_EXIST}
        self.assertEqual(expected_json, self.validator.to_json())
    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)
        ]
Beispiel #4
0
 def test_should_add_entity_field_with_default_constraints(self):
     expected_json = {
         "defaultValue":
         "",
         "label":
         "What is your name",
         "name":
         "field1_Name",
         "code":
         "Q1",
         "type":
         "short_code",
         'parent_field_code':
         None,
         "constraints": [("length", {
             "max": 20
         }), ("short_code", "^[a-zA-Z0-9]+$")],
         "required":
         False,
         "instruction":
         "test_instruction"
     }
     field = ShortCodeField(name="field1_Name",
                            code="Q1",
                            label="What is your name",
                            instruction="test_instruction")
     actual_json = field._to_json()
     self.assertDictEqual(actual_json, expected_json)
 def test_should_give_entity_specific_registration_form_submission(self):
     mocked_form_model = Mock(spec=EntityFormModel)
     mocked_form_model.is_entity_registration_form.return_value = True
     mocked_form_model.is_global_registration_form.return_value = False
     mocked_form_model.entity_type = "clinic"
     mocked_form_model.entity_questions = [ShortCodeField('name','code','label')]
     form_submission = FormSubmissionFactory().get_form_submission(mocked_form_model, OrderedDict(), None)
     self.assertEqual(type(form_submission), EntityRegistrationFormSubmission)
Beispiel #6
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')
Beispiel #7
0
 def _create_short_code_field(self, post_dict, code):
     return ShortCodeField(name=self._get_name(post_dict, code), code=code,
                           label=post_dict["title"],
                           instruction=post_dict.get("instruction"),
                           parent_field_code=post_dict.get('parent_field_code'),
                           hint=post_dict.get('hint'), constraint_message=post_dict.get('constraint_message'),
                           appearance=post_dict.get('appearance'),
                           default=post_dict.get('default'),
                           xform_constraint=post_dict.get('xform_constraint'),
                           relevant=post_dict.get('relevant'))
    def setUp(self):
        self.dbm = Mock(spec=DatabaseManager)
        self.get_by_short_code_patcher = patch(
            'mangrove.contrib.delete_validators.get_by_short_code')
        self.get_by_short_code_mock = self.get_by_short_code_patcher.start()

        self.validator = EntityShouldExistValidator()
        self.field1 = HierarchyField('a', 'entity_type', 'a')
        self.field2 = ShortCodeField('b', 'entity_id', 'b')
        self.field1.set_value('clinic')
        self.field2.set_value('cli01')
        self.fields = [self.field1, self.field2]

        self.entity_type = 'clinic'
        self.entity_id = 'cli01'
        self.values = {
            'entity_type': self.entity_type,
            'entity_id': self.entity_id
        }
Beispiel #9
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
Beispiel #10
0
    def test_entity_field(self):
        field = ShortCodeField(
            "name",
            "name",
            "what is ur name",
            constraints=[TextLengthConstraint(min=5, max=100)])
        entity_field = FormField().create(field)

        self.assertEquals(2, len(entity_field.validators))
        self.assertEquals(entity_field.widget.attrs["watermark"],
                          "Between 5 -- 100 characters")
        self.assertEquals(entity_field.widget.attrs['class'], 'subject_field')
        self.assertEqual(entity_field.min_length, 5)
        self.assertEqual(entity_field.max_length, 100)
Beispiel #11
0
 def test_should_generate_default_code_if_short_code_is_empty(self):
     registration_work_flow = RegistrationWorkFlow(self.dbm,
                                                   self.form_model_mock,
                                                   DummyLocationTree())
     self.form_model_mock.get_short_code = Mock(return_value=None)
     self.form_model_mock.entity_type = ['clinic']
     self.form_model_mock.entity_questions = [
         ShortCodeField(name="entity question", code="s", label="bar")
     ]
     values = registration_work_flow.process({'t': 'clinic', 'l': 'pune'})
     self.assertEqual(
         {
             's': 'cli1',
             't': 'clinic',
             'l': ['pune', 'mh', 'india']
         }, values)
 def setUp(self):
     self.validator = MobileNumberValidationsForReporterRegistrationValidator(
     )
     self.field1 = ShortCodeField('t', 't', 't')
     self.field2 = TextField('m', 'm', 'm')
     self.fields = [self.field1, self.field2]
     self.dbm = Mock(spec=DatabaseManager)
     self.dbm.view = Mock()
     self.dbm.view.datasender_by_mobile = Mock(return_value=[{
         'doc': {
             "data": {
                 "mobile_number": {
                     "value": "123"
                 }
             },
             "short_code": "abc"
         }
     }])
Beispiel #13
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))
Beispiel #14
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
Beispiel #15
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
Beispiel #16
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())
Beispiel #17
0
def add_unique_id_and_short_code_field(dbm, logger):
    for row in dbm.database.query(list_all_form_models, include_docs=True):
        try:
            document_data = row.doc
            json_data = document_data.get('json_fields')
            validator = None
            short_code_field = None
            short_code_dict = None
            index = 0
            if document_data.get('is_registration_model') or document_data.get("form_code") == "delete":
                for index, f in enumerate(json_data):
                    if f.get('name') == SHORT_CODE_FIELD:
                        short_code_field = ShortCodeField(f.get('name'), f.get('code'), f.get('label'),
                                                          defaultValue=f.get('defaultValue'),
                                                          instruction=f.get('instruction'), required=f.get('required'))
                        short_code_dict = f
                        break
            else:
                for index, f in enumerate(json_data):
                    if f.get('entity_question_flag'):
                        start_key = [document_data.get('form_code')]
                        end_key = [document_data.get('form_code'), {}]
                        survey_response_rows = dbm.database.iterview("surveyresponse/surveyresponse", 1000, reduce=False, include_docs=False, startkey=start_key, endkey=end_key)

                        if document_data.get('entity_type') != ['reporter']:
                            short_code_field = UniqueIdField(document_data.get('entity_type')[0], f.get('name'),
                                                             f.get('code'),
                                                             f.get('label'), defaultValue=f.get('defaultValue'),
                                                             instruction=f.get('instruction'),
                                                             required=f.get('required'))
                            validator = UniqueIdExistsValidator
                            #Remove test field from survey responses
                            for row in survey_response_rows:
                                if row.get('value').get('test'):
                                    row.get('value').pop('test')
                        else:
                            for row in survey_response_rows:
                                try:
                                    row.get('value').get('values').pop(f.get('code'))
                                    if row.get('value').get('test'):
                                        row.get('value').pop('test')
                                    survey_response = SurveyResponseDocument._wrap_row(row)
                                    dbm._save_document(survey_response)
                                except Exception as e:
                                    logger.error("Survey response update failed for database %s for id %s" %(dbm.database_name,row.get('id')))
                                    logger.error(e)
                        short_code_dict = f
                        break
                    #Remove event_time flag from reporting date question
                    elif f.get('type') == 'date' and 'event_time_field_flag' in f:
                        f.pop('event_time_field_flag')
                #Remove entity type from questionnaire form models.
                if document_data.get('entity_type'):
                    document_data.pop('entity_type')
            if short_code_dict:
                json_data.remove(short_code_dict)
                form_model = FormModel.new_from_doc(dbm, (FormModelDocument.wrap(document_data)))
                if short_code_field:
                    form_model._form_fields.insert(index, short_code_field)
                if validator:
                    form_model.add_validator(validator)
                _save_form_model_doc(dbm, form_model)
        except Exception as e:
            logger.error('Failed form model for database : %s, doc with id: %s', dbm.database_name,
                          row.id)
            logger.error(e)
Beispiel #18
0
    def _construct_global_registration_form(self):
        mocked_form_model = Mock()
        mocked_form_model.entity_type = GLOBAL_REGISTRATION_FORM_ENTITY_TYPE
        mocked_form_model.entity_questions = [ShortCodeField('name','s','label')]

        return mocked_form_model
Beispiel #19
0
 def _create_short_code_field(self, post_dict, code):
     return ShortCodeField(name=self._get_name(post_dict), code=code,
                           label=post_dict["title"],
                           instruction=post_dict.get("instruction"),
                           parent_field_code=post_dict.get('parent_field_code'))
Beispiel #20
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