Esempio n. 1
0
 def test_should_invalidate_special_characters_sent_for_choice(self):
     with self.assertRaises(AnswerNotInListException):
         constraint = ChoiceConstraint(
             single_select_constraint=False,
             list_of_valid_choices=["village", "urban", "city", "country"],
             code="Q1")
         constraint.validate("a!b")
Esempio n. 2
0
 def test_should_not_validate_wrong_choice(self):
     with self.assertRaises(AnswerNotInListException):
         constraint = ChoiceConstraint(
             single_select_constraint=True,
             list_of_valid_choices=["village", "urban"],
             code="Q1")
         constraint.validate("c")
Esempio n. 3
0
 def test_should_not_validate_no_values_sent_for_choice(self):
     with self.assertRaises(AnswerHasNoValuesException):
         constraint = ChoiceConstraint(
             single_select_constraint=True,
             list_of_valid_choices=["village", "urban"],
             code="Q1")
         constraint.validate("")
Esempio n. 4
0
 def test_should_validate_multiple_choice(self):
     constraint = ChoiceConstraint(
         single_select_constraint=False,
         list_of_valid_choices=["village", "urban"],
         code="Q1")
     v_data = constraint.validate("ab")
     self.assertEquals(v_data, ["village", "urban"])
Esempio n. 5
0
 def test_should_invalidate_answer_with_2_numbers(self):
     valid_choices = [
         "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
         "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
         "1a", "1b", "1c"
     ]
     with self.assertRaises(AnswerNotInListException):
         constraint = ChoiceConstraint(single_select_constraint=False,
                                       list_of_valid_choices=valid_choices,
                                       code="Q1")
         constraint.validate("abc1b341c")
Esempio n. 6
0
 def test_should_not_validate_wrong_choice(self):
     with self.assertRaises(AnswerNotInListException):
         valid_choices = [
             "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l",
             "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x",
             "y", "z", "1a", "1b", "1c"
         ]
         constraint = ChoiceConstraint(single_select_constraint=True,
                                       list_of_valid_choices=valid_choices,
                                       code="Q1")
         constraint.validate("1d")
Esempio n. 7
0
 def test_should_not_validate_answer_with_one_letter_followed_by_one_number_on_a_single_choice(
         self):
     valid_choices = [
         "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
         "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",
         "1a", "1b", "1c"
     ]
     with self.assertRaises(AnswerNotInListException):
         constraint = ChoiceConstraint(single_select_constraint=True,
                                       list_of_valid_choices=valid_choices,
                                       code="Q1")
         constraint.validate("a1")
Esempio n. 8
0
 def test_should_not_validate_multiple_values_sent_for_single_choice(self):
     with self.assertRaises(AnswerHasTooManyValuesException):
         valid_choices = [
             "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l",
             "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x",
             "y", "z", "1a", "1b", "1c"
         ]
         constraint = ChoiceConstraint(single_select_constraint=True,
                                       list_of_valid_choices=valid_choices,
                                       code="Q1")
         self.assertEqual(constraint.validate("1b"), ['1b'])
         constraint.validate("a1a")
Esempio n. 9
0
 def __init__(self,
              name,
              code,
              label,
              options,
              ddtype,
              instruction=None,
              language=field_attributes.DEFAULT_LANGUAGE,
              single_select_flag=True):
     assert len(options) > 0
     type = field_attributes.SELECT_FIELD if single_select_flag else field_attributes.MULTISELECT_FIELD
     self.SINGLE_SELECT_FLAG = single_select_flag
     Field.__init__(self,
                    type=type,
                    name=name,
                    code=code,
                    label=label,
                    language=language,
                    ddtype=ddtype,
                    instruction=instruction)
     self._dict[self.OPTIONS] = []
     valid_choices = self._dict[self.OPTIONS]
     if options is not None:
         for option in options:
             if isinstance(option, tuple):
                 single_language_specific_option = {
                     'text': {
                         language: option[0]
                     },
                     'val': option[1]
                 }
             elif isinstance(option, dict):
                 single_language_specific_option = option
             else:
                 single_language_specific_option = {
                     'text': {
                         language: option
                     }
                 }
             valid_choices.append(single_language_specific_option)
     self.constraint = ChoiceConstraint(
         list_of_valid_choices=[
             each.get('text').get(language) for each in valid_choices
         ],
         single_select_constraint=single_select_flag,
         code=code)
