Example #1
0
def get_value_through_type(value_type, value_dict):
    u'''Получить корректные значения // сформировать их'''
    format_dict = header_type_to_filter_type()
    fast_trancate = lambda x: '.'.join(x.split('-')[::-1]) if isinstance(
        x, (str, unicode)) else x
    if value_type not in {'date', 'float'}:
        return value_dict[format_dict[value_type]]
    else:
        interval = [
            fast_trancate(x) for x in [
                value_dict[format_dict[value_type]['from']], value_dict[
                    format_dict[value_type]['to']]
            ]
        ]
        equal_value = fast_trancate(value_dict[format_dict['text']])

        smth = Something()
        #print(interval, equal_value, 'gvtt', smth in interval)
        if not is_exist(value_dict['condition'], '@value'):
            value_dict['condition'] = {}
            if smth in interval:
                value_dict['condition']['@value'] = 'between'
                value_dict['condition']['@label'] = u''
            else:
                value_dict['condition']['@value'] = 'equal'
                value_dict['condition']['@label'] = u''

        return interval if value_dict['condition'][
            '@value'] == 'between' else equal_value
Example #2
0
    def preprocessor_any(self, values_dict):
        must_have_settings = {'data_type', 'empty', 'label', 'values_to_header', 
                              'end', 'case_sensitive'}

        if 'data_type' not in values_dict.keys() or values_dict['data_type'] not in self.data_types:
            raise IncorrectHeaderInput("Incorrect input: not specified field data type.")
        result = {}
        for setting in must_have_settings:
            if setting in values_dict.keys():
                result[setting] = values_dict[setting]
            elif setting == 'end':
                result[setting] = '; '
            elif setting == 'case_sensitive':
                result[setting] = False
            else:
                result[setting] = ''
        # postprocessing
        if is_exist(values_dict, u'newline'):
            result['newline'] = True
        return result
Example #3
0
    def return_header(self, current_values, context_filter=False):
        u'''current_values = {id_field: value} for non-standard filtering and
            {id_field: {data_types : value, ...}} for STANDARTEN'''
        # New view
        # Приведение всех значений в поле, которое обрабатывается в соответствие с типом
        if context_filter is False:
            standard_header_dict = through_filler(current_values,
                                                  self.header_dict)
        else:
            # Переработка полученных значений в текст в поле text, вне зависиммости от способа отображения
            for y in current_values.values():
                if is_exist(y, 'item', {'@id': self.smth}):
                    dash_date = re.compile(r"[0-9]{4}-[0-9]{2}-[0-9]{2}")
                    dot_date = re.compile(r"[0-9]{2}.[0-9]{2}.[0-9]{4}")
                    dash_date_string = re.findall(dash_date,
                                                  unicode(y['item']['@name']))
                    dot_date_string = re.findall(dot_date,
                                                 unicode(y['item']['@name']))
                    if dash_date_string:
                        y['text'] = dash_date_string[0]
                    elif dot_date_string:
                        y['text'] = dot_date_string[0]
                    else:
                        y['text'] = y['item']['@name']
                elif is_exist(y, 'items'):
                    if '@name' not in y['items']:
                        y['text'] = u'; '.join(
                            [x['@name'] for x in y['items']])
                    else:
                        y['text'] = y['items']['@name']
            standard_header_dict = current_values

        header_list = [{
            "@class": 'header-class',
            "span": {
                "@class": 'header-header',
                '#text': self.header
            }
        }] if self.header else []
        i = 0
        next_upper = False
        # Формирование списка с подстановкой значений, либо emtpy-вариантом
        for key, values_dict in self.header_dict.items():
            # Получение из пришедшего словаря данных
            current_value = get_value_through_type(
                values_dict['data_type'], standard_header_dict[key] if key
                in standard_header_dict.keys() else unbound_dict_filler(['']))
            # Переменные для стилей-словарей
            h_key = ''
            h_cond = ''
            h_value = ''
            #print(current_value, values_dict['data_type'])
            if current_value in ('', None):
                h_value = values_dict['empty']
            else:
                # Если получаемые значения должны подставляться с использованием алиасов, то заменяем значения
                if is_exist(values_dict, 'values_to_header', self.smth):
                    format_string = values_dict['values_to_header'][
                        current_value]
                else:
                    format_string = current_value
                # Проверка на полученные значения -- одно или много
                if values_dict['data_type'] in {'date', 'float'}:
                    # Задаем текстовые шаблоны для интервальных значений
                    first_chapter = u'c %s'
                    second_chapter = u'по %s'
                    h_key = values_dict['label']
                    # Формируем окончательный вариант
                    if is_exist(standard_header_dict[key], 'condition',
                                {'@value': 'equal'}):
                        h_cond = standard_header_dict[key]['condition'][
                            '@label']
                        h_value = format_string
                    elif is_exist(standard_header_dict[key], 'condition',
                                  {'@value': 'right'}):
                        h_value = second_chapter % format_string
                    elif is_exist(standard_header_dict[key], 'condition',
                                  {'@value': 'left'}):
                        h_value = first_chapter % format_string
                    else:
                        h_value = u'%s%s%s' % (
                            (first_chapter % format_string[0])
                            if format_string[0] != '' else '',
                            ' ' if '' not in format_string else '',
                            (second_chapter % format_string[1])
                            if format_string[1] != '' else '')
                else:
                    if values_dict['data_type'] == 'bool':
                        h_key = (u'%s%s.' % (self.boolean_prefix, values_dict['label'].rstrip()))\
                            if format_string in {True, 'true', 'True'} else values_dict['empty']
                    else:
                        h_key = values_dict['label'] if values_dict[
                            'label'] else ''
                        if self.is_context:
                            h_cond = standard_header_dict[key]['condition']['@label']\
                                if '@label' in standard_header_dict[key]['condition'] else u''
                        h_value = format_string
            # Добавляем переход на новую строку
