コード例 #1
0
ファイル: test_validations.py プロジェクト: mariot/mangrove
 def test_should_add_length_constraints_if_text_length_constraints(self):
     self.assertEquals(
         "string-length(.) >= 10 and string-length(.) <= 20",
         TextLengthConstraint(min=10, max=20).xform_constraint())
     self.assertEquals("string-length(.) >= 10",
                       TextLengthConstraint(min=10).xform_constraint())
     self.assertEquals("string-length(.) <= 10",
                       TextLengthConstraint(max=10).xform_constraint())
     self.assertEquals("", TextLengthConstraint().xform_constraint())
コード例 #2
0
 def test_phone_number_field(self):
     field = TelephoneNumberField(
         'phone',
         'phone_code',
         'phone',
         constraints=[
             TextLengthConstraint(min=10, max=12),
             RegexConstraint(reg='^[0-9]+$')
         ],
         instruction=
         "Answer must be country code plus telephone number. Example: 261333745269"
     )
     phone_field = FormField().create(field)
     self.assertTrue(isinstance(phone_field, PhoneNumberField))
     self.assertEqual(len(phone_field.validators), 3)
     self.assertEqual(phone_field.widget.attrs['watermark'],
                      'Between 10 -- 12 characters')
     validator_types = []
     for validator in phone_field.validators:
         validator_types.append(type(validator))
     self.assertTrue(MinLengthValidator in validator_types)
     self.assertTrue(MaxLengthValidator in validator_types)
     self.assertTrue(RegexValidator in validator_types)
     self.assertEqual(
         field.instruction,
         "Answer must be country code plus telephone number. Example: 261333745269"
     )
コード例 #3
0
ファイル: test_form_model.py プロジェクト: mariot/mangrove
 def _create_form_model(self):
     self.entity_type = ["HealthFacility", "Clinic"]
     question1 = UniqueIdField('clinic',
                               name="entity_question",
                               code="ID",
                               label="What is associated entity")
     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')])
     self.form_model = FormModelBuilder(
         self.manager, self.entity_type,
         "1").label("Aids form_model").name("aids").add_fields(
             question1, question2, question3, question4).build()
     self.form_model_id = self.form_model.id
コード例 #4
0
def migration_to_add_email_data_for_web_users_in_couch(db_name):
    logger = logging.getLogger(db_name)
    logger.info('Starting Migration')
    mark_as_completed(db_name)
    manager = get_db_manager(db_name)
    try:
        form_model = get_form_model_by_code(manager, REGISTRATION_FORM_CODE)
    except FormModelDoesNotExistsException as f:
        logger.warning(f.message)
        return
    email_field = 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)
    try:
        form_model.add_field(email_field)
        form_model.save()
        logger.info("Migrated registration form")
    except QuestionCodeAlreadyExistsException as e:
        logger.warning('email field is present' + e.message)
    except Exception as e:
        logger.exception(e.message)
コード例 #5
0
 def setUpClass(cls):
     FormModelDocument.registered_functions = []
     cls.db_name = uniq('mangrove-test')
     cls.manager = get_db_manager('http://localhost:5984/', cls.db_name)
     initializer._create_views(cls.manager)
     create_views(cls.manager)
     question1 = UniqueIdField(unique_id_type='clinic',
                               name="entity_question",
                               code="ID",
                               label="What is associated entity")
     question2 = TextField(name="question1_Name",
                           code="Q1",
                           label="What is your name",
                           defaultValue="some default value",
                           constraints=[TextLengthConstraint(5, 10)])
     cls.project1 = Project(dbm=cls.manager,
                            name=project1_name,
                            goals="Testing",
                            devices=['web'],
                            form_code="abc",
                            fields=[question1, question2])
     cls.project1_id = cls.project1.save()
     cls.project2 = Project(dbm=cls.manager,
                            name=project2_name,
                            goals="Testing",
                            devices=['web'],
                            form_code="def",
                            fields=[question1, question2])
     cls.project2_id = cls.project2.save()