Esempio n. 10
0
 def __init__(self,
              name,
              code,
              label,
              options,
              instruction=None,
              single_select_flag=True,
              required=True,
              parent_field_code=None,
              has_other=False):
     assert len(options) > 0
     type = field_attributes.SELECT_FIELD if single_select_flag else field_attributes.MULTISELECT_FIELD
     self.single_select_flag = single_select_flag
     Field.__init__(self,
                    type=type,
                    name=name,
                    code=code,
                    label=label,
                    instruction=instruction,
                    required=required,
                    parent_field_code=parent_field_code)
     self._dict[self.OPTIONS] = []
     valid_choices = self._dict[self.OPTIONS]
     if has_other:
         self._dict['has_other'] = has_other
     if options is not None:
         for option in options:
             if isinstance(option, tuple):
                 single_language_specific_option = {
                     'text': option[0],
                     'val': option[1]
                 }
             elif isinstance(option, dict):
                 single_language_specific_option = option
             else:
                 single_language_specific_option = {
                     'text': option,
                     'val': option
                 }
             valid_choices.append(single_language_specific_option)
     self.constraint = ChoiceConstraint(
         list_of_valid_choices=valid_choices,
         single_select_constraint=single_select_flag,
         code=code,
         has_other=has_other)
Esempio n. 11
0
class SelectField(Field):
    OPTIONS = "choices"

    def __init__(self, name, code, label, options, ddtype, instruction=None,
                 language=field_attributes.DEFAULT_LANGUAGE,
                 single_select_flag=True):
        assert len(options) > 0
        type = field_attributes.SELECT_FIELD if single_select_flag else field_attributes.MULTISELECT_FIELD
        self.SINGLE_SELECT_FLAG = single_select_flag
        Field.__init__(self, type=type, name=name, code=code,
                       label=label, language=language, ddtype=ddtype, instruction=instruction)
        self._dict[self.OPTIONS] = []
        valid_choices = self._dict[self.OPTIONS]
        if options is not None:
            for option in options:
                if isinstance(option, tuple):
                    single_language_specific_option = {'text': {language: option[0]}, 'val': option[1]}
                elif isinstance(option, dict):
                    single_language_specific_option = option
                else:
                    single_language_specific_option = {'text': {language: option}}
                valid_choices.append(single_language_specific_option)
        self.constraint = ChoiceConstraint(
            list_of_valid_choices=[each.get('text').get(language) for each in valid_choices],
            single_select_constraint=single_select_flag, code=code)

    SINGLE_SELECT_FLAG = 'single_select_flag'

    def validate(self, value):
        return self.constraint.validate(answer=value)

    @property
    def options(self):
        return self._dict.get(self.OPTIONS)

    def _to_json_view(self):
        dict = self._dict.copy()
        option_list = []
        for option in self.options:
            option_text = option["text"][field_attributes.DEFAULT_LANGUAGE]
            option_list.append({"text": option_text, "val": option.get("val")})
        dict['choices'] = option_list
        dict['ddtype'] = dict['ddtype'].to_json()
        return dict

    def to_html(self):
        options_html = ""
        for option in self.options:
            options_html += '<option value="%s">%s</option>' % (option['val'], option['text']['eng'], )
        multiple_select = '' if self.SINGLE_SELECT_FLAG else 'MULTIPLE'
        return '<select name="%s" %s>%s</select>' % (self.name, multiple_select, options_html)