#             if is_exist(values_dict, 'newline'):
#                 h_value = unicode(h_value) + u'\n'
#                 next_upper = True

            if h_value != values_dict['empty']:
                h_value = unicode(h_value) + values_dict['end']
                first_string = h_key or h_value or u''
                # Штука для того, чтобы следующий фильтр шёл с большой буквы
                if next_upper and not is_exist(
                        values_dict, 'case_sensitive',
                        True) and first_string and first_string[0].islower():
                    first_string = u' '.join([first_string.split()[0].capitalize(), u' '.join(first_string.split()[1:])])\
                                if len(first_string.split()) > 1 else first_string.capitalize()
                if first_string:
                    if h_key:
                        h_key = first_string
                    elif h_value:
                        h_value = first_string
                    next_upper = False
            if '.' in values_dict['end']:
                next_upper = True
            i += 1

            header_key = {"@class": "header-key", "#text": h_key + u' '}
            header_condition = {
                "@class":
                "header-condition",
                "#text":
                (h_cond +
                 (u': ' if ';' in h_value else u' ')) if h_cond else ''
            }
            header_value = {"@class": "header-value", "#text": h_value + u' '}
            header_list.append({"@class": "header-clause", "span": []})
            if h_key.strip() not in {
                    '.', ''
            } and (values_dict['data_type'] == 'bool' or
                   (values_dict['data_type'] != 'bool' and h_value)):
                header_list[-1]['span'].append(header_key)
            if h_cond.strip() not in {'.', ''}:
                header_list[-1]['span'].append(header_condition)
            if h_value.strip() not in {'.', ''}:
                header_list[-1]['span'].append(header_value)

        header_list = filter(lambda x: x['span'] != [], header_list)
        if header_list:
            if isinstance(header_list[0]['span'], dict):
                header_list[0]['span'] = [header_list[0]['span']]
        if len(header_list) == int(bool(self.header)):
            if len(header_list) == 1:
                header_list[0]['span'][0]["#text"] += u' нет.'
            else:
                header_list.append({
                    "@class": "header-clause",
                    "#text": u'Не заданы параметры поиска'
                })
        return {'span': header_list}