コード例 #6
0
    def test_should_convert_field_with_constraints_to_json(self):
        constraints = [
            TextLengthConstraint(min=10, max=12),
            RegexConstraint("^[A-Za-z0-9]+$")
        ]
        field = TextField(name="test",
                          code='MC',
                          label='question',
                          constraints=constraints)
        expected_json = {
            "code": "MC",
            "name": "test",
            "defaultValue": "",
            "instruction": None,
            "label": "question",
            "type": "text",
            'parent_field_code': None,
            "length": {
                'max': 12,
                'min': 10
            },
            "regex": "^[A-Za-z0-9]+$",
            "required": True
        }

        self.assertEqual(expected_json, field_to_json(field))
コード例 #7
0
def add_regex_constraint_to_short_code(form_model, logger):
    form_model.entity_question.set_constraints([
        TextLengthConstraint(max=20)._to_json(),
        ShortCodeRegexConstraint("^[a-zA-Z0-9]+$")._to_json()
    ])
    form_model.save()
    logger.info("migrated form code: %s" % form_model.form_code)
コード例 #8
0
 def __init__(self,
              name,
              code,
              label,
              constraints=None,
              defaultValue=None,
              instruction=None,
              required=False,
              parent_field_code=None):
     if not constraints:
         constraints = [
             TextLengthConstraint(max=20),
             ShortCodeRegexConstraint("^[a-zA-Z0-9]+$")
         ]
     assert isinstance(constraints, list)
     TextField.__init__(self,
                        name=name,
                        code=code,
                        label=label,
                        instruction=instruction,
                        constraints=constraints,
                        defaultValue=defaultValue,
                        required=required,
                        parent_field_code=parent_field_code)
     self._dict['type'] = field_attributes.SHORT_CODE_FIELD
コード例 #9
0
    def test_should_create_text_field_type_for_default_english_language(self):
        expected_json = {
            "defaultValue": "some default value",
            "label": "What is your name",
            "name": "field1_Name",
            "instruction": "Answer is word or phrase",
            "code": "Q1",
            'parent_field_code': None,
            "constraints": [("length", {
                "min": 1,
                "max": 20
            })],
            "type": "text",
            "required": True,
        }
        field = TextField(name="field1_Name",
                          code="Q1",
                          label="What is your name",
                          defaultValue="some default value",
                          constraints=[TextLengthConstraint(1, 20)],
                          instruction="Answer is word or phrase")
        actual_json = field._to_json()
        self.assertEqual(actual_json, expected_json)

        field.set_value("abc")
        self.assertEqual("abc", field.convert_to_unicode())
コード例 #10
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()
コード例 #11
0
 def test_telephone_number_field_should_return_expected_json(self):
     mobile_number_length = TextLengthConstraint(max=15)
     mobile_number_pattern = RegexConstraint(reg='^[0-9]+$')
     field = TelephoneNumberField(
         name="test",
         code='MC',
         label='question',
         constraints=[mobile_number_length, mobile_number_pattern],
         instruction='')
     expected_json = {
         "label": "question",
         "name": "test",
         "code": "MC",
         'parent_field_code': None,
         "type": "telephone_number",
         "instruction": "",
         "constraints": [('length', {
             'max': 15
         }), ('regex', '^[0-9]+$')],
         "defaultValue": '',
         "required": True,
         "appearance": None,
         "constraint_message": None,
         "default": None,
         "hint": None,
         "xform_constraint": None,
         "relevant": None
     }
     self.assertEqual(expected_json, field._to_json())
コード例 #12
0
 def test_should_add_constraint_text_for_text_field_with_max(self):
     constraints = [TextLengthConstraint(max=100)]
     field = TextField(name="What's in a name?",
                       code="nam",
                       label="naam",
                       constraints=constraints)
     preview = helper.get_preview_for_field(field)
     self.assertEqual("Upto 100 characters", preview["constraints"])
コード例 #13
0
 def test_should_throw_exception_if_field_created_with_none_datadict_type(
         self):
     with self.assertRaises(AssertionError):
         TextField(
             name="Name",
             code="Q1",
             label="What is your Name",
             constraints=dict(length=TextLengthConstraint(min=4, max=15)))