Esempio n. 12
0
 def __init__(self, name, code, label, options, ddtype, instruction=None,
              language=field_attributes.DEFAULT_LANGUAGE,
              single_select_flag=True):
     assert len(options) > 0
     type = field_attributes.SELECT_FIELD if single_select_flag else field_attributes.MULTISELECT_FIELD
     self.SINGLE_SELECT_FLAG = single_select_flag
     Field.__init__(self, type=type, name=name, code=code,
                    label=label, language=language, ddtype=ddtype, instruction=instruction)
     self._dict[self.OPTIONS] = []
     valid_choices = self._dict[self.OPTIONS]
     if options is not None:
         for option in options:
             if isinstance(option, tuple):
                 single_language_specific_option = {'text': {language: option[0]}, 'val': option[1]}
             elif isinstance(option, dict):
                 single_language_specific_option = option
             else:
                 single_language_specific_option = {'text': {language: option}}
             valid_choices.append(single_language_specific_option)
     self.constraint = ChoiceConstraint(
         list_of_valid_choices=[each.get('text').get(language) for each in valid_choices],
         single_select_constraint=single_select_flag, code=code)
Esempio n. 13
0
 def test_should_invalidate_special_characters_sent_for_choice(self):
     with self.assertRaises(AnswerNotInListException):
         constraint = ChoiceConstraint(single_select_constraint=False,
                                       list_of_valid_choices=["village", "urban", "city", "country"],
                                       code="Q1")
         constraint.validate("a!b")
Esempio n. 14
0
 def test_should_not_validate_no_values_sent_for_choice(self):
     with self.assertRaises(AnswerHasNoValuesException):
         constraint = ChoiceConstraint(single_select_constraint=True, list_of_valid_choices=["village", "urban"],
                                       code="Q1")
         constraint.validate("")
Esempio n. 15
0
 def test_should_validate_multiple_choice(self):
     constraint = ChoiceConstraint(single_select_constraint=False, list_of_valid_choices=["village", "urban"],
                                   code="Q1")
     v_data = constraint.validate("ab")
     self.assertEquals(v_data, ["village", "urban"])
Esempio n. 16
0
class SelectField(Field):
    '''option values for this should contain single letters like a,b,c,d etc and after 26 options should start with a number followed by single character
    like 1a,1b,1c,1d etc '''
    OPTIONS = "choices"

    def __init__(self,
                 name,
                 code,
                 label,
                 options,
                 instruction=None,
                 single_select_flag=True,
                 required=True,
                 parent_field_code=None,
                 has_other=False):
        assert len(options) > 0
        type = field_attributes.SELECT_FIELD if single_select_flag else field_attributes.MULTISELECT_FIELD
        self.single_select_flag = single_select_flag
        Field.__init__(self,
                       type=type,
                       name=name,
                       code=code,
                       label=label,
                       instruction=instruction,
                       required=required,
                       parent_field_code=parent_field_code)
        self._dict[self.OPTIONS] = []
        valid_choices = self._dict[self.OPTIONS]
        if has_other:
            self._dict['has_other'] = has_other
        if options is not None:
            for option in options:
                if isinstance(option, tuple):
                    single_language_specific_option = {
                        'text': option[0],
                        'val': option[1]
                    }
                elif isinstance(option, dict):
                    single_language_specific_option = option
                else:
                    single_language_specific_option = {
                        'text': option,
                        'val': option
                    }
                valid_choices.append(single_language_specific_option)
        self.constraint = ChoiceConstraint(
            list_of_valid_choices=valid_choices,
            single_select_constraint=single_select_flag,
            code=code,
            has_other=has_other)

    SINGLE_SELECT_FLAG = 'single_select_flag'

    def validate(self, value):
        Field.validate(self, value)
        return self.constraint.validate(answer=value)

    @property
    def options(self):
        return self._dict.get(self.OPTIONS)

    def _to_json_view(self):
        dict = self._dict.copy()
        return dict

    @property
    def has_other(self):
        return self._dict.get('has_other')

    def get_constraint_text(self):
        return [option["text"] for option in self.options]

    def convert_to_unicode(self):
        if self.value is None:
            return unicode("")
        return unicode(",".join([unicode(i)
                                 for i in self.value])) if isinstance(
                                     self.value, list) else unicode(self.value)

    # def _get_value_by_option(self, option):
    # for opt in self.options:
    #         opt_text = opt['text']
    #         opt_value = opt['val']
    #         if opt_value.lower() == option.lower():
    #             return opt_text
    #     return None

    @property
    def is_single_select(self):
        return self.type == "select1"

    def get_value_by_option(self, option, default=None):
        for opt in self.options:
            opt_text = opt['text']
            opt_value = opt['val']
            if opt_value.lower() == option.lower():
                return opt_text
        return default

    def get_option_value_list(self, question_value):

        # if isinstance(question_value, list) and question_value[0] == 'other':
        #     if self.is_single_select:
        #         return [question_value[1]]
        #     else:
        #         question_value = ','.join(question_value[1].split(' '))

        options = self.get_option_list(question_value)
        result = []
        for option in options:
            option_value = self.get_value_by_option(option, default=option)
            if option_value:
                result.append(option_value)
        return result

    def get_option_list(self, question_value):
        if question_value is None: return []

        question_value = question_value.lower()

        if ',' in question_value:
            responses = question_value.split(',')
            responses = [r.strip() for r in responses]
        elif ' ' in question_value:
            responses = question_value.split(' ')
        elif question_value in [
                item.get('val') for item in self._dict[self.OPTIONS]
        ]:
            # yes in ['yes','no']
            responses = [question_value]
        elif self.has_other and question_value == 'other':
            responses = ['other']
        else:
            responses = re.findall(r'[1-9]?[a-zA-Z]', question_value)

        return responses

    def formatted_field_values_for_excel(self, value):
        if value is None: return []

        options = self.get_option_list(value)
        result = []
        for option in options:
            option_value = self.get_value_by_option(option)
            if option_value:
                result.append(option_value)
        return result

    def get_options_map(self):
        options_map = {}
        for option in self.options:
            options_map.update({option['val']: option['text']})
        return options_map

    def escape_option_text(self):
        for option in self._dict.get(self.OPTIONS):
            option['text'] = escape(option['text'])