Example #4
0
    def test_any_function(self):
        from any_functions import is_exist, Something
        # Негативная проверка на корректность включённости ключа в словарь
        # Проверка на некорректные типы данных
        for i in [None, '1', 1, True, [], [1], {1}, (1, )]:
            self.assertEqual(is_exist(i, 1, None), None)
        # Логические значения
        self.assertEqual(is_exist({1: 2}, True, None), False)
        self.assertEqual(is_exist({0: 2}, False, None), False)
        self.assertEqual(is_exist({'': 2}, False, None), False)
        # Числа/строки
        self.assertEqual(is_exist({'1': ''}, 1), False)
        self.assertEqual(is_exist({'1': 2}, 1, None), False)
        self.assertEqual(is_exist({1: 2}, '1', None), False)
        self.assertEqual(is_exist({0: 2}, '', None), False)
        self.assertEqual(is_exist({0: 2}, 2, 2), False)
        # Проверка на корректность возвращённого значения при наличии значения
        self.assertEqual(is_exist({1: 2, '1': '2'}, 1, 2), True)
        self.assertEqual(is_exist({1: 2, '1': '2'}, 1, '2'), False)
        self.assertEqual(is_exist({1: 2, '1': '2'}, '1', '2'), True)
        self.assertEqual(is_exist({1: 2, '1': '2'}, 2, 1), False)
        # Тесты для путей в словарях
        smth = Something()
        self.assertEqual(is_exist({
            2: {
                2: 3
            },
            '1': '2'
        }, 2, {1: {
            2: smth
        }}), False)
        self.assertEqual(
            is_exist(
                {
                    'outer': {
                        'inner1': {
                            'inner2': {
                                'default': ['we', 'have', 'it']
                            }
                        },
                        'other': True,
                        'othertwo': 123,
                        'another': {
                            1: 2,
                            'oi': 'ne'
                        }
                    }
                }, 'outer', {'inner1': {
                    'inner2': {
                        'default': smth
                    }
                }}), True)
        self.assertEqual(
            is_exist(
                {
                    'outer': {
                        'inner1': {
                            'inner2': {
                                'default': ['we', 'have', 'it']
                            }
                        },
                        'other': True,
                        'othertwo': 123,
                        'another': {
                            1: 2,
                            'oi': 'ne'
                        }
                    }
                }, 'outer', {'inner1': {
                    'inner2': smth
                }}, {'inor': smth}), False)
        self.assertEqual(
            is_exist(
                {
                    'outer': {
                        'inner1': {
                            'inner2': {
                                'default': ['we', 'have', 'it']
                            }
                        },
                        'other': True,
                        'othertwo': 123,
                        'another': {
                            1: 2,
                            'oi': 'ne'
                        }
                    }
                }, 'outer', {'inner1': {
                    'inner2': smth
                }}, {'inor'}), False)
        self.assertEqual(
            is_exist(
                {
                    'outer': {
                        'inner1': {
                            'inner2': {
                                'default': ['we', 'have', 'it']
                            }
                        },
                        'other': True,
                        'othertwo': 123,
                        'another': {
                            1: 2,
                            'oi': 'ne'
                        }
                    }
                }, 'outer', {'inner1': {
                    'inner2': smth
                }}, {'othertwo': 123}), True)
        example_dict = {
            '@required': 'false',
            '@style': 'unbound',
            '@id': 'period',
            'item': {
                '@id': '',
                '@name': ''
            },
            'conditions': {
                'condition': [{
                    '@value': 'between',
                    '@label': u'\u043c\u0435\u0436\u0434\u0443'
                }]
            },
            '@tableName': 'nsi.vw_aerodrome_cert',
            '@randint': 0,
            '@type': 'date',
            '@boolInput': 'false',
            'selects': {
                'select': []
            },
            '@minValue': '01.01.2016',
            '@value': '',
            '@label':
            u'\u041f\u0435\u0440\u0438\u043e\u0434 \u0442\u0435\u043a\u0443\u0448\u0435\u0433\u043e \u0433\u043e\u0434\u0430',
            '@maxValue': '07.09.2016',
            '@selector_data': '',
            'default': ['01.01.2016', '07.09.2016'],
            '@key': 'view',
            '@current_condition': 'between',
            'items': {
                'item': []
            }
        }
        self.assertEqual(is_exist(example_dict, 'item', {'@id': smth}), False)
        self.assertEqual(
            is_exist(example_dict, 'conditions', {'condition': smth}), True)
        self.assertEqual(
            is_exist({'period': {
                'minValue': 90
            }}, 'period', {
                'minValue': smth,
                'maxValue': smth
            }), False)
        self.assertEqual(
            is_exist({'period': {
                'minValue': 90,
                'maxValue': 188
            }}, 'period', {
                'minValue': smth,
                'maxValue': smth
            }), True)
        unbound_dict = {
            'strUnit': {
                'item': {
                    u'@id':
                    u'strUnits17',
                    u'@name':
                    u'\u0420\u0443\u043a\u043e\u0432\u043e\u0434\u0441\u0442\u0432\u043e'
                },
                'maxValue': u'',
                'minValue': u'',
                'condition': u'equal',
                'text': u'',
                'bool': False
            },
            'lastPeriod': {
                'item': {
                    u'@id': u'',
                    u'@name': u''
                },
                'maxValue': u'',
                'minValue': u'',
                'condition': u'equal',
                'text': u'',
                'bool': True
            },
            'tu': {
                'item': {
                    u'@id':
                    u'ogkn4',
                    u'@name':
                    u'\u0423\u0413\u0410\u041d \u041d\u041e\u0422\u0411 \u0426\u0424\u041e'
                },
                'maxValue': u'',
                'minValue': u'',
                'condition': u'equal',
                'text': u'',
                'bool': False
            },
            'date': {
                'item': {
                    u'@id': u'',
                    u'@name': u''
                },
                'maxValue': u'2016-09-13',
                'minValue': u'2016-01-01',
                'condition': u'between',
                'text': u'',
                'bool': False
            }
        }
        self.assertEqual(is_exist(unbound_dict, 'lastPeriod', {'bool': True}),
                         True)

        self.assertEqual(smth, True)
        self.assertEqual(smth, False)
        self.assertTrue(smth not in ['', ''])
        self.assertTrue(smth in ['1', ''])
        self.assertTrue(smth in {'1': ''}.keys())
        with self.assertRaises(TypeError):
            smth in {'1': ''}
        self.assertTrue(smth == 0)
        self.assertFalse(smth == [])