コード例 #14
0
 def _get_unique_id_field(self, code):
     field_name = 'unique_id_field'
     return UniqueIdField(unique_id_type='clinic',
                          name=field_name,
                          code=code,
                          label=field_name,
                          instruction=self.instruction,
                          required=True,
                          constraints=[TextLengthConstraint(1, 20)])
コード例 #15
0
ファイル: field_builder.py プロジェクト: kimetrica/mangrove
 def _add_text_length_constraint(self, post_dict):
     max_length_from_post = post_dict.get("max_length")
     min_length_from_post = post_dict.get("min_length")
     max_length = max_length_from_post if not is_empty(max_length_from_post) else None
     min_length = min_length_from_post if not is_empty(min_length_from_post) else None
     constraints = []
     if not (max_length is None and min_length is None):
         constraints.append(TextLengthConstraint(min=min_length, max=max_length))
     return constraints
コード例 #16
0
 def test_should_add_constraint_text_for_text_field_with_max(self):
     type = DataDictType(Mock(DatabaseManager), name="Name type")
     constraints = [TextLengthConstraint(max=100)]
     field = TextField(name="What's in a name?",
                       code="nam",
                       label="naam",
                       ddtype=type,
                       constraints=constraints)
     preview = helper.get_preview_for_field(field)
     self.assertEqual("Upto 100 characters", preview["constraints"])
コード例 #17
0
 def test_successful_text_length_validation(self):
     field = TextField(name="Name",
                       code="Q2",
                       label="What is your Name",
                       constraints=[TextLengthConstraint(min=4, max=15)])
     field1 = TextField(name="Name", code="Q2", label="What is your Name")
     valid_value = field.validate("valid")
     self.assertEqual(valid_value, "valid")
     valid_value = field1.validate("valid")
     self.assertEqual(valid_value, "valid")
コード例 #18
0
    def test_should_create_text_field_with_multiple_constraints(self):
        length_constraint = TextLengthConstraint(min=10, max=12)
        regex_constraint = RegexConstraint("^[A-Za-z0-9]+$")
        constraints = [length_constraint, regex_constraint]
        field = TextField(name="test",
                          code='MC',
                          label='question',
                          constraints=constraints)

        self.assertEqual(constraints, field.constraints)
コード例 #19
0
def _create_entity_id_question(dbm, entity_id_question_code):
    entity_data_dict_type = get_or_create_data_dict(dbm=dbm, name="eid", slug="entity_id", primitive_type="string",
        description="Entity ID")
    name = ugettext("Which subject are you reporting on?")
    entity_id_question = TextField(name=name, code=entity_id_question_code,
        label=name,
        entity_question_flag=True, ddtype=entity_data_dict_type,
        constraints=[TextLengthConstraint(min=1, max=20)],
        instruction=(ugettext('Answer must be %d characters maximum') % 20))
    return entity_id_question
コード例 #20
0
    def test_should_convert_text_in_epsilon_format_to_expanded_text(self):
        mobile_number_length = TextLengthConstraint(max=15)
        mobile_number_pattern = RegexConstraint(reg='^[0-9]+$')
        field = TelephoneNumberField(
            name="test",
            code='MC',
            label='question',
            constraints=[mobile_number_length, mobile_number_pattern],
            instruction='')

        self.assertEqual(u'266123321435', field._clean(u'2.66123321435e+11'))
コード例 #21
0
 def _get_telephone_number_field(self):
     form_model = self._get_form_model()
     phone_number_field = TelephoneNumberField(
         name=self.field_name,
         code='m',
         label=self.field_name,
         ddtype=Mock(spec=DataDictType),
         constraints=[
             TextLengthConstraint(max=15),
             RegexConstraint(reg='^[0-9]+$')
         ])
     return phone_number_field