Esempio n. 17
0
 def test_should_not_validate_wrong_choice(self):
     with self.assertRaises(AnswerNotInListException):
         constraint = ChoiceConstraint(single_select_constraint=True, list_of_valid_choices=["village", "urban"],
                                       code="Q1")
         constraint.validate("c")
Esempio n. 18
0
class SelectField(Field):
    OPTIONS = "choices"

    def __init__(self,
                 name,
                 code,
                 label,
                 options,
                 ddtype,
                 instruction=None,
                 language=field_attributes.DEFAULT_LANGUAGE,
                 single_select_flag=True):
        assert len(options) > 0
        type = field_attributes.SELECT_FIELD if single_select_flag else field_attributes.MULTISELECT_FIELD
        self.SINGLE_SELECT_FLAG = single_select_flag
        Field.__init__(self,
                       type=type,
                       name=name,
                       code=code,
                       label=label,
                       language=language,
                       ddtype=ddtype,
                       instruction=instruction)
        self._dict[self.OPTIONS] = []
        valid_choices = self._dict[self.OPTIONS]
        if options is not None:
            for option in options:
                if isinstance(option, tuple):
                    single_language_specific_option = {
                        'text': {
                            language: option[0]
                        },
                        'val': option[1]
                    }
                elif isinstance(option, dict):
                    single_language_specific_option = option
                else:
                    single_language_specific_option = {
                        'text': {
                            language: option
                        }
                    }
                valid_choices.append(single_language_specific_option)
        self.constraint = ChoiceConstraint(
            list_of_valid_choices=[
                each.get('text').get(language) for each in valid_choices
            ],
            single_select_constraint=single_select_flag,
            code=code)

    SINGLE_SELECT_FLAG = 'single_select_flag'

    def validate(self, value):
        return self.constraint.validate(answer=value)

    @property
    def options(self):
        return self._dict.get(self.OPTIONS)

    def _to_json_view(self):
        dict = self._dict.copy()
        option_list = []
        for option in self.options:
            option_text = option["text"][field_attributes.DEFAULT_LANGUAGE]
            option_list.append({"text": option_text, "val": option.get("val")})
        dict['choices'] = option_list
        dict['ddtype'] = dict['ddtype'].to_json()
        return dict

    def to_html(self):
        options_html = ""
        for option in self.options:
            options_html += '<option value="%s">%s</option>' % (
                option['val'],
                option['text']['eng'],
            )
        multiple_select = '' if self.SINGLE_SELECT_FLAG else 'MULTIPLE'
        return '<select name="%s" %s>%s</select>' % (
            self.name, multiple_select, options_html)