コード例 #22
0
 def test_should_return_error_for_text_length_validation_for_max_value(
         self):
     with self.assertRaises(AnswerTooLongException) as e:
         field = TextField(name="Age",
                           code="Q2",
                           label="What is your age",
                           constraints=[TextLengthConstraint(min=1, max=4)])
         valid_value = field.validate("long_answer")
         self.assertFalse(valid_value)
     self.assertEqual(
         e.exception.message,
         "Answer long_answer for question Q2 is longer than allowed.")
コード例 #23
0
 def _get_text_field(self, is_required, entity_question_flag, code=None):
     code = self.text_field_code if code is None else code
     field_name = self.field_name if not entity_question_flag else self.short_code_question_code
     text_field = TextField(name=field_name,
                            code=code,
                            label=field_name,
                            ddtype=Mock(spec=DataDictType),
                            instruction=self.instruction,
                            required=is_required,
                            constraints=[TextLengthConstraint(1, 20)],
                            entity_question_flag=entity_question_flag)
     return text_field
コード例 #24
0
 def test_should_raise_regex_mismatch_exception_if_invalid_phone_number(
         self):
     mobile_number_length = TextLengthConstraint(max=15)
     mobile_number_pattern = RegexConstraint(reg='^[0-9]+$')
     field = TelephoneNumberField(
         name="test",
         code='MC',
         label='question',
         constraints=[mobile_number_length, mobile_number_pattern],
         instruction='')
     with self.assertRaises(RegexMismatchException):
         field.validate(u'020321dsa')
コード例 #25
0
    def test_telephone_number_should_clean_value_to_remove_only_hyphen_from_the_given_value(
            self):
        mobile_number_length = TextLengthConstraint(max=15)
        mobile_number_pattern = RegexConstraint(reg='^[0-9]+$')
        field = TelephoneNumberField(
            name="test",
            code='MC',
            label='question',
            constraints=[mobile_number_length, mobile_number_pattern],
            instruction='')

        self.assertEqual('1234321122', field._clean('123-4321122'))
        self.assertEqual('123dsasa4321122', field._clean('123dsasa4321122'))
コード例 #26
0
    def test_telephone_number_should_clean_before_validate(self):
        mobile_number_length = TextLengthConstraint(max=15)
        mobile_number_pattern = RegexConstraint(reg='^[0-9]+$')
        field = TelephoneNumberField(
            name="test",
            code='MC',
            label='question',
            constraints=[mobile_number_length, mobile_number_pattern],
            instruction='')

        self.assertEqual(u'266123321435', field.validate(u'2.66123321435e+11'))
        self.assertEqual(u'266123321435', field.validate(u'266-123321435'))
        self.assertEqual(u'266123321435', field.validate(u'266123321435.0'))
コード例 #27
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)
コード例 #28
0
ファイル: test_model.py プロジェクト: mrudtf/datawinners
 def _create_form_model_for_project(self, project):
     ddtype = DataDictType(self.manager, name='Default String Datadict Type', slug='string_default',
         primitive_type='string')
     question1 = TextField(name="entity_question", code="ID", label="What is associated entity", entity_question_flag=True, ddtype=ddtype)
     question2 = TextField(name="question1_Name", code="Q1", label="What is your name",
         defaultValue="some default value",
         constraints=[TextLengthConstraint(5, 10)],
         ddtype=ddtype)
     self.form_model = FormModel(self.manager, 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.manager)
コード例 #29
0
    def test_should_validate_text_data_based_on_list_of_constraints(self):
        length_constraint = TextLengthConstraint(min=10, max=12)
        regex_constraint = RegexConstraint("^[A-Za-z0-9]+$")
        constraints = [length_constraint, regex_constraint]
        field = TextField(name="test",
                          code='MC',
                          label='question',
                          constraints=constraints)

        self.assertEqual('validatable', field.validate('validatable'))
        self.assertRaises(RegexMismatchException, field.validate,
                          '!alidatabl!')
        self.assertRaises(AnswerTooShortException, field.validate, 'val')
        self.assertRaises(AnswerTooLongException, field.validate,
                          'val11111111111111')
コード例 #30
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')