PK[6,Qu u pytils/__init__.py# -*- coding: utf-8 -*- # PyTils - simple processing for russian strings # Copyright (C) 2006-2007 Yury Yurevich # # http://gorod-omsk.ru/blog/pythy/projects/pytils/ # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation, version 2 # of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. """ Simple processing for russian strings """ __id__ = __revision__ = "$Id: __init__.py 74 2007-02-27 15:11:35Z the.pythy $" __url__ = "$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/__init__.py $" __all__ = ["numeral", "dt", "translit", "test", "utils"] # версия PyTils VERSION_MAJOR = 0 #: Major version of PyTils (i.e. branch) VERSION_MINOR = 2 #: Minor version of PyTils (i.e. release) VERSION_TINY = 1 #: Tiny version of PyTils (i.e. subrelease) VERSION = "%d.%d.%d" % (VERSION_MAJOR, VERSION_MINOR, VERSION_TINY) #: Version's string REL_DATE = '20070227' #: Release date def _get_svn_date_from_id(id_string): """Returns date of last update (extract from __id__)""" if id_string.replace('$', '') == "Id": return REL_DATE else: return id_string.split()[3].replace('-', '') _module_dates = [_get_svn_date_from_id(__id__), ] #: Last changes in submodules # импорт модулей for _module_name in __all__: _imported_module = __import__("pytils."+_module_name, globals(), locals(), ["pytils"]) _module_dates.append(_get_svn_date_from_id(_imported_module.__id__)) SVN_DATE = max(_module_dates) #: Last change in submodules # если взяли с svn, то версия будет # X.Y.Z-svnYYYYMMDD, где X.Y.Z - номер оригинальной версии, # а YYYYMMDD - дата последнего изменения в модулях # единственная сложность остается, если взяли не через svn, # а через webdav, в этом случае Id не проставляется и версия # будет оригинальной. Это можно обойти, скажем, учитывая дату # изменения файлов, но я пока не вижу в этом смысла. if SVN_DATE > REL_DATE: VERSION = "%s-svn%s" % (VERSION, SVN_DATE) #: Version's string (with appended svndate) PKz"6lvv pytils/dt.py# -*- coding: utf-8 -*- # -*- test-case-name: pytils.test.test_dt -*- # PyTils - simple processing for russian strings # Copyright (C) 2006-2007 Yury Yurevich # # http://gorod-omsk.ru/blog/pythy/projects/pytils/ # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation, version 2 # of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. """ Russian dates without locales """ __id__ = __revision__ = "$Id: dt.py 63 2007-01-02 09:22:16Z the.pythy $" __url__ = "$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/dt.py $" import datetime from pytils import numeral, utils DAY_ALTERNATIVES = { 1: (u"вчера", u"завтра"), 2: (u"позавчера", u"послезавтра") } #: Day alternatives (i.e. one day ago -> yesterday) DAY_VARIANTS = ( u"день", u"дня", u"дней", ) #: Forms (1, 2, 5) for noun 'day' HOUR_VARIANTS = ( u"час", u"часа", u"часов", ) #: Forms (1, 2, 5) for noun 'hour' MINUTE_VARIANTS = ( u"минуту", u"минуты", u"минут", ) #: Forms (1, 2, 5) for noun 'minute' PREFIX_IN = u"через" #: Prefix 'in' (i.e. B{in} three hours) SUFFIX_AGO = u"назад" #: Prefix 'ago' (i.e. three hours B{ago}) MONTH_NAMES = ( (u"янв", u"январь", u"января"), (u"фев", u"февраль", u"февраля"), (u"мар", u"март", u"марта"), (u"апр", u"апрель", u"апреля"), (u"май", u"май", u"мая"), (u"июн", u"июнь", u"июня"), (u"июл", u"июль", u"июля"), (u"авг", u"август", u"августа"), (u"сен", u"сентябрь", u"сентября"), (u"окт", u"октябрь", u"октября"), (u"ноя", u"ноябрь", u"ноября"), (u"дек", u"декабрь", u"декабря"), ) #: Month names (abbreviated, full, inflected) DAY_NAMES = ( (u"пн", u"понедельник", u"понедельник"), (u"вт", u"вторник", u"вторник"), (u"ср", u"среда", u"среду"), (u"чт", u"четверг", u"четверг"), (u"пт", u"пятница", u"пятницу"), (u"сб", u"суббота", u"субботу"), (u"вск", u"воскресенье", u"субботу"), ) #: Day names (abbreviated, full, inflected) def distance_of_time_in_words(from_time, accuracy=1, to_time=None): """ Represents distance of time in words @param from_time: source time (in seconds from epoch) @type from_time: C{int}, C{float} or C{datetime.datetime} @param accuracy: level of accuracy (1..3), default=1 @type accuracy: C{int} @param to_time: target time (in seconds from epoch), default=None translates to current time @type to_time: C{int}, C{float} or C{datetime.datetime} @return: distance of time in words @rtype: unicode @raise TypeError: input parameters' check failed @raise ValueError: accuracy is lesser or equal zero """ current = False if to_time is None: current = True to_time = datetime.datetime.now() utils.check_type('from_time', (int, float, datetime.datetime)) utils.check_type('to_time', (int, float, datetime.datetime)) utils.check_type('accuracy', int) utils.check_positive('accuracy', strict=True) if not isinstance(from_time, datetime.datetime): from_time = datetime.datetime.fromtimestamp(from_time) if not isinstance(to_time, datetime.datetime): to_time = datetime.datetime.fromtimestamp(to_time) dt_delta = to_time - from_time difference = dt_delta.days*86400 + dt_delta.seconds seconds_orig = int(abs(difference)) minutes_orig = int(abs(difference)/60.0) hours_orig = int(abs(difference)/3600.0) days_orig = int(abs(difference)/86400.0) in_future = from_time > to_time words = [] values = [] alternatives = [] days = days_orig hours = hours_orig - days_orig*24 words.append(u"%d %s" % (days, numeral.choose_plural(days, DAY_VARIANTS))) values.append(days) words.append(u"%d %s" % \ (hours, numeral.choose_plural(hours, HOUR_VARIANTS))) values.append(hours) hours == 1 and current and alternatives.append(u"час") minutes = minutes_orig - hours_orig*60 words.append(u"%d %s" % (minutes, numeral.choose_plural(minutes, MINUTE_VARIANTS))) values.append(minutes) minutes == 1 and current and alternatives.append(u"минуту") real_words = words # убираем из values и words конечные нули while values and not values[-1]: values.pop() words.pop() # убираем из values и words начальные нули while values and not values[0]: values.pop(0) words.pop(0) limit = min(accuracy, len(words)) real_words = words[:limit] real_values = values[:limit] # снова убираем конечные нули while real_values and not real_values[-1]: real_values.pop() real_words.pop() limit -= 1 real_str = u" ".join(real_words) # альтернативные варианты нужны только если в real_words одно значение # и, вдобавок, если используется текущее время alter_str = limit == 1 and current and \ alternatives and alternatives[0] _result_str = alter_str or real_str result_str = in_future and u"%s %s" % (PREFIX_IN, _result_str) \ or u"%s %s" % (_result_str, SUFFIX_AGO) # если же прошло менее минуты, то real_words -- пустой, и поэтому # нужно брать alternatives[0], а не result_str zero_str = minutes == 0 and not real_words and \ (in_future and u"менее чем через минуту" \ or u"менее минуты назад") # нужно использовать вчера/позавчера/завтра/послезавтра # если days 1..2 и в real_words одно значение day_alternatives = DAY_ALTERNATIVES.get(days, False) alternate_day = day_alternatives and current and limit == 1 and \ ((in_future and day_alternatives[1]) \ or day_alternatives[0]) final_str = not real_words and zero_str or alternate_day or result_str return final_str def ru_strftime(format=u"%d.%m.%Y", date=None, inflected=False, inflected_day=False): """ Russian strftime without locale @param format: strftime format, default=u'%d.%m.%Y' @type format: C{unicode} @param date: date value, default=None translates to today @type date: C{datetime.date} or C{datetime.datetime} @return: strftime string @rtype: unicode @raise TypeError: input parameters' check failed """ if date is None: date = datetime.datetime.today() utils.check_type('date', (datetime.date, datetime.datetime)) utils.check_type('format', unicode) midx = inflected and 2 or 1 didx = inflected_day and 2 or 1 format = format.replace(u'%a', DAY_NAMES[date.weekday()][0]) format = format.replace(u'%A', DAY_NAMES[date.weekday()][didx]) format = format.replace(u'%b', MONTH_NAMES[date.month-1][0]) format = format.replace(u'%B', MONTH_NAMES[date.month-1][midx]) # strftime must be str, so encode it to utf8: s_format = format.encode("utf-8") s_res = date.strftime(s_format) # and back to unicode u_res = s_res.decode("utf-8") return u_res PKz"6\H6H6pytils/numeral.py# -*- coding: utf-8 -*- # -*- test-case-name: pytils.test.test_numeral -*- # PyTils - simple processing for russian strings # Copyright (C) 2006-2007 Yury Yurevich # # http://gorod-omsk.ru/blog/pythy/projects/pytils/ # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation, version 2 # of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. """ Plural forms and in-word representation for numerals. """ __id__ = __revision__ = "$Id: numeral.py 63 2007-01-02 09:22:16Z the.pythy $" __url__ = "$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/numeral.py $" from pytils import utils FRACTIONS = ( (u"десятая", u"десятых", u"десятых"), (u"сотая", u"сотых", u"сотых"), (u"тысячная", u"тысячных", u"тысячных"), (u"десятитысячная", u"десятитысячных", u"десятитысячных"), (u"стотысячная", u"стотысячных", u"стотысячных"), (u"миллионная", u"милллионных", u"милллионных"), (u"десятимиллионная", u"десятимилллионных", u"десятимиллионных"), (u"стомиллионная", u"стомилллионных", u"стомиллионных"), (u"миллиардная", u"миллиардных", u"миллиардных"), ) #: Forms (1, 2, 5) for fractions ONES = { 0: (u"", u"", u""), 1: (u"один", u"одна", u"одно"), 2: (u"два", u"две", u"два"), 3: (u"три", u"три", u"три"), 4: (u"четыре", u"четыре", u"четыре"), 5: (u"пять", u"пять", u"пять"), 6: (u"шесть", u"шесть", u"шесть"), 7: (u"семь", u"семь", u"семь"), 8: (u"восемь", u"восемь", u"восемь"), 9: (u"девять", u"девять", u"девять"), } #: Forms (MALE, FEMALE, NEUTER) for ones TENS = { 0: u"", # 1 - особый случай 10: u"десять", 11: u"одиннадцать", 12: u"двенадцать", 13: u"тринадцать", 14: u"четырнадцать", 15: u"пятнадцать", 16: u"шестнадцать", 17: u"семнадцать", 18: u"восемнадцать", 19: u"девятнадцать", 2: u"двадцать", 3: u"тридцать", 4: u"сорок", 5: u"пятьдесят", 6: u"шестьдесят", 7: u"семьдесят", 8: u"восемьдесят", 9: u"девяносто", } #: Tens HUNDREDS = { 0: u"", 1: u"сто", 2: u"двести", 3: u"триста", 4: u"четыреста", 5: u"пятьсот", 6: u"шестьсот", 7: u"семьсот", 8: u"восемьсот", 9: u"девятьсот", } #: Hundreds MALE = 1 #: sex - male FEMALE = 2 #: sex - female NEUTER = 3 #: sex - neuter def _get_float_remainder(fvalue, signs=9): """ Get remainder of float, i.e. 2.05 -> '05' @param fvalue: input value @type fvalue: C{int}, C{long} or C{float} @param signs: maximum number of signs @type signs: C{int} or C{long} @return: remainder @rtype: C{str} @raise TypeError: fvalue neither C{int}, no C{float} @raise ValueError: fvalue is negative @raise ValueError: signs overflow """ utils.check_type('fvalue', (int, long, float)) utils.check_positive('fvalue') if isinstance(fvalue, (int, long)): return "0" signs = min(signs, len(FRACTIONS)) # нужно remainder в строке, потому что дробные X.0Y # будут "ломаться" до X.Y remainder = str(fvalue).split('.')[1] iremainder = int(remainder) orig_remainder = remainder factor = len(str(remainder)) - signs if factor > 0: # после запятой цифр больше чем signs, округляем iremainder = int(round(iremainder / (10.0**factor))) format = "%%0%dd" % min(len(remainder), signs) remainder = format % iremainder if len(remainder) > signs: # при округлении цифр вида 0.998 ругаться raise ValueError("Signs overflow: I can't round only fractional part \ of %s to fit %s in %d signs" % \ (str(fvalue), orig_remainder, signs)) return remainder def choose_plural(amount, variants): """ Choose proper case depending on amount @param amount: amount of objects @type amount: C{int} or C{long} @param variants: variants (forms) of object in such form: (1 object, 2 objects, 5 objects). @type variants: 3-element C{sequence} of C{unicode} or C{unicode} (three variants with delimeter ',') @return: proper variant @rtype: C{unicode} @raise TypeError: amount isn't C{int}, variants isn't C{sequence} @raise ValueError: amount is negative @raise ValueError: variants' length lesser than 3 """ utils.check_type('amount', (int, long)) utils.check_positive('amount') utils.check_type('variants', (list, tuple, unicode)) if isinstance(variants, unicode): variants = [v.strip() for v in variants.split(',')] if amount % 10 == 1 and amount % 100 != 11: variant = 0 elif amount % 10 >= 2 and amount % 10 <= 4 and \ (amount % 100 < 10 or amount % 100 >= 20): variant = 1 else: variant = 2 utils.check_length('variants', 3) return variants[variant] def rubles(amount, zero_for_kopeck=False): """ Get string for money @param amount: amount of money @type amount: C{int}, C{long} or C{float} @param zero_for_kopeck: If false, then zero kopecks ignored @type zero_for_kopeck: C{bool} @return: in-words representation of money's amount @rtype: C{unicode} @raise TypeError: amount neither C{int}, no C{float} @raise ValueError: amount is negative """ utils.check_type('amount', (int, long, float)) utils.check_positive('amount') pts = [] amount = round(amount, 2) pts.append(sum_string(int(amount), 1, (u"рубль", u"рубля", u"рублей"))) remainder = _get_float_remainder(amount, 2) iremainder = int(remainder) if iremainder != 0 or zero_for_kopeck: # если 3.1, то это 10 копеек, а не одна if iremainder < 10 and len(remainder) == 1: iremainder *= 10 pts.append(sum_string(iremainder, 2, (u"копейка", u"копейки", u"копеек"))) return u" ".join(pts) def in_words_int(amount, gender=MALE): """ Integer in words @param amount: numeral @type amount: C{int} or C{long} @param gender: gender (MALE, FEMALE or NEUTER) @type gender: C{int} @return: in-words reprsentation of numeral @rtype: C{unicode} @raise TypeError: when amount is not C{int} @raise ValueError: amount is negative """ utils.check_type('amount', (int, long)) utils.check_positive('amount') return sum_string(amount, gender) def in_words_float(amount, _gender=FEMALE): """ Float in words @param amount: float numeral @type amount: C{float} @return: in-words reprsentation of float numeral @rtype: C{unicode} @raise TypeError: when amount is not C{float} @raise ValueError: when ammount is negative """ utils.check_type('amount', float) utils.check_positive('amount') pts = [] # преобразуем целую часть pts.append(sum_string(int(amount), 2, (u"целая", u"целых", u"целых"))) # теперь то, что после запятой remainder = _get_float_remainder(amount) signs = len(str(remainder)) - 1 pts.append(sum_string(int(remainder), 2, FRACTIONS[signs])) return u" ".join(pts) def in_words(amount, gender=None): """ Numeral in words @param amount: numeral @type amount: C{int}, C{long} or C{float} @param gender: gender (MALE, FEMALE or NEUTER) @type gender: C{int} @return: in-words reprsentation of numeral @rtype: C{unicode} raise TypeError: when amount not C{int} or C{float} raise ValueError: when amount is negative raise TypeError: when gender is not C{int} (and not None) raise ValueError: if gender isn't in (MALE, FEMALE, NEUTER) """ utils.check_positive('amount') gender is not None and utils.check_type('gender', int) if not (gender is None or gender in (MALE, FEMALE, NEUTER)): raise ValueError("Gender must be MALE, FEMALE or NEUTER, " + \ "not %d" % gender) if gender is None: args = (amount,) else: args = (amount, gender) # если целое if isinstance(amount, (int, long)): return in_words_int(*args) # если дробное elif isinstance(amount, float): return in_words_float(*args) # ни float, ни int else: raise TypeError("Amount must be float or int, not %s" % \ type(amount)) def sum_string(amount, gender, items=None): """ Get sum in words @param amount: amount of objects @type amount: C{int} or C{long} @param gender: gender of object (MALE, FEMALE or NEUTER) @type gender: C{int} @param items: variants of object in three forms: for one object, for two objects and for five objects @type items: 3-element C{sequence} of C{unicode} or just C{unicode} (three variants with delimeter ',') @return: in-words representation objects' amount @rtype: C{unicode} @raise TypeError: input parameters' check failed @raise ValueError: items isn't 3-element C{sequence} @raise ValueError: amount bigger than 10**11 @raise ValueError: amount is negative """ if isinstance(items, unicode): items = [i.strip() for i in items.split(',')] if items is None: items = (u"", u"", u"") utils.check_type('items', (list, tuple)) try: one_item, two_items, five_items = items except ValueError: raise ValueError("Items must be 3-element sequence") utils.check_type('amount', (int, long)) utils.check_type('gender', int) utils.check_type('one_item', unicode) utils.check_type('two_items', unicode) utils.check_type('five_items', unicode) utils.check_positive('amount') if amount == 0: return u"ноль %s" % five_items into = u'' tmp_val = amount # единицы into, tmp_val = _sum_string_fn(into, tmp_val, gender, items) # тысячи into, tmp_val = _sum_string_fn(into, tmp_val, FEMALE, (u"тысяча", u"тысячи", u"тысяч")) # миллионы into, tmp_val = _sum_string_fn(into, tmp_val, MALE, (u"миллион", u"миллиона", u"миллионов")) # миллиарды into, tmp_val = _sum_string_fn(into, tmp_val, MALE, (u"миллиард", u"миллиарда", u"миллиардов")) if tmp_val == 0: return into else: raise ValueError("Cannot operand with numbers bigger than 10**11") def _sum_string_fn(into, tmp_val, gender, items=None): """ Make in-words representation of single order @param into: in-words representation of lower orders @type into: C{unicode} @param tmp_val: temporary value without lower orders @type tmp_val: C{int} or C{long} @param gender: gender (MALE, FEMALE or NEUTER) @type gender: C{int} @param items: variants of objects @type items: 3-element C{sequence} of C{unicode} @return: new into and tmp_val @rtype: C{tuple} @raise TypeError: input parameters' check failed @raise ValueError: tmp_val is negative """ if items is None: items = (u"", u"", u"") one_item, two_items, five_items = items utils.check_type('into', unicode) utils.check_type('tmp_val', (int, long)) utils.check_type('gender', int) utils.check_type('one_item', unicode) utils.check_type('two_items', unicode) utils.check_type('five_items', unicode) utils.check_positive('tmp_val') if tmp_val == 0: return into, tmp_val rest = rest1 = end_word = None words = [] rest = tmp_val % 1000 tmp_val = tmp_val / 1000 if rest == 0: # последние три знака нулевые if into == u"": into = u"%s " % five_items return into, tmp_val # начинаем подсчет с rest end_word = five_items # сотни words.append(HUNDREDS[rest / 100]) # десятки rest = rest % 100 rest1 = rest / 10 # особый случай -- tens=1 tens = rest1 == 1 and TENS[rest] or TENS[rest1] words.append(tens) # единицы if rest1 < 1 or rest1 > 1: amount = rest % 10 end_word = choose_plural(amount, items) words.append(ONES[amount][gender-1]) words.append(end_word) # добавляем то, что уже было words.append(into) # убираем пустые подстроки words = filter(lambda x: len(x) > 0, words) # склеиваем и отдаем return u" ".join(words).strip(), tmp_val PKz"6ZTTpytils/translit.py# -*- coding: utf-8 -*- # -*- test-case-name: pytils.test.test_translit -*- # PyTils - simple processing for russian strings # Copyright (C) 2006-2007 Yury Yurevich # # http://gorod-omsk.ru/blog/pythy/projects/pytils/ # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation, version 2 # of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. """ Simple transliteration """ __id__ = __revision__ = "$Id: translit.py 63 2007-01-02 09:22:16Z the.pythy $" __url__ = "$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/translit.py $" import re from pytils import utils TRANSTABLE = ( (u"'", u"'"), (u'"', u'"'), (u"‘", u"'"), (u"’", u"'"), (u"«", u'"'), (u"»", u'"'), (u"–", u"-"), (u"…", u"..."), (u"№", u"#"), ## верхний регистр # трехбуквенные замены (u"Щ", u"Sch"), # при замене русский->английский будет первая замена, # т.е. Sch # а вот если английский->русский, то вариант SCH и Sch -- # оба пройдут (u"Щ", u"SCH"), # двухбуквенные замены (u"Ё", u"Yo"), (u"Ё", u"YO"), (u"Ж", u"Zh"), (u"Ж", u"ZH"), (u"Ц", u"Ts"), (u"Ц", u"TS"), (u"Ч", u"Ch"), (u"Ч", u"CH"), (u"Ш", u"Sh"), (u"Ш", u"SH"), (u"Ы", u"Yi"), (u"Ы", u"YI"), (u"Ю", u"Yu"), (u"Ю", u"YU"), (u"Я", u"Ya"), (u"Я", u"YA"), # однобуквенные замены (u"А", u"A"), (u"Б", u"B"), (u"В", u"V"), (u"Г", u"G"), (u"Д", u"D"), (u"Е", u"E"), (u"З", u"Z"), (u"И", u"I"), (u"Й", u"J"), (u"К", u"K"), (u"Л", u"L"), (u"М", u"M"), (u"Н", u"N"), (u"О", u"O"), (u"П", u"P"), (u"Р", u"R"), (u"С", u"S"), (u"Т", u"T"), (u"У", u"U"), (u"Ф", u"F"), (u"Х", u"H"), (u"Э", u"E"), (u"Ъ", u"`"), (u"Ь", u"'"), ## нижний регистр # трехбуквенные замены (u"щ", u"sch"), # двухбуквенные замены (u"ё", u"yo"), (u"ж", u"zh"), (u"ц", u"ts"), (u"ч", u"ch"), (u"ш", u"sh"), (u"ы", u"yi"), (u"ю", u"yu"), (u"я", u"ya"), # однобуквенные замены (u"а", u"a"), (u"б", u"b"), (u"в", u"v"), (u"г", u"g"), (u"д", u"d"), (u"е", u"e"), (u"з", u"z"), (u"и", u"i"), (u"й", u"j"), (u"к", u"k"), (u"л", u"l"), (u"м", u"m"), (u"н", u"n"), (u"о", u"o"), (u"п", u"p"), (u"р", u"r"), (u"с", u"s"), (u"т", u"t"), (u"у", u"u"), (u"ф", u"f"), (u"х", u"h"), (u"э", u"e"), (u"ъ", u"`"), (u"ь", u"'"), # для полноты английского алфавит (в slugify) # дополняем английскими буквами, которых # не в парах (u"c", u"c"), (u"q", u"q"), (u"y", u"y"), (u"x", u"x"), (u"w", u"w"), (u"1", u"1"), (u"2", u"2"), (u"3", u"3"), (u"4", u"4"), (u"5", u"5"), (u"6", u"6"), (u"7", u"7"), (u"8", u"8"), (u"9", u"9"), (u"0", u"0"), ) #: Translation table RU_ALPHABET = [x[0] for x in TRANSTABLE] #: Russian alphabet that we can translate EN_ALPHABET = [x[1] for x in TRANSTABLE] #: English alphabet that we can detransliterate ALPHABET = RU_ALPHABET + EN_ALPHABET #: Alphabet that we can (de)transliterate def translify(in_string): """ Translify russian text @param in_string: input string @type in_string: C{unicode} @return: transliterated string @rtype: C{str} @raise TypeError: when in_string is not C{unicode} @raise ValueError: when string doesn't transliterate completely """ utils.check_type('in_string', unicode) translit = in_string for symb_in, symb_out in TRANSTABLE: translit = translit.replace(symb_in, symb_out) try: translit = str(translit) except UnicodeEncodeError: raise ValueError("Unicode string doesn't transliterate completely, " + \ "is it russian?") return translit def detranslify(in_string): """ Detranslify @param in_string: input string @type in_string: C{basestring} @return: detransliterated string @rtype: C{str} @raise TypeError: when in_string neither C{str}, no C{unicode} @raise ValueError: if in_string is C{str}, but it isn't ascii """ utils.check_type('in_string', basestring) # в unicode try: russian = unicode(in_string) except UnicodeDecodeError: raise ValueError("We expects when in_string is str type," + \ "it is an ascii, but now it isn't. Use unicode " + \ "in this case.") for symb_out, symb_in in TRANSTABLE: russian = russian.replace(symb_in, symb_out) return russian def slugify(in_string): """ Prepare string for slug (i.e. URL or file/dir name) @param in_string: input string @type in_string: C{basestring} @return: slug-string @rtype: C{str} @raise TypeError: when in_string isn't C{unicode} or C{str} @raise ValueError: if in_string is C{str}, but it isn't ascii """ utils.check_type('in_string', basestring) try: u_in_string = unicode(in_string).lower() except UnicodeDecodeError: raise ValueError("We expects when in_string is str type," + \ "it is an ascii, but now it isn't. Use unicode " + \ "in this case.") # convert & to "and" u_in_string = re.sub('\&\;|\&', ' and ', u_in_string) # replace spaces by hyphen u_in_string = re.sub('[-\s]+', '-', u_in_string) # remove symbols that not in alphabet u_in_string = u''.join([symb for symb in u_in_string if symb in ALPHABET]) # translify it out_string = translify(u_in_string) # remove non-alpha return re.sub('[^\w\s-]', '', out_string).strip().lower() def dirify(in_string): """ Alias for L{slugify} """ slugify(in_string) PKz"6d"6pytils/utils.py# -*- coding: utf-8 -*- # -*- test-case-name: pytils.test.test_utils -*- # PyTils - simple processing for russian strings # Copyright (C) 2006-2007 Yury Yurevich # # http://gorod-omsk.ru/blog/pythy/projects/pytils/ # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation, version 2 # of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. """ Misc utils for internal use """ __id__ = __revision__ = "$Id: utils.py 63 2007-01-02 09:22:16Z the.pythy $" __url__ = "$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/utils.py $" import sys def provide_unicode(stext, encoding, default=u"неизвестно"): """ Provide Unicode from text @param stext: text @type stext: C{str} @param encoding: encoding if input text @type encoding: C{str} @return: C{unicode} """ try: utext = str(stext).decode(encoding) except UnicodeDecodeError, err: utext = default % {'error': err, 'value': u""} return utext def provide_str(utext, encoding, default="unknown"): """ Provide text from Unicode @param utext: unicode text @type utext: C{unicode} @param encoding: encoding of output text @type encoding: C{str} @return: C{str} """ try: stext = unicode(utext).encode(encoding) except UnicodeEncodeError, err: stext = default % {'error': err, 'value': ""} return stext def get_value_by_name(variable_name, depth=1): """ Return value of variable by it's name @param variable_name: name of variable @type variable_name: C{str} @param depth: stack depth @type depth: C{int} @raise RuntimeError: when unable to fetch variable """ try: variable_value = sys._getframe(depth).f_locals[variable_name] except KeyError: raise RuntimeError("Unable to fetch variable %s (depth %d)" % \ (variable_name, depth)) return variable_value def check_type(variable_name, typ): """ Checks type of variable @param variable_name: name of variable @type variable_name: C{str} @param typ: type checking for @type typ: C{type} or C{tuple} of types @return: None when check successful @raise TypeError: check failed """ variable_value = get_value_by_name(variable_name, 2) if not isinstance(variable_value, typ): raise TypeError("%s must be %s, not %s" % \ (variable_name, str(typ), type(variable_value))) def check_length(variable_name, length): """ Checks length of variable's value @param variable_name: name of variable @type variable_name: C{str} @param length: length checking for @type length: C{int} @return: None when check successful @raise ValueError: check failed """ variable_value = get_value_by_name(variable_name, 2) _length = len(variable_value) if _length != length: raise ValueError("%s's length must be %d, but it %d" % \ (variable_name, length, _length)) def check_positive(variable_name, strict=False): """ Checks if variable is positive @param variable_name: name of variable @type variable_name: C{str} @return: None when check successful @raise ValueError: check failed """ variable_value = get_value_by_name(variable_name, 2) if not strict and variable_value < 0: raise ValueError("%s must be positive or zero, not %s" % \ (variable_name, str(variable_value))) if strict and variable_value <= 0: raise ValueError("%s must be positive, not %s" % \ (variable_name, str(variable_value))) PKt[6م  pytils/__init__.pyc; [JEc@sdZdZZdZdddddgZdZd Zd Zd eeefZd Z d Z e egZ xFeD]>Z e de eedgZe ie eiquWee Zee jodeefZndS(s' Simple processing for russian strings s4$Id: __init__.py 74 2007-02-27 15:11:35Z the.pythy $sH$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/__init__.py $snumeralsdtstranslitstestsutilsiiis%d.%d.%ds20070227cCs?|idddjotSn|ididdSdS(s1Returns date of last update (extract from __id__)s$ssIdis-N(s id_stringsreplacesREL_DATEssplit(s id_string((s-build/bdist.linux-i686/egg/pytils/__init__.pys_get_svn_date_from_id#sspytils.spytilss%s-svn%sN(s__doc__s__id__s __revision__s__url__s__all__s VERSION_MAJORs VERSION_MINORs VERSION_TINYsVERSIONsREL_DATEs_get_svn_date_from_ids _module_datess _module_names __import__sglobalsslocalss_imported_modulesappendsmaxsSVN_DATE(s_get_svn_date_from_ids __revision__s__all__s VERSION_MAJORs VERSION_TINYsSVN_DATEs__url__sVERSIONsREL_DATEs__id__s_imported_modules _module_names _module_datess VERSION_MINOR((s-build/bdist.linux-i686/egg/pytils/__init__.pys?s(     PKt[6Ϲ< pytils/dt.pyc; $Ec@sdZdZZdZdkZdklZlZhdddf<dd d fd?fd@dAdAfdBdCdDfdEdFdGfdHdIdGffZdedJZdKeeedLZdS(Ms Russian dates without locales s.$Id: dt.py 63 2007-01-02 09:22:16Z the.pythy $sB$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/dt.py $N(snumeralsutilsiu вчераu завтраiuпозавчераuпослезавтраuденьuдняuднейuчасuчасаu часовu минутуu минутыu минутu черезu назадuянвu январьu январяuфевuфевральuфевраляuмарuмартu мартаuапрu апрельu апреляuмайuмаяuиюнuиюньuиюняuиюлuиюльuиюляuавгu августuавгустаuсенuсентябрьuсентябряuоктuоктябрьuоктябряuнояu ноябрьu ноябряuдекuдекабрьuдекабряuпнuпонедельникuвтuвторникuсрu средаu средуuчтuчетвергuптuпятницаuпятницуuсбuсубботаuсубботуuвскuвоскресеньеcCs*t}|tjot}tii}ntidt t tiftidt t tiftidt ti ddtt |ti otii|}nt |ti otii|}n||}|id|i}t t|}t t|d}t t|d}t t|d} ||j}g}g}g}| }|| d }|id |ti|t f|i||id |ti|t!f|i||d jo|o |id ||d }|id |ti|t#f|i||d jo|o |id|}x,|o |d o|i%|i%qhWx2|o |d o|i%d|i%dqWt&|t(|}|| }|| } x6| o | d o"| i%|i%|d 8}qWdi+|}|d jo|o|o|d}|p|}|odt/|fpd|t0f} |djo| o|odpd} t3i4|t} | o.|o'|d jo|o| d p| d}| o| p |p| }|SdS(sL Represents distance of time in words @param from_time: source time (in seconds from epoch) @type from_time: C{int}, C{float} or C{datetime.datetime} @param accuracy: level of accuracy (1..3), default=1 @type accuracy: C{int} @param to_time: target time (in seconds from epoch), default=None translates to current time @type to_time: C{int}, C{float} or C{datetime.datetime} @return: distance of time in words @rtype: unicode @raise TypeError: input parameters' check failed @raise ValueError: accuracy is lesser or equal zero s from_timesto_timesaccuracysstrictiQf60.0f3600.0f86400.0iu%d %siuчасi<u минутуiiu u%s %su)менее чем через минутуu"менее минуты назадN(8sFalsescurrentsto_timesNonesTruesdatetimesnowsutilss check_typesintsfloatscheck_positives isinstances from_times fromtimestampsdt_deltasdaysssecondss differencesabss seconds_origs minutes_origs hours_origs days_origs in_futureswordssvaluess alternativesshourssappendsnumerals choose_plurals DAY_VARIANTSs HOUR_VARIANTSsminutessMINUTE_VARIANTSs real_wordsspopsminsaccuracyslenslimits real_valuessjoinsreal_strs alter_strs _result_strs PREFIX_INs SUFFIX_AGOs result_strszero_strsDAY_ALTERNATIVESsgetsday_alternativess alternate_days final_str(s from_timesaccuracysto_timesdt_deltas _result_strs alternativess alter_strslimits in_futures result_strs real_valuessday_alternativess days_origszero_strscurrents real_wordss final_strsreal_strs seconds_origshourss minutes_origswordss differences alternate_daysdayss hours_origsvaluessminutes((s'build/bdist.linux-i686/egg/pytils/dt.pysdistance_of_time_in_wordsPsx   # # !# !      % ()7u%d.%m.%Yc Cs+|tjotii}ntidtitiftidt|odpd}|odpd}|i dt |id}|i dt |i|}|i dt|idd}|i d t|id|}|id }|i|}|id }|Sd S( s_ Russian strftime without locale @param format: strftime format, default=u'%d.%m.%Y' @type format: C{unicode} @param date: date value, default=None translates to today @type date: C{datetime.date} or C{datetime.datetime} @return: strftime string @rtype: unicode @raise TypeError: input parameters' check failed sdatesformatiiu%aiu%Au%bu%Bsutf-8N(sdatesNonesdatetimestodaysutilss check_typesunicodes inflectedsmidxs inflected_daysdidxsformatsreplaces DAY_NAMESsweekdays MONTH_NAMESsmonthsencodess_formatsstrftimess_ressdecodesu_res( sformatsdates inflecteds inflected_daysmidxss_formatss_ressu_ressdidx((s'build/bdist.linux-i686/egg/pytils/dt.pys ru_strftimes   !!(s__doc__s__id__s __revision__s__url__sdatetimespytilssnumeralsutilssDAY_ALTERNATIVESs DAY_VARIANTSs HOUR_VARIANTSsMINUTE_VARIANTSs PREFIX_INs SUFFIX_AGOs MONTH_NAMESs DAY_NAMESsNonesdistance_of_time_in_wordssFalses ru_strftime(s MONTH_NAMESs __revision__s ru_strftimes PREFIX_INsutilssdatetimes__url__s HOUR_VARIANTSs__id__s DAY_NAMESsDAY_ALTERNATIVESsnumeralsMINUTE_VARIANTSs SUFFIX_AGOsdistance_of_time_in_wordss DAY_VARIANTS((s'build/bdist.linux-i686/egg/pytils/dt.pys?s  $Z tPKt[6٪ r6r6pytils/numeral.pyc; $Ec @sdZdZZdZdklZdddfdddfdd d fd d d fd d d fdddfdddfdddfdddff Zhddddf<ddddf<ddd df<d!d"d"d"f<d#d$d$d$f<d%d&d&d&f<d'd(d(d(f<d)d*d*d*f<d+d,d,d,f<d-d.d.d.f<d?d@<dAdB<ddC<d!dD<d#dE<d%dF<d'dG<d)dH<d+dI<d-dJ '05' @param fvalue: input value @type fvalue: C{int}, C{long} or C{float} @param signs: maximum number of signs @type signs: C{int} or C{long} @return: remainder @rtype: C{str} @raise TypeError: fvalue neither C{int}, no C{float} @raise ValueError: fvalue is negative @raise ValueError: signs overflow sfvalues0s.iif10.0s%%0%ddshSigns overflow: I can't round only fractional part of %s to fit %s in %d signsN(sutilss check_typesintslongsfloatscheck_positives isinstancesfvaluesminssignsslens FRACTIONSsstrssplits remainders iremaindersorig_remaindersfactorsroundsformats ValueError(sfvaluessignssorig_remainders iremaindersformatsfactors remainder((s,build/bdist.linux-i686/egg/pytils/numeral.pys_get_float_remainder\s"    #cCs"tidttftidtidtttft|to:gi }|i dD]}||iqc~}n|ddjo|ddjo d}nU|dd jo0|dd jo|ddjp|dd jo d}nd }tidd ||Sd S(s0 Choose proper case depending on amount @param amount: amount of objects @type amount: C{int} or C{long} @param variants: variants (forms) of object in such form: (1 object, 2 objects, 5 objects). @type variants: 3-element C{sequence} of C{unicode} or C{unicode} (three variants with delimeter ',') @return: proper variant @rtype: C{unicode} @raise TypeError: amount isn't C{int}, variants isn't C{sequence} @raise ValueError: amount is negative @raise ValueError: variants' length lesser than 3 samountsvariantss,i iidi iiiiiN(sutilss check_typesintslongscheck_positivesliststuplesunicodes isinstancesvariantssappends_[1]ssplitsvsstripsamountsvariants check_length(samountsvariantssvariants_[1]sv((s,build/bdist.linux-i686/egg/pytils/numeral.pys choose_plurals :" D cCstidtttftidg}t|d}|i t t|ddddft |d}t|}|djp|oT|djot|djo|d9}n|i t |dd d d fnd i|Sd S(s Get string for money @param amount: amount of money @type amount: C{int}, C{long} or C{float} @param zero_for_kopeck: If false, then zero kopecks ignored @type zero_for_kopeck: C{bool} @return: in-words representation of money's amount @rtype: C{unicode} @raise TypeError: amount neither C{int}, no C{float} @raise ValueError: amount is negative samountiiu рубльu рубляu рублейii uкопейкаuкопейкиu копеекu N(sutilss check_typesintslongsfloatscheck_positivesptssroundsamountsappends sum_strings_get_float_remainders remainders iremainderszero_for_kopeckslensjoin(samountszero_for_kopecks remainders iremainderspts((s,build/bdist.linux-i686/egg/pytils/numeral.pysrubless (  cCs4tidttftidt||SdS(sI Integer in words @param amount: numeral @type amount: C{int} or C{long} @param gender: gender (MALE, FEMALE or NEUTER) @type gender: C{int} @return: in-words reprsentation of numeral @rtype: C{unicode} @raise TypeError: when amount is not C{int} @raise ValueError: amount is negative samountN(sutilss check_typesintslongscheck_positives sum_stringsamountsgender(samountsgender((s,build/bdist.linux-i686/egg/pytils/numeral.pys in_words_ints cCstidttidg}|itt|ddddft |}t t |d}|itt|dt|di|SdS(s Float in words @param amount: float numeral @type amount: C{float} @return: in-words reprsentation of float numeral @rtype: C{unicode} @raise TypeError: when amount is not C{float} @raise ValueError: when ammount is negative samountiu целаяu целыхiu N(sutilss check_typesfloatscheck_positivesptssappends sum_stringsintsamounts_get_float_remainders remainderslensstrssignss FRACTIONSsjoin(samounts_genders remainderssignsspts((s,build/bdist.linux-i686/egg/pytils/numeral.pysin_words_floats   #cCstid|tj otidt|tjp|tttfj ot dd|n|tjo |f}n ||f}t |tt fot|Sn5t |tot|Sntdt|dS(s Numeral in words @param amount: numeral @type amount: C{int}, C{long} or C{float} @param gender: gender (MALE, FEMALE or NEUTER) @type gender: C{int} @return: in-words reprsentation of numeral @rtype: C{unicode} raise TypeError: when amount not C{int} or C{float} raise ValueError: when amount is negative raise TypeError: when gender is not C{int} (and not None) raise ValueError: if gender isn't in (MALE, FEMALE, NEUTER) samountsgenders'Gender must be MALE, FEMALE or NEUTER, snot %ds#Amount must be float or int, not %sN(sutilsscheck_positivesgendersNones check_typesintsMALEsFEMALEsNEUTERs ValueErrorsamountsargss isinstanceslongs in_words_intsfloatsin_words_floats TypeErrorstype(samountsgendersargs((s,build/bdist.linux-i686/egg/pytils/numeral.pysin_wordss $   c Cst|to:gi} |idD]}| |iq'~ }n|tjodddf}nt i dt t fy|\}}}Wntj otdnXt i dttft i dtt i dtt i dtt i d tt id|d jo d |Snd}|}t||||\}}t||td d df\}}t||tdddf\}}t||tdddf\}}|d jo|Sn tddS(s Get sum in words @param amount: amount of objects @type amount: C{int} or C{long} @param gender: gender of object (MALE, FEMALE or NEUTER) @type gender: C{int} @param items: variants of object in three forms: for one object, for two objects and for five objects @type items: 3-element C{sequence} of C{unicode} or just C{unicode} (three variants with delimeter ',') @return: in-words representation objects' amount @rtype: C{unicode} @raise TypeError: input parameters' check failed @raise ValueError: items isn't 3-element C{sequence} @raise ValueError: amount bigger than 10**11 @raise ValueError: amount is negative s,usitemss Items must be 3-element sequencesamountsgendersone_items two_itemss five_itemsiu ноль %su тысячаu тысячиu тысячuмиллионuмиллионаuмиллионовuмиллиардuмиллиардаuмиллиардовs.Cannot operand with numbers bigger than 10**11N(s isinstancesitemssunicodesappends_[1]ssplitsisstripsNonesutilss check_typesliststuplesone_items two_itemss five_itemss ValueErrorsintslongscheck_positivesamountsintostmp_vals_sum_string_fnsgendersFEMALEsMALE( samountsgendersitemss five_itemssone_itemstmp_valsintos two_itemssis_[1]((s,build/bdist.linux-i686/egg/pytils/numeral.pys sum_string,s<:        c Cs|tjodddf}n|\}} }tidttidtt ftidttidttidttidtti d|djo||fSnt}}} g} |d }|d }|djo)|djod |}n||fSn|} | it|d |d }|d }|d jot|pt|}| i||d jp |d jo6|d } t| |} | it| |d n| i| | i|td| } di| i|fSdS(s, Make in-words representation of single order @param into: in-words representation of lower orders @type into: C{unicode} @param tmp_val: temporary value without lower orders @type tmp_val: C{int} or C{long} @param gender: gender (MALE, FEMALE or NEUTER) @type gender: C{int} @param items: variants of objects @type items: 3-element C{sequence} of C{unicode} @return: new into and tmp_val @rtype: C{tuple} @raise TypeError: input parameters' check failed @raise ValueError: tmp_val is negative usintostmp_valsgendersone_items two_itemss five_itemsiiu%s idi icCst|djS(Ni(slensx(sx((s,build/bdist.linux-i686/egg/pytils/numeral.pyssu N(sitemssNonesone_items two_itemss five_itemssutilss check_typesunicodesintslongscheck_positivestmp_valsintosrestsrest1send_wordswordssappendsHUNDREDSsTENSstenssamounts choose_pluralsONESsgendersfiltersjoinsstrip( sintostmp_valsgendersitemssone_items five_itemssrestsrest1stenss two_itemsswordssend_wordsamount((s,build/bdist.linux-i686/egg/pytils/numeral.pys_sum_string_fnmsF         "    N(s__doc__s__id__s __revision__s__url__spytilssutilss FRACTIONSsONESsTENSsHUNDREDSsMALEsFEMALEsNEUTERs_get_float_remainders choose_pluralsFalsesrubless in_words_intsin_words_floatsNonesin_wordss sum_strings_sum_string_fn(s FRACTIONSsrubless __revision__s in_words_intsNEUTERs choose_pluralsutilssin_words_floatsHUNDREDSs__url__s_sum_string_fnsONESs__id__sFEMALEsin_wordssTENSs_get_float_remaindersMALEs sum_string((s,build/bdist.linux-i686/egg/pytils/numeral.pys?s$  r `  / % #   ' APKt[6[:Wpytils/translit.pyc; $Ecd@s5dZdZZdZdkZdklZddfddfddfddfd dfd dfd d fd dfddfddfddfddfddfddfddfddfddfddfddfd d!fd d"fd#d$fd#d%fd&d'fd&d(fd)d*fd)d+fd,d-fd.d/fd0d1fd2d3fd4d5fd6d7fd8d9fd:d;fd<d=fd>d?fd@dAfdBdCfdDdEfdFdGfdHdIfdJdKfdLdMfdNdOfdPdQfdRdSfdTdUfdVd7fdWdXfdYdfdZd[fd\d]fd^d_fd`dafdbdcfdddefdfdgfdhdifdjdkfdldmfdndofdpdqfdrdsfdtdufdvdwfdxdyfdzd{fd|d}fd~dfddfddfddfddfddfddfddfddfddfddfddfddwfddXfddfddfddfddfddfddfddfddfddfddfddfddfddfddfddfddffcZgiZ eD]Z e e dq[ Z giZ eD]Z e e dq[ Z e e Z dZdZdZdZdS(s Simple transliteration s4$Id: translit.py 63 2007-01-02 09:22:16Z the.pythy $sH$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/translit.py $N(sutilsu'u"u‘u’u«u»u–u-u…u...u№u#uЩuSchuSCHuЁuYouYOuЖuZhuZHuЦuTsuTSuЧuChuCHuШuShuSHuЫuYiuYIuЮuYuuYUuЯuYauYAuАuAuБuBuВuVuГuGuДuDuЕuEuЗuZuИuIuЙuJuКuKuЛuLuМuMuНuNuОuOuПuPuРuRuСuSuТuTuУuUuФuFuХuHuЭuЪu`uЬuщuschuёuyouжuzhuцutsuчuchuшushuыuyiuюuyuuяuyauаuauбubuвuvuгuguдuduеueuзuzuиuiuйujuкukuлuluмumuнunuоuouпupuрuruсusuтutuуuuuфufuхuhuэuъuьucuquyuxuwu1u2u3u4u5u6u7u8u9u0iicCs}tidt|}x&tD]\}}|i||}qWyt |}Wn#t j ot ddnX|SdS(s Translify russian text @param in_string: input string @type in_string: C{unicode} @return: transliterated string @rtype: C{str} @raise TypeError: when in_string is not C{unicode} @raise ValueError: when string doesn't transliterate completely s in_strings1Unicode string doesn't transliterate completely, sis it russian?N( sutilss check_typesunicodes in_stringstranslits TRANSTABLEssymb_inssymb_outsreplacesstrsUnicodeEncodeErrors ValueError(s in_stringssymb_inssymb_outstranslit((s-build/bdist.linux-i686/egg/pytils/translit.pys translifys  cCs{tidtyt|}Wn'tj otdddnXx&tD]\}}|i ||}qQW|SdS(s Detranslify @param in_string: input string @type in_string: C{basestring} @return: detransliterated string @rtype: C{str} @raise TypeError: when in_string neither C{str}, no C{unicode} @raise ValueError: if in_string is C{str}, but it isn't ascii s in_strings&We expects when in_string is str type,s.it is an ascii, but now it isn't. Use unicode s in this case.N( sutilss check_types basestringsunicodes in_stringsrussiansUnicodeDecodeErrors ValueErrors TRANSTABLEssymb_outssymb_insreplace(s in_stringssymb_outssymb_insrussian((s-build/bdist.linux-i686/egg/pytils/translit.pys detranslifys  cCstidtyt|i}Wn'tj otdddnXt i dd|}t i dd|}d i gi }|D]!}|tjo||qq~}t|}t i d d |iiSd S( s4 Prepare string for slug (i.e. URL or file/dir name) @param in_string: input string @type in_string: C{basestring} @return: slug-string @rtype: C{str} @raise TypeError: when in_string isn't C{unicode} or C{str} @raise ValueError: if in_string is C{str}, but it isn't ascii s in_strings&We expects when in_string is str type,s.it is an ascii, but now it isn't. Use unicode s in this case.s \&\;|\&s and s[-\s]+s-us[^\w\s-]sN(sutilss check_types basestringsunicodes in_stringslowers u_in_stringsUnicodeDecodeErrors ValueErrorsressubsjoinsappends_[1]ssymbsALPHABETs translifys out_stringsstrip(s in_stringssymbs u_in_strings_[1]s out_string((s-build/bdist.linux-i686/egg/pytils/translit.pysslugifys A cCst|dS(s Alias for L{slugify} N(sslugifys in_string(s in_string((s-build/bdist.linux-i686/egg/pytils/translit.pysdirifys(s__doc__s__id__s __revision__s__url__srespytilssutilss TRANSTABLEsappends_[1]sxs RU_ALPHABETs EN_ALPHABETsALPHABETs translifys detranslifysslugifysdirify(s TRANSTABLEs_[1]s __revision__s translifysALPHABETsutilssdirifys EN_ALPHABETs__url__sres__id__s RU_ALPHABETsxs detranslifysslugify((s-build/bdist.linux-i686/egg/pytils/translit.pys?s   u++    PKt[6Txpytils/utils.pyc; $Ec@sedZdZZdZdkZddZddZdd Zd Zd Z e d Z dS( s Misc utils for internal use s1$Id: utils.py 63 2007-01-02 09:22:16Z the.pythy $sE$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/utils.py $NuнеизвестноcCsUyt|i|}Wn1tj o%}|hd|<dd<}nX|SdS(s Provide Unicode from text @param stext: text @type stext: C{str} @param encoding: encoding if input text @type encoding: C{str} @return: C{unicode} serrorsvalueuN(sstrsstextsdecodesencodingsutextsUnicodeDecodeErrorserrsdefault(sstextsencodingsdefaultserrsutext((s*build/bdist.linux-i686/egg/pytils/utils.pysprovide_unicodes !sunknowncCsUyt|i|}Wn1tj o%}|hd|<dd<}nX|SdS(s Provide text from Unicode @param utext: unicode text @type utext: C{unicode} @param encoding: encoding of output text @type encoding: C{str} @return: C{str} serrorsvaluesN(sunicodesutextsencodesencodingsstextsUnicodeEncodeErrorserrsdefault(sutextsencodingsdefaultserrsstext((s*build/bdist.linux-i686/egg/pytils/utils.pys provide_str.s !icCsNyti|i|}Wn)tj otd||fnX|SdS(s Return value of variable by it's name @param variable_name: name of variable @type variable_name: C{str} @param depth: stack depth @type depth: C{int} @raise RuntimeError: when unable to fetch variable s&Unable to fetch variable %s (depth %d)N(ssyss _getframesdepthsf_localss variable_namesvariable_valuesKeyErrors RuntimeError(s variable_namesdepthsvariable_value((s*build/bdist.linux-i686/egg/pytils/utils.pysget_value_by_nameAs cCsMt|d}t|| o)td|t|t|fndS(s  Checks type of variable @param variable_name: name of variable @type variable_name: C{str} @param typ: type checking for @type typ: C{type} or C{tuple} of types @return: None when check successful @raise TypeError: check failed is%s must be %s, not %sN(sget_value_by_names variable_namesvariable_values isinstancestyps TypeErrorsstrstype(s variable_namestypsvariable_value((s*build/bdist.linux-i686/egg/pytils/utils.pys check_typeUs cCsIt|d}t|}||jotd|||fndS(s Checks length of variable's value @param variable_name: name of variable @type variable_name: C{str} @param length: length checking for @type length: C{int} @return: None when check successful @raise ValueError: check failed is!%s's length must be %d, but it %dN(sget_value_by_names variable_namesvariable_valueslens_lengthslengths ValueError(s variable_nameslengthsvariable_values_length((s*build/bdist.linux-i686/egg/pytils/utils.pys check_lengthis   cCs|t|d}| o |djo td|t|fn|o |djo td|t|fndS(s Checks if variable is positive @param variable_name: name of variable @type variable_name: C{str} @return: None when check successful @raise ValueError: check failed iis#%s must be positive or zero, not %ss%s must be positive, not %sN(sget_value_by_names variable_namesvariable_valuesstricts ValueErrorsstr(s variable_namesstrictsvariable_value((s*build/bdist.linux-i686/egg/pytils/utils.pyscheck_positive~s  ( s__doc__s__id__s __revision__s__url__ssyssprovide_unicodes provide_strsget_value_by_names check_types check_lengthsFalsescheck_positive( ssyss __revision__sprovide_unicodes check_typesget_value_by_names provide_strscheck_positives check_lengths__url__s__id__((s*build/bdist.linux-i686/egg/pytils/utils.pys?s       PKz"6PsLNNpytils/templatetags/__init__.py# -*- coding: utf-8 -*- # PyTils - simple processing for russian strings # Copyright (C) 2006-2007 Yury Yurevich # # http://gorod-omsk.ru/blog/pythy/projects/pytils/ # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation, version 2 # of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. """ Pytils templatetags for Django web-framework """ __id__ = __revision__ = "$Id: __init__.py 63 2007-01-02 09:22:16Z the.pythy $" __url__ = "$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/templatetags/__init__.py $" PKMS6|7++ pytils/templatetags/pytils_dt.py# -*- coding: utf-8 -*- # -*- test-case-name: pytils.test.templatetags.test_dt -*- # PyTils - simple processing for russian strings # Copyright (C) 2006-2007 Yury Yurevich # # http://gorod-omsk.ru/blog/pythy/projects/pytils/ # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation, version 2 # of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. """ pytils.dt templatetags for Django web-framework """ __id__ = __revision__ = "$Id: pytils_dt.py 70 2007-02-19 03:42:32Z the.pythy $" __url__ = "$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/templatetags/pytils_dt.py $" import time from django import template, conf from pytils import dt, utils register = template.Library() #: Django template tag/filter registrator encoding = conf.settings.DEFAULT_CHARSET #: Current charset (sets in Django project's settings) debug = conf.settings.DEBUG #: Debug mode (sets in Django project's settings) show_value = getattr(conf.settings, 'PYTILS_SHOW_VALUES_ON_ERROR', False) #: Show values on errors (sets in Django project's settings) # Если отладка, то показываем 'unknown+сообщение об ошибке'. # Если отладка выключена, то можно чтобы при ошибках показывалось # значение, переданное фильтру (PYTILS_SHOW_VALUES_ON_ERROR=True) # либо пустая строка. if debug: default_value = "unknown: %(error)s" default_uvalue = u"unknown: %(error)s" elif show_value: default_value = "%(value)s" default_uvalue = u"%(value)s" else: default_value = "" default_uvalue = u"" # -- filters -- def distance_of_time(from_time, accuracy=1): """ Display distance of time from current time. Parameter is an accuracy level (deafult is 1). Value must be numeral (i.e. time.time() result) or datetime.datetime (i.e. datetime.datetime.now() result). Examples:: {{ some_time|distance_of_time }} {{ some_dtime|distance_of_time:2 }} """ try: res = utils.provide_str( dt.distance_of_time_in_words(from_time, accuracy), encoding, default=default_value) except Exception, err: # because filter must die silently try: default_distance = "%s seconds" % str(int(time.time() - from_time)) except Exception: default_distance = "" res = default_value % {'error': err, 'value': default_distance} return res def ru_strftime(date, format="%d.%m.%Y", inflected_day=False): """ Russian strftime, formats date with given format. Value is a date (supports datetime.date and datetime.datetime), parameter is a format (string). For explainings about format, see documentation for original strftime: http://docs.python.org/lib/module-time.html Examples:: {{ some_date|ru_strftime:"%d %B %Y, %A" }} """ try: uformat = utils.provide_unicode(format, encoding, default=u"%d.%m.%Y") ures = dt.ru_strftime(uformat, date, inflected=True, inflected_day=inflected_day) res = utils.provide_str(ures, encoding) except Exception, err: # because filter must die silently try: default_date = date.strftime(format) except Exception: default_date = str(date) res = default_value % {'error': err, 'value': default_date} return res def ru_strftime_inflected(date, format="%d.%m.%Y", inflected_day=True): """ Russian strftime with inflected day, formats date with given format (similar to ru_strftime), also inflects day in proper form. Examples:: {{ some_date|ru_strftime_inflected:"in %A (%d %B %Y)" """ return ru_strftime(date, format, inflected_day) # -- register filters register.filter('distance_of_time', distance_of_time) register.filter('ru_strftime', ru_strftime) register.filter('ru_strftime_inflected', ru_strftime_inflected) PKMS6ܾdLL%pytils/templatetags/pytils_numeral.py# -*- coding: utf-8 -*- # -*- test-case-name: pytils.test.templatetags.test_numeral -*- # PyTils - simple processing for russian strings # Copyright (C) 2006-2007 Yury Yurevich # # http://gorod-omsk.ru/blog/pythy/projects/pytils/ # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation, version 2 # of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. """ pytils.numeral templatetags for Django web-framework """ __id__ = __revision__ = "$Id: pytils_numeral.py 70 2007-02-19 03:42:32Z the.pythy $" __url__ = "$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/templatetags/pytils_numeral.py $" from django import template, conf from pytils import numeral, utils register = template.Library() #: Django template tag/filter registrator encoding = conf.settings.DEFAULT_CHARSET #: Current charset (sets in Django project's settings) debug = conf.settings.DEBUG #: Debug mode (sets in Django project's settings) show_value = getattr(conf.settings, 'PYTILS_SHOW_VALUES_ON_ERROR', False) #: Show values on errors (sets in Django project's settings) # Если отладка, то показываем 'unknown+сообщение об ошибке'. # Если отладка выключена, то можно чтобы при ошибках показывалось # значение, переданное фильтру (PYTILS_SHOW_VALUES_ON_ERROR=True) # либо пустая строка. if debug: default_value = "unknown: %(error)s" default_uvalue = u"unknown: %(error)s" elif show_value: default_value = "%(value)s" default_uvalue = u"%(value)s" else: default_value = "" default_uvalue = u"" # -- filters def choose_plural(amount, variants): """ Choose proper form for plural. Value is a amount, parameters are forms of noun. Forms are variants for 1, 2, 5 nouns. It may be tuple of elements, or string where variants separates each other by comma. Examples:: {{ some_int|choose_plural:"пример,примера,примеров" }} """ try: if isinstance(variants, str): uvariants = utils.provide_unicode(variants, encoding, default_value) else: uvariants = [utils.provide_unicode(v, encoding, default_uvalue) for v in variants] res = utils.provide_str( numeral.choose_plural(amount, uvariants), encoding, default=default_value ) except Exception, err: # because filter must die silently try: default_variant = variants except Exception: default_variant = "" res = default_value % {'error': err, 'value': default_variant} return res def rubles(amount, zero_for_kopeck=False): """Converts float value to in-words representation (for money)""" try: res = utils.provide_str( numeral.rubles(amount, zero_for_kopeck), encoding, default=default_value ) except Exception, err: # because filter must die silently res = default_value % {'error': err, 'value': str(amount)} return res def in_words(amount, gender=None): """ In-words representation of amount. Parameter is a gender: MALE, FEMALE or NEUTER Examples:: {{ some_int|in_words }} {{ some_other_int|in_words:FEMALE }} """ try: res = utils.provide_str( numeral.in_words(amount, getattr(numeral, str(gender), None)), encoding, default=default_value ) except Exception, err: # because filter must die silently res = default_value % {'error': err, 'value': str(amount)} return res # -- register filters register.filter('choose_plural', choose_plural) register.filter('rubles', rubles) register.filter('in_words', in_words) # -- tags def sum_string(amount, gender, items): """ in_words and choose_plural in a one flask Makes in-words representation of value with choosing correct form of noun. First parameter is an amount of objects. Second is a gender (MALE, FEMALE, NEUTER). Third is a variants of forms for object name. Examples:: {% sum_string some_int MALE "пример,примера,примеров" %} {% sum_string some_other_int FEMALE "задача,задачи,задач" %} """ try: uitems = [utils.provide_unicode(i, encoding, default_uvalue) for i in items] res = utils.provide_str( numeral.sum_string(amount, getattr(numeral, str(gender), None), uitems), encoding, default=default_value ) except Exception, err: # because tag's renderer must die silently res = default_value % {'error': err, 'value': str(amount)} return res # -- register tags register.simple_tag(sum_string) PKMS6͸ &pytils/templatetags/pytils_translit.py# -*- coding: utf-8 -*- # -*- test-case-name: pytils.test.templatetags.test_translit -*- # PyTils - simple processing for russian strings # Copyright (C) 2006-2007 Yury Yurevich # # http://gorod-omsk.ru/blog/pythy/projects/pytils/ # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation, version 2 # of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. """ pytils.translit templatetags for Django web-framework """ __id__ = __revision__ = "$Id: pytils_translit.py 70 2007-02-19 03:42:32Z the.pythy $" __url__ = "$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/templatetags/pytils_translit.py $" from django import template, conf from pytils import translit, utils register = template.Library() #: Django template tag/filter registrator encoding = conf.settings.DEFAULT_CHARSET #: Current charset (sets in Django project's settings) debug = conf.settings.DEBUG #: Debug mode (sets in Django project's settings) show_value = getattr(conf.settings, 'PYTILS_SHOW_VALUES_ON_ERROR', False) #: Show values on errors (sets in Django project's settings) # Если отладка, то показываем 'unknown+сообщение об ошибке'. # Если отладка выключена, то можно чтобы при ошибках показывалось # значение, переданное фильтру (PYTILS_SHOW_VALUES_ON_ERROR=True) # либо пустая строка. if debug: default_value = "unknown: %(error)s" default_uvalue = u"unknown: %(error)s" elif show_value: default_value = "%(value)s" default_uvalue = u"%(value)s" else: default_value = "" default_uvalue = u"" # -- filters -- def translify(stext): """Translify russian text""" try: res = translit.translify( utils.provide_unicode( stext, encoding, default=default_value )) except Exception, err: # because filter must die silently res = default_value % {'error': err, 'value': stext} return res def detranslify(stext): """Detranslify russian text""" try: res = utils.provide_str( translit.detranslify(stext), encoding, default=default_uvalue) except Exception, err: # because filter must die silently res = default_value % {'error': err, 'value': stext} return res def slugify(stext): """Make slug from (russian) text""" try: res = translit.slugify( utils.provide_unicode( stext, encoding, default=default_value )) except Exception, err: # because filter must die silently res = default_value % {'error': err, 'value': stext} return res # -- register filters register.filter('translify', translify) register.filter('detranslify', detranslify) register.filter('slugify', slugify) PKt[6 pytils/templatetags/__init__.pyc; $Ec@sdZdZZdZdS(s. Pytils templatetags for Django web-framework s4$Id: __init__.py 63 2007-01-02 09:22:16Z the.pythy $sU$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/templatetags/__init__.py $N(s__doc__s__id__s __revision__s__url__(s__url__s __revision__s__id__((s:build/bdist.linux-i686/egg/pytils/templatetags/__init__.pys?s PKt[63kIm!pytils/templatetags/pytils_dt.pyc; Ec@sdZdZZdZdkZdklZlZdkl Z l Z ei Z ei iZei iZeei deZeodZdZn$eod Zd Zn d Zd Zd dZdedZdedZe idee idee idedS(s1 pytils.dt templatetags for Django web-framework s5$Id: pytils_dt.py 70 2007-02-19 03:42:32Z the.pythy $sV$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/templatetags/pytils_dt.py $N(stemplatesconf(sdtsutilssPYTILS_SHOW_VALUES_ON_ERRORsunknown: %(error)suunknown: %(error)ss %(value)su %(value)ssuicCsy(titi||tdt}Wnqt j oe}y$dt t t i |}Wnt j o d}nXthd|<d|<}nX|SdS(sF Display distance of time from current time. Parameter is an accuracy level (deafult is 1). Value must be numeral (i.e. time.time() result) or datetime.datetime (i.e. datetime.datetime.now() result). Examples:: {{ some_time|distance_of_time }} {{ some_dtime|distance_of_time:2 }} sdefaults %s secondssserrorsvalueN(sutilss provide_strsdtsdistance_of_time_in_wordss from_timesaccuracysencodings default_valuesress Exceptionserrsstrsintstimesdefault_distance(s from_timesaccuracyserrsressdefault_distance((s;build/bdist.linux-i686/egg/pytils/templatetags/pytils_dt.pysdistance_of_time2s $ !s%d.%m.%YcCsyLti|tdd}ti||dtd|}ti |t}Wnft j oZ}y|i|}Wnt j ot|}nXthd|<d|<}nX|SdS(sb Russian strftime, formats date with given format. Value is a date (supports datetime.date and datetime.datetime), parameter is a format (string). For explainings about format, see documentation for original strftime: http://docs.python.org/lib/module-time.html Examples:: {{ some_date|ru_strftime:"%d %B %Y, %A" }} sdefaultu%d.%m.%Ys inflecteds inflected_dayserrorsvalueN(sutilssprovide_unicodesformatsencodingsuformatsdts ru_strftimesdatesTrues inflected_daysuress provide_strsress Exceptionserrsstrftimes default_datesstrs default_value(sdatesformats inflected_dayserrsressuress default_datesuformat((s;build/bdist.linux-i686/egg/pytils/templatetags/pytils_dt.pys ru_strftimeMs   !cCst|||SdS(s Russian strftime with inflected day, formats date with given format (similar to ru_strftime), also inflects day in proper form. Examples:: {{ some_date|ru_strftime_inflected:"in %A (%d %B %Y)" N(s ru_strftimesdatesformats inflected_day(sdatesformats inflected_day((s;build/bdist.linux-i686/egg/pytils/templatetags/pytils_dt.pysru_strftime_inflectedissdistance_of_times ru_strftimesru_strftime_inflected(s__doc__s__id__s __revision__s__url__stimesdjangostemplatesconfspytilssdtsutilssLibrarysregisterssettingssDEFAULT_CHARSETsencodingsDEBUGsdebugsgetattrsFalses show_values default_valuesdefault_uvaluesdistance_of_times ru_strftimesTruesru_strftime_inflectedsfilter(s default_values __revision__stemplatesencodingsutilssregisters__url__s show_values__id__sconfstimesdebugsdts ru_strftimesdefault_uvaluesru_strftime_inflectedsdistance_of_time((s;build/bdist.linux-i686/egg/pytils/templatetags/pytils_dt.pys?s.         PKt[6$&pytils/templatetags/pytils_numeral.pyc; Ec@sdZdZZdZdklZlZdklZl Z ei Z ei i Zei iZeei deZeodZdZn$eodZd Zn d Zd Zd Zed ZedZe idee idee idedZe iedS(s6 pytils.numeral templatetags for Django web-framework s:$Id: pytils_numeral.py 70 2007-02-19 03:42:32Z the.pythy $s[$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/templatetags/pytils_numeral.py $(stemplatesconf(snumeralsutilssPYTILS_SHOW_VALUES_ON_ERRORsunknown: %(error)suunknown: %(error)ss %(value)su %(value)ssucCsyt|toti|tt}n7gi}|D]}|ti|tt q:~}ti t i||tdt}WnWtj oK}y |}Wntj o d}nXthd|<d|<}nX|SdS(sI Choose proper form for plural. Value is a amount, parameters are forms of noun. Forms are variants for 1, 2, 5 nouns. It may be tuple of elements, or string where variants separates each other by comma. Examples:: {{ some_int|choose_plural:"пример,примера,примеров" }} sdefaultsserrorsvalueN(s isinstancesvariantssstrsutilssprovide_unicodesencodings default_values uvariantssappends_[1]svsdefault_uvalues provide_strsnumerals choose_pluralsamountsress Exceptionserrsdefault_variant(samountsvariantsserrsress uvariantssdefault_variants_[1]sv((s@build/bdist.linux-i686/egg/pytils/templatetags/pytils_numeral.pys choose_plural1s 6  !cCsjy(titi||tdt}Wn7t j o+}thd|<dt |<}nX|SdS(s;Converts float value to in-words representation (for money)sdefaultserrorsvalueN( sutilss provide_strsnumeralsrublessamountszero_for_kopecksencodings default_valuesress Exceptionserrsstr(samountszero_for_kopeckserrsres((s@build/bdist.linux-i686/egg/pytils/templatetags/pytils_numeral.pysrublesPs'cCs|y:titi|ttt|tt dt }Wn7t j o+}t hd|<dt|<}nX|SdS(s In-words representation of amount. Parameter is a gender: MALE, FEMALE or NEUTER Examples:: {{ some_int|in_words }} {{ some_other_int|in_words:FEMALE }} sdefaultserrorsvalueN(sutilss provide_strsnumeralsin_wordssamountsgetattrsstrsgendersNonesencodings default_valuesress Exceptionserr(samountsgenderserrsres((s@build/bdist.linux-i686/egg/pytils/templatetags/pytils_numeral.pysin_words]s ''s choose_pluralsrublessin_wordscCsysgi}|D]}|ti|ttq~}ti t i |t t t|t|tdt}Wn7tj o+}thd|<dt|<}nX|SdS(s in_words and choose_plural in a one flask Makes in-words representation of value with choosing correct form of noun. First parameter is an amount of objects. Second is a gender (MALE, FEMALE, NEUTER). Third is a variants of forms for object name. Examples:: {% sum_string some_int MALE "пример,примера,примеров" %} {% sum_string some_other_int FEMALE "задача,задачи,задач" %} sdefaultserrorsvalueN(sappends_[1]sitemssisutilssprovide_unicodesencodingsdefault_uvaluesuitemss provide_strsnumerals sum_stringsamountsgetattrsstrsgendersNones default_valuesress Exceptionserr(samountsgendersitemssresserrsis_[1]suitems((s@build/bdist.linux-i686/egg/pytils/templatetags/pytils_numeral.pys sum_stringzs 6*'N(s__doc__s__id__s __revision__s__url__sdjangostemplatesconfspytilssnumeralsutilssLibrarysregisterssettingssDEFAULT_CHARSETsencodingsDEBUGsdebugsgetattrsFalses show_values default_valuesdefault_uvalues choose_pluralsrublessNonesin_wordssfilters sum_strings simple_tag(s default_valuesrubless __revision__stemplatesencodings choose_pluralsutilssregisters__url__s show_values__id__sconfsdebugsnumeralsin_wordssdefault_uvalues sum_string((s@build/bdist.linux-i686/egg/pytils/templatetags/pytils_numeral.pys?s0         PKt[6iW'" " 'pytils/templatetags/pytils_translit.pyc; Ec@sdZdZZdZdklZlZdklZl Z ei Z ei i Zei iZeei deZeodZdZn$eodZd Zn d Zd Zd Zd ZdZe idee idee idedS(s7 pytils.translit templatetags for Django web-framework s;$Id: pytils_translit.py 70 2007-02-19 03:42:32Z the.pythy $s\$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/templatetags/pytils_translit.py $(stemplatesconf(stranslitsutilssPYTILS_SHOW_VALUES_ON_ERRORsunknown: %(error)suunknown: %(error)ss %(value)su %(value)ssucCsay%titi|tdt}Wn1tj o%}thd|<d|<}nX|SdS(sTranslify russian textsdefaultserrorsvalueN( stranslits translifysutilssprovide_unicodesstextsencodings default_valuesress Exceptionserr(sstextserrsres((sAbuild/bdist.linux-i686/egg/pytils/templatetags/pytils_translit.pys translify2s!cCsay%titi|tdt}Wn1tj o%}t hd|<d|<}nX|SdS(sDetranslify russian textsdefaultserrorsvalueN( sutilss provide_strstranslits detranslifysstextsencodingsdefault_uvaluesress Exceptionserrs default_value(sstextserrsres((sAbuild/bdist.linux-i686/egg/pytils/templatetags/pytils_translit.pys detranslify@s!cCsay%titi|tdt}Wn1tj o%}thd|<d|<}nX|SdS(sMake slug from (russian) textsdefaultserrorsvalueN( stranslitsslugifysutilssprovide_unicodesstextsencodings default_valuesress Exceptionserr(sstextserrsres((sAbuild/bdist.linux-i686/egg/pytils/templatetags/pytils_translit.pysslugifyLs!s translifys detranslifysslugifyN(s__doc__s__id__s __revision__s__url__sdjangostemplatesconfspytilsstranslitsutilssLibrarysregisterssettingssDEFAULT_CHARSETsencodingsDEBUGsdebugsgetattrsFalses show_values default_valuesdefault_uvalues translifys detranslifysslugifysfilter(s default_values __revision__stemplatesencodingsutilssregisters__url__s detranslifys show_values__id__sconfsdebugsdefault_uvaluestranslitsslugifys translify((sAbuild/bdist.linux-i686/egg/pytils/templatetags/pytils_translit.pys?s,        PKMS67%%pytils/test/__init__.py# -*- coding: utf-8 -*- # PyTils - simple processing for russian strings # Copyright (C) 2006-2007 Yury Yurevich # # http://gorod-omsk.ru/blog/pythy/projects/pytils/ # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation, version 2 # of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. """ Unit tests for pytils """ __id__ = __revision__ = "$Id: __init__.py 70 2007-02-19 03:42:32Z the.pythy $" __url__ = "$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/test/__init__.py $" __all__ = ["test_numeral", "test_dt", "test_translit", "test_utils"] import unittest def get_django_suite(): try: import django except ImportError: return unittest.TestSuite() import pytils.test.templatetags return pytils.test.templatetags.get_suite() def get_suite(): """Return TestSuite for all unit-test of PyTils""" suite = unittest.TestSuite() for module_name in __all__: imported_module = __import__("pytils.test."+module_name, globals(), locals(), ["pytils.test"]) loader = unittest.defaultTestLoader suite.addTest(loader.loadTestsFromModule(imported_module)) suite.addTest(get_django_suite()) return suite def run(verbosity=1): """Run all unit-test of PyTils""" suite = get_suite() unittest.TextTestRunner(verbosity=verbosity).run(suite) if __name__ == '__main__': run(2) PKz"6Ti,,pytils/test/test_dt.py# -*- coding: utf-8 -*- # PyTils - simple processing for russian strings # Copyright (C) 2006-2007 Yury Yurevich # # http://gorod-omsk.ru/blog/pythy/projects/pytils/ # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation, version 2 # of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. """ Unit-tests for pytils.dt """ __id__ = __revision__ = "$Id: test_dt.py 63 2007-01-02 09:22:16Z the.pythy $" __url__ = "$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/test/test_dt.py $" import datetime import time import unittest import pytils class DistanceOfTimeInWordsTestCase(unittest.TestCase): """ Test case for pytils.dt.distance_of_time_in_words """ def setUp(self): """ Setting up environment for tests """ self.time = 1156862275.7711999 self.dtime = {} self.updateTime(self.time) def updateTime(self, _time): """Update all time-related values for current time """ self.dtime['10sec_ago'] = _time - 10 self.dtime['1min_ago'] = _time - 60 self.dtime['10min_ago'] = _time - 600 self.dtime['1hr_ago'] = _time - 3720 self.dtime['10hr_ago'] = _time - 36600 self.dtime['1day_ago'] = _time - 87600 self.dtime['1day1hr_ago'] = _time - 90600 self.dtime['2day_ago'] = _time - 87600*2 self.dtime['in_10sec'] = _time + 10 self.dtime['in_1min'] = _time + 61 self.dtime['in_10min'] = _time + 601 self.dtime['in_1hr'] = _time + 3721 self.dtime['in_10hr'] = _time + 36601 self.dtime['in_1day'] = _time + 87601 self.dtime['in_1day1hr'] = _time + 90601 self.dtime['in_2day'] = _time + 87600*2 + 1 def ckDefaultAccuracy(self, typ, estimated): """ Checks with default value for accuracy """ t0 = time.time() # --- change state !!! attention self.updateTime(t0) # --- t1 = self.dtime[typ] res = pytils.dt.distance_of_time_in_words(from_time=t1, to_time=t0) # --- revert state to original value self.updateTime(self.time) # --- self.assertEquals(res, estimated) def ckDefaultToTime(self, typ, accuracy, estimated): """ Checks with default value of time """ t0 = time.time() # --- change state !!! attention self.updateTime(t0) # --- t1 = self.dtime[typ] res = pytils.dt.distance_of_time_in_words(t1, accuracy) # --- revert state to original value self.updateTime(self.time) # --- self.assertEquals(res, estimated) def testDOTIWDefaultAccuracy(self): """ Unit-test for distance_of_time_in_words with default accuracy """ self.ckDefaultAccuracy("10sec_ago", u"менее минуты назад") self.ckDefaultAccuracy("1min_ago", u"1 минуту назад") self.ckDefaultAccuracy("10min_ago", u"10 минут назад") self.ckDefaultAccuracy("1hr_ago", u"1 час назад") self.ckDefaultAccuracy("10hr_ago", u"10 часов назад") self.ckDefaultAccuracy("1day_ago", u"1 день назад") self.ckDefaultAccuracy("1day1hr_ago", u"1 день назад") self.ckDefaultAccuracy("2day_ago", u"2 дня назад") self.ckDefaultAccuracy("in_10sec", u"менее чем через минуту") self.ckDefaultAccuracy("in_1min", u"через 1 минуту") self.ckDefaultAccuracy("in_10min", u"через 10 минут") self.ckDefaultAccuracy("in_1hr", u"через 1 час") self.ckDefaultAccuracy("in_10hr", u"через 10 часов") self.ckDefaultAccuracy("in_1day", u"через 1 день") self.ckDefaultAccuracy("in_1day1hr", u"через 1 день") self.ckDefaultAccuracy("in_2day", u"через 2 дня") def testDOTIWDefaultToTimeAcc1(self): """ Unit-tests for distance_of_time_in_words with default to_time and accuracy=1 """ # accuracy = 1 self.ckDefaultToTime("10sec_ago", 1, u"менее минуты назад") self.ckDefaultToTime("1min_ago", 1, u"минуту назад") self.ckDefaultToTime("10min_ago", 1, u"10 минут назад") self.ckDefaultToTime("1hr_ago", 1, u"час назад") self.ckDefaultToTime("10hr_ago", 1, u"10 часов назад") self.ckDefaultToTime("1day_ago", 1, u"вчера") self.ckDefaultToTime("1day1hr_ago", 1, u"вчера") self.ckDefaultToTime("2day_ago", 1, u"позавчера") self.ckDefaultToTime("in_10sec", 1, u"менее чем через минуту") self.ckDefaultToTime("in_1min", 1, u"через минуту") self.ckDefaultToTime("in_10min", 1, u"через 10 минут") self.ckDefaultToTime("in_1hr", 1, u"через час") self.ckDefaultToTime("in_10hr", 1, u"через 10 часов") self.ckDefaultToTime("in_1day", 1, u"завтра") self.ckDefaultToTime("in_1day1hr", 1, u"завтра") self.ckDefaultToTime("in_2day", 1, u"послезавтра") def testDOTIWDefaultToTimeAcc2(self): """ Unit-tests for distance_of_time_in_words with default to_time and accuracy=2 """ # accuracy = 2 self.ckDefaultToTime("10sec_ago", 2, u"менее минуты назад") self.ckDefaultToTime("1min_ago", 2, u"минуту назад") self.ckDefaultToTime("10min_ago", 2, u"10 минут назад") self.ckDefaultToTime("1hr_ago", 2, u"1 час 2 минуты назад") self.ckDefaultToTime("10hr_ago", 2, u"10 часов 10 минут назад") self.ckDefaultToTime("1day_ago", 2, u"вчера") self.ckDefaultToTime("1day1hr_ago", 2, u"1 день 1 час назад") self.ckDefaultToTime("2day_ago", 2, u"позавчера") self.ckDefaultToTime("in_10sec", 2, u"менее чем через минуту") self.ckDefaultToTime("in_1min", 2, u"через минуту") self.ckDefaultToTime("in_10min", 2, u"через 10 минут") self.ckDefaultToTime("in_1hr", 2, u"через 1 час 2 минуты") self.ckDefaultToTime("in_10hr", 2, u"через 10 часов 10 минут") self.ckDefaultToTime("in_1day", 2, u"завтра") self.ckDefaultToTime("in_1day1hr", 2, u"через 1 день 1 час") self.ckDefaultToTime("in_2day", 2, u"послезавтра") def testDOTIWDefaultToTimeAcc3(self): """ Unit-tests for distance_of_time_in_words with default to_time and accuracy=3 """ # accuracy = 3 self.ckDefaultToTime("10sec_ago", 3, u"менее минуты назад") self.ckDefaultToTime("1min_ago", 3, u"минуту назад") self.ckDefaultToTime("10min_ago", 3, u"10 минут назад") self.ckDefaultToTime("1hr_ago", 3, u"1 час 2 минуты назад") self.ckDefaultToTime("10hr_ago", 3, u"10 часов 10 минут назад") self.ckDefaultToTime("1day_ago", 3, u"1 день 0 часов 20 минут назад") self.ckDefaultToTime("1day1hr_ago", 3, u"1 день 1 час 10 минут назад") self.ckDefaultToTime("2day_ago", 3, u"2 дня 0 часов 40 минут назад") self.ckDefaultToTime("in_10sec", 3, u"менее чем через минуту") self.ckDefaultToTime("in_1min", 3, u"через минуту") self.ckDefaultToTime("in_10min", 3, u"через 10 минут") self.ckDefaultToTime("in_1hr", 3, u"через 1 час 2 минуты") self.ckDefaultToTime("in_10hr", 3, u"через 10 часов 10 минут") self.ckDefaultToTime("in_1day", 3, u"через 1 день 0 часов 20 минут") self.ckDefaultToTime("in_1day1hr", 3, u"через 1 день 1 час 10 минут") self.ckDefaultToTime("in_2day", 3, u"через 2 дня 0 часов 40 минут") def testDOTWDatetimeType(self): """ Unit-tests for testing datetime.datetime as input values """ first_time = datetime.datetime.now() second_time = first_time + datetime.timedelta(0, 1000) self.assertEquals(pytils.dt.distance_of_time_in_words( from_time=first_time, accuracy=1, to_time=second_time), u"16 минут назад") def testDOTIWExceptions(self): """ Unit-tests for testings distance_of_time_in_words' exceptions """ self.assertRaises(TypeError, pytils.dt.distance_of_time_in_words, "test") self.assertRaises(TypeError, pytils.dt.distance_of_time_in_words, time.time(), "test") self.assertRaises(TypeError, pytils.dt.distance_of_time_in_words, time.time(), 2, "test") self.assertRaises(ValueError, pytils.dt.distance_of_time_in_words, time.time(), 0) class RuStrftimeTestCase(unittest.TestCase): """ Test case for pytils.dt.ru_strftime """ def setUp(self): """ Setting up environment for tests """ self.date = datetime.date(2006, 8, 25) def ck(self, format, estimates): """ Checks w/o inflected """ res = pytils.dt.ru_strftime(format, self.date) self.assertEquals(res, estimates) def ckInflected(self, format, estimates): """ Checks with inflected """ res = pytils.dt.ru_strftime(format, self.date, True) self.assertEquals(res, estimates) def ckInflectedDay(self, format, estimates): """ Checks with inflected day """ res = pytils.dt.ru_strftime(format, self.date, inflected_day=True) self.assertEquals(res, estimates) def testRuStrftime(self): """ Unit-tests for pytils.dt.ru_strftime """ self.ck(u"тест %a", u"тест пт") self.ck(u"тест %A", u"тест пятница") self.ck(u"тест %b", u"тест авг") self.ck(u"тест %B", u"тест август") self.ckInflected(u"тест %B", u"тест августа") self.ckInflected(u"тест выполнен %d %B %Y года", u"тест выполнен 25 августа 2006 года") self.ckInflectedDay(u"тест выполнен в %A", u"тест выполнен в пятницу") def testRuStrftimeExceptions(self): """ Unit-tests for testing pytils.dt.ru_strftime's exceptions """ self.assertRaises(TypeError, pytils.dt.ru_strftime, time.time()) self.assertRaises(TypeError, pytils.dt.ru_strftime, u"%Y.%m.%d%", time.time()) if __name__ == '__main__': unittest.main() PKz"6 >>pytils/test/test_numeral.py# -*- coding: utf-8 -*- # PyTils - simple processing for russian strings # Copyright (C) 2006-2007 Yury Yurevich # # http://gorod-omsk.ru/blog/pythy/projects/pytils/ # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation, version 2 # of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. """ Unit-tests for pytils.numeral """ __id__ = __revision__ = "$Id: test_numeral.py 63 2007-01-02 09:22:16Z the.pythy $" __url__ = "$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/test/test_numeral.py $" import unittest import pytils class ChoosePluralTestCase(unittest.TestCase): """ Test case for pytils.numeral.choose_plural """ def setUp(self): """ Setting up environment for tests """ self.variants = (u"гвоздь", u"гвоздя", u"гвоздей") def checkChoosePlural(self, amount, estimated): """ Checks choose_plural """ self.assertEquals(pytils.numeral.choose_plural(amount, self.variants), estimated) def testChoosePlural(self): """ Unit-test for choose_plural """ self.checkChoosePlural(1, u"гвоздь") self.checkChoosePlural(2, u"гвоздя") self.checkChoosePlural(3, u"гвоздя") self.checkChoosePlural(5, u"гвоздей") self.checkChoosePlural(11, u"гвоздей") self.checkChoosePlural(109, u"гвоздей") self.checkChoosePlural(109l, u"гвоздей") def testChoosePluralExceptions(self): """ Unit-test for testing choos_plural's exceptions """ self.assertRaises(TypeError, pytils.numeral.choose_plural, "25", u"any,bene,raba") self.assertRaises(TypeError, pytils.numeral.choose_plural, 25, 30) self.assertRaises(ValueError, pytils.numeral.choose_plural, 25, u"any,bene") self.assertRaises(ValueError, pytils.numeral.choose_plural, -25, u"any,bene,raba") def testChoosePluralVariantsInStr(self): self.assertEquals( pytils.numeral.choose_plural(1,u"гвоздь,гвоздя, гвоздей"), u"гвоздь") class GetFloatRemainderTestCase(unittest.TestCase): """ Test case for pytils.numeral._get_float_remainder """ def testFloatRemainder(self): """ Unit-test for _get_float_remainder """ self.assertEquals(pytils.numeral._get_float_remainder(1.3), '3') self.assertEquals(pytils.numeral._get_float_remainder(2.35, 1), '4') self.assertEquals(pytils.numeral._get_float_remainder(123.1234567891), '123456789') self.assertEquals(pytils.numeral._get_float_remainder(2.353, 2), '35') self.assertEquals(pytils.numeral._get_float_remainder(0.01), '01') self.assertEquals(pytils.numeral._get_float_remainder(5), '0') def testFloatRemainderExceptions(self): """ Unit-test for testing _get_float_remainder's exceptions """ self.assertRaises(ValueError, pytils.numeral._get_float_remainder, 2.998, 2) self.assertRaises(TypeError, pytils.numeral._get_float_remainder, "1.23") self.assertRaises(ValueError, pytils.numeral._get_float_remainder, -1.23) class RublesTestCase(unittest.TestCase): """ Test case for pytils.numeral.rubles """ def testRubles(self): """ Unit-test for rubles """ self.assertEquals(pytils.numeral.rubles(10.01), u"десять рублей одна копейка") self.assertEquals(pytils.numeral.rubles(10.10), u"десять рублей десять копеек") self.assertEquals(pytils.numeral.rubles(2.353), u"два рубля тридцать пять копеек") self.assertEquals(pytils.numeral.rubles(2.998), u"три рубля") self.assertEquals(pytils.numeral.rubles(3), u"три рубля") self.assertEquals(pytils.numeral.rubles(3, True), u"три рубля ноль копеек") self.assertEquals(pytils.numeral.rubles(3l), u"три рубля") def testRublesExceptions(self): """ Unit-test for testing rubles' exceptions """ self.assertRaises(TypeError, pytils.numeral.rubles, "3") self.assertRaises(ValueError, pytils.numeral.rubles, -15) class InWordsTestCase(unittest.TestCase): """ Test case for pytils.numeral.in_words """ def testInt(self): """ Unit-test for in_words_int """ self.assertEquals(pytils.numeral.in_words_int(10), u"десять") self.assertEquals(pytils.numeral.in_words_int(5), u"пять") self.assertEquals(pytils.numeral.in_words_int(102), u"сто два") self.assertEquals(pytils.numeral.in_words_int(3521), u"три тысячи пятьсот двадцать один") self.assertEquals(pytils.numeral.in_words_int(3500), u"три тысячи пятьсот") self.assertEquals(pytils.numeral.in_words_int(5231000), u"пять миллионов двести тридцать одна тысяча") self.assertEquals(pytils.numeral.in_words_int(10l), u"десять") def testIntExceptions(self): """ Unit-test for testing in_words_int's exceptions """ self.assertRaises(TypeError, pytils.numeral.in_words_int, 2.5) self.assertRaises(ValueError, pytils.numeral.in_words_int, -3) def testFloat(self): """ Unit-test for in_words_float """ self.assertEquals(pytils.numeral.in_words_float(10.0), u"десять целых ноль десятых") self.assertEquals(pytils.numeral.in_words_float(2.25), u"две целых двадцать пять сотых") self.assertEquals(pytils.numeral.in_words_float(0.01), u"ноль целых одна сотая") self.assertEquals(pytils.numeral.in_words_float(0.10), u"ноль целых одна десятая") def testFloatExceptions(self): """ Unit-test for testing in_words_float's exceptions """ self.assertRaises(TypeError, pytils.numeral.in_words_float, '2') self.assertRaises(TypeError, pytils.numeral.in_words_float, 2) self.assertRaises(ValueError, pytils.numeral.in_words_float, -2.3) def testWithGenderOldStyle(self): """ Unit-test for in_words_float with gender (old-style, i.e. ints) """ self.assertEquals(pytils.numeral.in_words(21, 1), u"двадцать один") self.assertEquals(pytils.numeral.in_words(21, 2), u"двадцать одна") self.assertEquals(pytils.numeral.in_words(21, 3), u"двадцать одно") # на дробные пол не должен влиять - всегда в женском роде self.assertEquals(pytils.numeral.in_words(21.0, 1), u"двадцать одна целая ноль десятых") self.assertEquals(pytils.numeral.in_words(21.0, 2), u"двадцать одна целая ноль десятых") self.assertEquals(pytils.numeral.in_words(21.0, 3), u"двадцать одна целая ноль десятых") self.assertEquals(pytils.numeral.in_words(21l, 1), u"двадцать один") def testWithGender(self): """ Unit-test for in_words_float with gender (old-style, i.e. ints) """ self.assertEquals(pytils.numeral.in_words(21, pytils.numeral.MALE), u"двадцать один") self.assertEquals(pytils.numeral.in_words(21, pytils.numeral.FEMALE), u"двадцать одна") self.assertEquals(pytils.numeral.in_words(21, pytils.numeral.NEUTER), u"двадцать одно") # на дробные пол не должен влиять - всегда в женском роде self.assertEquals(pytils.numeral.in_words(21.0, pytils.numeral.MALE), u"двадцать одна целая ноль десятых") self.assertEquals(pytils.numeral.in_words(21.0, pytils.numeral.FEMALE), u"двадцать одна целая ноль десятых") self.assertEquals(pytils.numeral.in_words(21.0, pytils.numeral.NEUTER), u"двадцать одна целая ноль десятых") self.assertEquals(pytils.numeral.in_words(21l, pytils.numeral.MALE), u"двадцать один") def testCommon(self): """ Unit-test for general in_words """ self.assertEquals(pytils.numeral.in_words(10), u"десять") self.assertEquals(pytils.numeral.in_words(5), u"пять") self.assertEquals(pytils.numeral.in_words(102), u"сто два") self.assertEquals(pytils.numeral.in_words(3521), u"три тысячи пятьсот двадцать один") self.assertEquals(pytils.numeral.in_words(3500), u"три тысячи пятьсот") self.assertEquals(pytils.numeral.in_words(5231000), u"пять миллионов двести тридцать одна тысяча") self.assertEquals(pytils.numeral.in_words(10.0), u"десять целых ноль десятых") self.assertEquals(pytils.numeral.in_words(2.25), u"две целых двадцать пять сотых") self.assertEquals(pytils.numeral.in_words(0.01), u"ноль целых одна сотая") self.assertEquals(pytils.numeral.in_words(0.10), u"ноль целых одна десятая") self.assertEquals(pytils.numeral.in_words(10l), u"десять") def testCommonExceptions(self): """ Unit-test for testing in_words' exceptions """ self.assertRaises(TypeError, pytils.numeral.in_words, "0.2") self.assertRaises(TypeError, pytils.numeral.in_words, 0.2, "1") self.assertRaises(ValueError, pytils.numeral.in_words, 0.2, 5) self.assertRaises(ValueError, pytils.numeral.in_words, -2) class SumStringTestCase(unittest.TestCase): """ Test case for pytils.numeral.sum_string """ def setUp(self): """ Setting up environment for tests """ self.variants_male = (u"гвоздь", u"гвоздя", u"гвоздей") self.variants_female = (u"шляпка", u"шляпки", u"шляпок") def ckMaleOldStyle(self, amount, estimated): """ Checks sum_string with male gender with old-style genders (i.e. ints) """ self.assertEquals(pytils.numeral.sum_string(amount, 1, self.variants_male), estimated) def ckMale(self, amount, estimated): """ Checks sum_string with male gender """ self.assertEquals(pytils.numeral.sum_string(amount, pytils.numeral.MALE, self.variants_male), estimated) def ckFemaleOldStyle(self, amount, estimated): """ Checks sum_string with female gender wuth old-style genders (i.e. ints) """ self.assertEquals(pytils.numeral.sum_string(amount, 2, self.variants_female), estimated) def ckFemale(self, amount, estimated): """ Checks sum_string with female gender """ self.assertEquals(pytils.numeral.sum_string(amount, pytils.numeral.FEMALE, self.variants_female), estimated) def testSumStringOldStyle(self): """ Unit-test for sum_string with old-style genders """ self.ckMaleOldStyle(10, u"десять гвоздей") self.ckMaleOldStyle(2, u"два гвоздя") self.ckMaleOldStyle(31, u"тридцать один гвоздь") self.ckFemaleOldStyle(10, u"десять шляпок") self.ckFemaleOldStyle(2, u"две шляпки") self.ckFemaleOldStyle(31, u"тридцать одна шляпка") self.ckFemaleOldStyle(31l, u"тридцать одна шляпка") self.assertEquals(u"одиннадцать негритят", pytils.numeral.sum_string( 11, 1, u"негритенок,негритенка,негритят" )) def testSumString(self): """ Unit-test for sum_string """ self.ckMale(10, u"десять гвоздей") self.ckMale(2, u"два гвоздя") self.ckMale(31, u"тридцать один гвоздь") self.ckFemale(10, u"десять шляпок") self.ckFemale(2, u"две шляпки") self.ckFemale(31, u"тридцать одна шляпка") self.ckFemale(31l, u"тридцать одна шляпка") self.assertEquals(u"одиннадцать негритят", pytils.numeral.sum_string( 11, pytils.numeral.MALE, u"негритенок,негритенка,негритят" )) def testSumStringExceptions(self): """ Unit-test for testing sum_string's exceptions """ self.assertRaises(TypeError, pytils.numeral.sum_string, "1", 1) self.assertRaises(TypeError, pytils.numeral.sum_string, 1, "1") self.assertRaises(TypeError, pytils.numeral.sum_string, 1, "1", 23) self.assertRaises(TypeError, pytils.numeral.sum_string, 1, pytils.numeral.MALE, (23,24,25)) self.assertRaises(ValueError, pytils.numeral.sum_string, 1, pytils.numeral.MALE, (23,)) self.assertRaises(ValueError, pytils.numeral.sum_string, -1, pytils.numeral.MALE, u"any,bene,raba") if __name__ == '__main__': unittest.main() PKz"6ēLpytils/test/test_translit.py# -*- coding: utf-8 -*- # PyTils - simple processing for russian strings # Copyright (C) 2006-2007 Yury Yurevich # # http://gorod-omsk.ru/blog/pythy/projects/pytils/ # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation, version 2 # of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. """ Unit-tests for pytils.translit """ __id__ = __revision__ = "$Id: test_translit.py 63 2007-01-02 09:22:16Z the.pythy $" __url__ = "$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/test/test_translit.py $" import unittest import pytils class TranslitTestCase(unittest.TestCase): """ Test case for pytils.translit """ def ckTransl(self, in_, out_): """ Checks translify """ self.assertEquals(pytils.translit.translify(in_), out_) def ckDetransl(self, in_, out_): """ Checks detranslify """ self.assertEquals(pytils.translit.detranslify(in_), out_) def ckSlug(self, in_, out_): """ Checks slugify """ self.assertEquals(pytils.translit.slugify(in_), out_) def testTransliteration(self): """ Unit-test for transliterations """ self.ckTransl(u"тест", 'test') self.ckTransl(u"проверка", 'proverka') self.ckTransl(u"транслит", 'translit') self.ckTransl(u"правда ли это", 'pravda li eto') self.ckTransl(u"Щука", 'Schuka') def testTransliterationExceptions(self): """ Unit-test for testing translify's exceptions """ self.assertRaises(TypeError, pytils.translit.translify, 25) self.assertRaises(ValueError, pytils.translit.translify, u'\u00bfHabla espa\u00f1ol?') def testDetransliteration(self): """ Unit-test for detransliterations """ self.ckDetransl('test', u"тест") self.ckDetransl('proverka', u"проверка") self.ckDetransl('translit', u"транслит") self.ckDetransl('SCHuka', u"Щука") self.ckDetransl('Schuka', u"Щука") def testDetransliterationExceptions(self): """ Unit-test for testing detranslify's exceptions """ self.assertRaises(TypeError, pytils.translit.detranslify, 25) self.assertRaises(ValueError, pytils.translit.detranslify, "тест") def testSlug(self): """ Unit-test for slugs """ self.ckSlug(u"ТеСт", 'test') self.ckSlug(u"Проверка связи", 'proverka-svyazi') self.ckSlug(u"me&you", 'me-and-you') self.ckSlug(u"и еще один тест", 'i-esche-odin-test') def testSlugExceptions(self): """ Unit-test for testing slugify's exceptions """ self.assertRaises(TypeError, pytils.translit.slugify, 25) self.assertRaises(ValueError, pytils.translit.slugify, "тест") def testTranslifyAdditionalUnicodeSymbols(self): """ Unit-test for testing additional unicode symbols """ self.ckTransl(u"«Вот так вот»", '"Vot tak vot"') self.ckTransl(u"‘Или вот так’", "'Ili vot tak'") self.ckTransl(u"– Да…", "- Da...") def testSlugifyIssue10(self): """ Unit-test for testing that bug#10 fixed """ self.ckSlug(u"Проверка связи…", 'proverka-svyazi') self.ckSlug(u"Проверка\x0aсвязи 2", 'proverka-svyazi-2') self.ckSlug(u"Проверка\201связи 3", 'proverkasvyazi-3') def testSlugifyIssue15(self): """ Unit-test for testing that bug#15 fixed """ self.ckSlug(u"World of Warcraft", "world-of-warcraft") if __name__ == '__main__': unittest.main() PKz"6)WD!!pytils/test/test_utils.py# -*- coding: utf-8 -*- # PyTils - simple processing for russian strings # Copyright (C) 2006-2007 Yury Yurevich # # http://gorod-omsk.ru/blog/pythy/projects/pytils/ # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation, version 2 # of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. """ Unit-tests for pytils.utils """ __id__ = __revision__ = "$Id: test_utils.py 63 2007-01-02 09:22:16Z the.pythy $" __url__ = "$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/test/test_utils.py $" import unittest import pytils class UnicodeTestCase(unittest.TestCase): """ Test case for unicode-utils """ def ckProvideUnicode(self, stext, encoding, utext): """ Check pytils.provide_unicode """ self.assertEquals( pytils.utils.provide_unicode(stext, encoding), utext ) def ckProvideStr(self, utext, encoding, stext): """ Check pytils.provide_str """ self.assertEquals( pytils.utils.provide_str(utext, encoding), stext ) def testProvideUnicode(self): """ Unit-tests for pytils.utils.provide_unicode """ self.ckProvideUnicode("тест №1", "utf-8", u"тест №1") def testProvideStr(self): """ Unit-tests for pytils.utils.provide_str """ self.ckProvideStr(u"тест №1", "utf-8", "тест №1") self.ckProvideStr(u"тест №1", "koi8-r", "unknown") def testProvideStrNonDefault(self): """ Unit-tests for pytils.utils.provide_str with 'default' parameter """ self.assertEquals( pytils.utils.provide_str(u"тест №1", "koi8-r", default="hz"), "hz" ) class ChecksTestCase(unittest.TestCase): """ Test case for check_* utils """ def testGetValueByName(self): """ Unit-test for pytils.utils.get_value_by_name """ var1 = '25' var2 = 25 self.assertEquals('25', pytils.utils.get_value_by_name('var1', depth=1)) self.assertEquals(25, pytils.utils.get_value_by_name('var2', depth=1)) self.assertRaises(RuntimeError, pytils.utils.get_value_by_name, 'var3') def testCheckType(self): """ Unit-test for pytils.utils.check_type """ var = '25' # нельзя assertRaises, потому что глубина стека вызовов тогда не 2, # а гораздо больше try: pytils.utils.check_type('var', int) except TypeError, err: self.assertEquals("var must be , not ", str(err)) try: pytils.utils.check_type('var', (int, float)) except TypeError, err: self.assertEquals("var must be (, ), " + \ "not ", str(err)) self.assertEquals(None, pytils.utils.check_type('var', str)) self.assertEquals(None, pytils.utils.check_type('var', (str, basestring))) def testCheckLength(self): """ Unit-test for pytils.utils.check_length """ var = 'test' self.assertEquals(None, pytils.utils.check_length('var', 4)) try: pytils.utils.check_length('var', 5) except ValueError, err: self.assertEquals("var's length must be 5, but it 4", str(err)) def testCheckPositive(self): """ Unit-test for pytils.utils.check_positive """ var1 = 1 var2 = 1.25 var3 = -2 var4 = -2.12 self.assertEquals(None, pytils.utils.check_positive('var1')) self.assertEquals(None, pytils.utils.check_positive('var2')) try: pytils.utils.check_positive('var3') except ValueError, err: self.assertEquals("var3 must be positive or zero, not -2", str(err)) try: pytils.utils.check_positive('var4') except ValueError, err: self.assertEquals("var4 must be positive or zero, not -2.12", str(err)) def testCheckPositiveStrict(self): """ Unit-test for pytils.utils.check_positive """ var1 = 1 var2 = 0 var3 = -2 self.assertEquals(None, pytils.utils.check_positive('var1', strict=True)) try: pytils.utils.check_positive('var2', strict=True) except ValueError, err: self.assertEquals("var2 must be positive, not 0", str(err)) try: pytils.utils.check_positive('var3') except ValueError, err: self.assertEquals("var3 must be positive or zero, not -2", str(err)) if __name__ == '__main__': unittest.main() PKt[6Ypytils/test/__init__.pyc; Ec@sndZdZZdZddddgZdkZdZd Zd d Ze d joed ndS(s Unit tests for pytils s4$Id: __init__.py 70 2007-02-19 03:42:32Z the.pythy $sM$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/test/__init__.py $s test_numeralstest_dts test_translits test_utilsNcCsJy dk}Wntj otiSnXdk}|iiiSdS(N( sdjangos ImportErrorsunittests TestSuitespytils.test.templatetagsspytilsstests templatetagss get_suite(spytilssdjango((s2build/bdist.linux-i686/egg/pytils/test/__init__.pysget_django_suites   cCsvti}x_tD]W}td|ttdg}ti }|i |i ||i t qW|SdS(s,Return TestSuite for all unit-test of PyTilss pytils.test.s pytils.testN(sunittests TestSuitessuites__all__s module_names __import__sglobalsslocalssimported_modulesdefaultTestLoadersloadersaddTestsloadTestsFromModulesget_django_suite(sloaders module_namessuitesimported_module((s2build/bdist.linux-i686/egg/pytils/test/__init__.pys get_suite#s    icCs&t}tid|i|dS(sRun all unit-test of PyTilss verbosityN(s get_suitessuitesunittestsTextTestRunners verbositysrun(s verbosityssuite((s2build/bdist.linux-i686/egg/pytils/test/__init__.pysrun3s s__main__i( s__doc__s__id__s __revision__s__url__s__all__sunittestsget_django_suites get_suitesruns__name__(s __revision__sruns__all__s get_suitesunittests__url__sget_django_suites__id__((s2build/bdist.linux-i686/egg/pytils/test/__init__.pys?s     PKt[6 22pytils/test/test_dt.pyc; $Ec@sdZdZZdZdkZdkZdkZdkZdeifdYZ deifdYZ e djoei ndS( s Unit-tests for pytils.dt s3$Id: test_dt.py 63 2007-01-02 09:22:16Z the.pythy $sL$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/test/test_dt.py $NsDistanceOfTimeInWordsTestCasecBshtZdZdZdZdZdZdZdZdZ dZ d Z d Z RS( s; Test case for pytils.dt.distance_of_time_in_words cCs&d|_h|_|i|idS(s2 Setting up environment for tests f1156862275.7711999N(sselfstimesdtimes updateTime(sself((s1build/bdist.linux-i686/egg/pytils/test/test_dt.pyssetUp"s  cCs |d|id<|d|id<|d|id<|d|id<|d |id <|d |id <|d |id<|d d|id<|d|id<|d|id<|d|id<|d|id<|d|id<|d|id<|d|id<|d dd|ids   cCs_ti}|i||i|}tii ||}|i|i|i ||dS(s3 Checks with default value of time N(stimest0sselfs updateTimesdtimestypst1spytilssdtsdistance_of_time_in_wordssaccuracysress assertEqualss estimated(sselfstypsaccuracys estimatedsresst0st1((s1build/bdist.linux-i686/egg/pytils/test/test_dt.pysckDefaultToTimeMs   cCs|idd|idd|idd|idd|id d |id d |id d |idd|idd|idd|idd|idd|idd|idd|idd|idddS( sO Unit-test for distance_of_time_in_words with default accuracy s 10sec_agou"менее минуты назадs1min_agou1 минуту назадs 10min_agou10 минут назадs1hr_agou1 час назадs10hr_agou10 часов назадs1day_agou1 день назадs 1day1hr_agos2day_agou2 дня назадsin_10secu)менее чем через минутуsin_1minuчерез 1 минутуsin_10minuчерез 10 минутsin_1hruчерез 1 часsin_10hruчерез 10 часовsin_1dayuчерез 1 деньs in_1day1hrsin_2dayuчерез 2 дняN(sselfsckDefaultAccuracy(sself((s1build/bdist.linux-i686/egg/pytils/test/test_dt.pystestDOTIWDefaultAccuracy\s"cCs4|iddd|iddd|iddd|iddd |id dd |id dd |iddd |iddd|iddd|iddd|iddd|iddd|iddd|iddd|iddd|idddd S(!s^ Unit-tests for distance_of_time_in_words with default to_time and accuracy=1 s 10sec_agoiu"менее минуты назадs1min_agouминуту назадs 10min_agou10 минут назадs1hr_agouчас назадs10hr_agou10 часов назадs1day_agou вчераs 1day1hr_agos2day_agouпозавчераsin_10secu)менее чем через минутуsin_1minuчерез минутуsin_10minuчерез 10 минутsin_1hruчерез часsin_10hruчерез 10 часовsin_1dayu завтраs in_1day1hrsin_2dayuпослезавтраN(sselfsckDefaultToTime(sself((s1build/bdist.linux-i686/egg/pytils/test/test_dt.pystestDOTIWDefaultToTimeAcc1rs"cCs4|iddd|iddd|iddd|iddd |id dd |id dd |iddd|iddd|iddd|iddd|iddd|iddd|iddd|iddd|iddd|id dd!d"S(#s^ Unit-tests for distance_of_time_in_words with default to_time and accuracy=2 s 10sec_agoiu"менее минуты назадs1min_agouминуту назадs 10min_agou10 минут назадs1hr_agou"1 час 2 минуты назадs10hr_agou&10 часов 10 минут назадs1day_agou вчераs 1day1hr_agou1 день 1 час назадs2day_agouпозавчераsin_10secu)менее чем через минутуsin_1minuчерез минутуsin_10minuчерез 10 минутsin_1hru"через 1 час 2 минутыsin_10hru&через 10 часов 10 минутsin_1dayu завтраs in_1day1hruчерез 1 день 1 часsin_2dayuпослезавтраN(sselfsckDefaultToTime(sself((s1build/bdist.linux-i686/egg/pytils/test/test_dt.pystestDOTIWDefaultToTimeAcc2s"cCs4|iddd|iddd|iddd|iddd |id dd |id dd |iddd|iddd|iddd|iddd|iddd|iddd|iddd|iddd|iddd|id dd!d"S(#s^ Unit-tests for distance_of_time_in_words with default to_time and accuracy=3 s 10sec_agoiu"менее минуты назадs1min_agouминуту назадs 10min_agou10 минут назадs1hr_agou"1 час 2 минуты назадs10hr_agou&10 часов 10 минут назадs1day_agou01 день 0 часов 20 минут назадs 1day1hr_agou,1 день 1 час 10 минут назадs2day_agou.2 дня 0 часов 40 минут назадsin_10secu)менее чем через минутуsin_1minuчерез минутуsin_10minuчерез 10 минутsin_1hru"через 1 час 2 минутыsin_10hru&через 10 часов 10 минутsin_1dayu0через 1 день 0 часов 20 минутs in_1day1hru,через 1 день 1 час 10 минутsin_2dayu.через 2 дня 0 часов 40 минутN(sselfsckDefaultToTime(sself((s1build/bdist.linux-i686/egg/pytils/test/test_dt.pystestDOTIWDefaultToTimeAcc3s.      cCsTtii}|tidd}|itii d|ddd|ddS( sJ Unit-tests for testing datetime.datetime as input values iis from_timesaccuracyisto_timeu16 минут назадN( sdatetimesnows first_times timedeltas second_timesselfs assertEqualsspytilssdtsdistance_of_time_in_words(sselfs second_times first_time((s1build/bdist.linux-i686/egg/pytils/test/test_dt.pystestDOTWDatetimeTypes cCs|ittiid|ittiitid|ittiitidd|ittiitiddS(sO Unit-tests for testings distance_of_time_in_words' exceptions stestiiN(sselfs assertRaisess TypeErrorspytilssdtsdistance_of_time_in_wordsstimes ValueError(sself((s1build/bdist.linux-i686/egg/pytils/test/test_dt.pystestDOTIWExceptionss "%( s__name__s __module__s__doc__ssetUps updateTimesckDefaultAccuracysckDefaultToTimestestDOTIWDefaultAccuracystestDOTIWDefaultToTimeAcc1stestDOTIWDefaultToTimeAcc2stestDOTIWDefaultToTimeAcc3stestDOTWDatetimeTypestestDOTIWExceptions(((s1build/bdist.linux-i686/egg/pytils/test/test_dt.pysDistanceOfTimeInWordsTestCases          sRuStrftimeTestCasecBsDtZdZdZdZdZdZdZdZRS(s- Test case for pytils.dt.ru_strftime cCstiddd|_dS(s2 Setting up environment for tests iiiN(sdatetimesdatesself(sself((s1build/bdist.linux-i686/egg/pytils/test/test_dt.pyssetUpscCs,tii||i}|i||dS(s& Checks w/o inflected N( spytilssdts ru_strftimesformatsselfsdatesress assertEqualss estimates(sselfsformats estimatessres((s1build/bdist.linux-i686/egg/pytils/test/test_dt.pysckscCs/tii||it}|i||dS(s' Checks with inflected N( spytilssdts ru_strftimesformatsselfsdatesTruesress assertEqualss estimates(sselfsformats estimatessres((s1build/bdist.linux-i686/egg/pytils/test/test_dt.pys ckInflectedscCs2tii||idt}|i||dS(s+ Checks with inflected day s inflected_dayN( spytilssdts ru_strftimesformatsselfsdatesTruesress assertEqualss estimates(sselfsformats estimatessres((s1build/bdist.linux-i686/egg/pytils/test/test_dt.pysckInflectedDayscCst|idd|idd|idd|idd|idd |id d |id d dS(s6 Unit-tests for pytils.dt.ru_strftime u тест %au тест птu тест %Auтест пятницаu тест %buтест авгu тест %Buтест августuтест августаu+тест выполнен %d %B %Y годаu9тест выполнен 25 августа 2006 годаuтест выполнен в %Au+тест выполнен в пятницуN(sselfscks ckInflectedsckInflectedDay(sself((s1build/bdist.linux-i686/egg/pytils/test/test_dt.pystestRuStrftimes cCsE|ittiiti|ittiidtidS(sK Unit-tests for testing pytils.dt.ru_strftime's exceptions u %Y.%m.%d%N(sselfs assertRaisess TypeErrorspytilssdts ru_strftimestime(sself((s1build/bdist.linux-i686/egg/pytils/test/test_dt.pystestRuStrftimeExceptionss( s__name__s __module__s__doc__ssetUpscks ckInflectedsckInflectedDaystestRuStrftimestestRuStrftimeExceptions(((s1build/bdist.linux-i686/egg/pytils/test/test_dt.pysRuStrftimeTestCases      s__main__( s__doc__s__id__s __revision__s__url__sdatetimestimesunittestspytilssTestCasesDistanceOfTimeInWordsTestCasesRuStrftimeTestCases__name__smain( s __revision__sDistanceOfTimeInWordsTestCasesunittestsdatetimes__url__s__id__stimesRuStrftimeTestCasespytils((s1build/bdist.linux-i686/egg/pytils/test/test_dt.pys?s     5 PKt[6?kAApytils/test/test_numeral.pyc; $Ec@sdZdZZdZdkZdkZdeifdYZdeifdYZdeifd YZ d eifd YZ d eifd YZ e djoei ndS(s Unit-tests for pytils.numeral s8$Id: test_numeral.py 63 2007-01-02 09:22:16Z the.pythy $sQ$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/test/test_numeral.py $NsChoosePluralTestCasecBs;tZdZdZdZdZdZdZRS(s4 Test case for pytils.numeral.choose_plural cCsdddf|_dS(s2 Setting up environment for tests u гвоздьu гвоздяuгвоздейN(sselfsvariants(sself((s6build/bdist.linux-i686/egg/pytils/test/test_numeral.pyssetUpscCs&|itii||i|dS(s& Checks choose_plural N(sselfs assertEqualsspytilssnumerals choose_pluralsamountsvariantss estimated(sselfsamounts estimated((s6build/bdist.linux-i686/egg/pytils/test/test_numeral.pyscheckChoosePlural%scCst|idd|idd|idd|idd|idd|id d|id dd S( s- Unit-test for choose_plural iu гвоздьiu гвоздяiiuгвоздейi imlmN(sselfscheckChoosePlural(sself((s6build/bdist.linux-i686/egg/pytils/test/test_numeral.pystestChoosePlural,scCst|ittiidd|ittiidd|ittiidd|ittiidddS(sA Unit-test for testing choos_plural's exceptions s25u any,bene,rabaiiuany,beneiN(sselfs assertRaisess TypeErrorspytilssnumerals choose_plurals ValueError(sself((s6build/bdist.linux-i686/egg/pytils/test/test_numeral.pystestChoosePluralExceptions8s   cCs#|itiiddddS(Niu)гвоздь,гвоздя, гвоздейu гвоздь(sselfs assertEqualsspytilssnumerals choose_plural(sself((s6build/bdist.linux-i686/egg/pytils/test/test_numeral.pystestChoosePluralVariantsInStrEs(s__name__s __module__s__doc__ssetUpscheckChoosePluralstestChoosePluralstestChoosePluralExceptionsstestChoosePluralVariantsInStr(((s6build/bdist.linux-i686/egg/pytils/test/test_numeral.pysChoosePluralTestCases    sGetFloatRemainderTestCasecBs tZdZdZdZRS(s; Test case for pytils.numeral._get_float_remainder cCs|itiidd|itiiddd|itiidd|itiidd d |itiid d |itiid ddS(s4 Unit-test for _get_float_remainder f1.3s3f2.3500000000000001is4f123.1234567891s 123456789f2.3530000000000002is35f0.01s01is0N(sselfs assertEqualsspytilssnumerals_get_float_remainder(sself((s6build/bdist.linux-i686/egg/pytils/test/test_numeral.pystestFloatRemainderOscCsR|ittiidd|ittiid|ittiiddS(sI Unit-test for testing _get_float_remainder's exceptions f2.9980000000000002is1.23f-1.23N(sselfs assertRaisess ValueErrorspytilssnumerals_get_float_remainders TypeError(sself((s6build/bdist.linux-i686/egg/pytils/test/test_numeral.pystestFloatRemainderExceptions`s  (s__name__s __module__s__doc__stestFloatRemainderstestFloatRemainderExceptions(((s6build/bdist.linux-i686/egg/pytils/test/test_numeral.pysGetFloatRemainderTestCaseJs  sRublesTestCasecBs tZdZdZdZRS(s- Test case for pytils.numeral.rubles cCs|itiidd|itiidd|itiidd|itiidd|itiid d|itiid td |itiid dd S( s& Unit-test for rubles f10.01u1десять рублей одна копейкаf10.1u3десять рублей десять копеекf2.3530000000000002u8два рубля тридцать пять копеекf2.9980000000000002uтри рубляiu'три рубля ноль копеекlN(sselfs assertEqualsspytilssnumeralsrublessTrue(sself((s6build/bdist.linux-i686/egg/pytils/test/test_numeral.pys testRublesnscCs6|ittiid|ittiiddS(s: Unit-test for testing rubles' exceptions s3iN(sselfs assertRaisess TypeErrorspytilssnumeralsrubless ValueError(sself((s6build/bdist.linux-i686/egg/pytils/test/test_numeral.pystestRublesExceptionss(s__name__s __module__s__doc__s testRublesstestRublesExceptions(((s6build/bdist.linux-i686/egg/pytils/test/test_numeral.pysRublesTestCaseis  sInWordsTestCasecBsVtZdZdZdZdZdZdZdZdZ dZ RS( s/ Test case for pytils.numeral.in_words cCs|itiidd|itiidd|itiidd|itiidd|itiid d |itiid d |itiid ddS(s, Unit-test for in_words_int i u десятьiuпятьifu сто дваi u<три тысячи пятьсот двадцать одинi u"три тысячи пятьсотiOuOпять миллионов двести тридцать одна тысячаl N(sselfs assertEqualsspytilssnumerals in_words_int(sself((s6build/bdist.linux-i686/egg/pytils/test/test_numeral.pystestIntscCs6|ittiid|ittiiddS(sA Unit-test for testing in_words_int's exceptions f2.5iN(sselfs assertRaisess TypeErrorspytilssnumerals in_words_ints ValueError(sself((s6build/bdist.linux-i686/egg/pytils/test/test_numeral.pystestIntExceptionsscCst|itiidd|itiidd|itiidd|itiiddd S( s. Unit-test for in_words_float f10.0u/десять целых ноль десятыхf2.25u6две целых двадцать пять сотыхf0.01u'ноль целых одна сотаяf0.10000000000000001u+ноль целых одна десятаяN(sselfs assertEqualsspytilssnumeralsin_words_float(sself((s6build/bdist.linux-i686/egg/pytils/test/test_numeral.pys testFloatscCsO|ittiid|ittiid|ittiiddS(sC Unit-test for testing in_words_float's exceptions s2if-2.2999999999999998N(sselfs assertRaisess TypeErrorspytilssnumeralsin_words_floats ValueError(sself((s6build/bdist.linux-i686/egg/pytils/test/test_numeral.pystestFloatExceptionsscCs|itiiddd|itiiddd|itiiddd|itiiddd |itiiddd |itiiddd |itiid ddd S( sQ Unit-test for in_words_float with gender (old-style, i.e. ints) iiuдвадцать одинiuдвадцать однаiuдвадцать одноf21.0u<двадцать одна целая ноль десятыхlN(sselfs assertEqualsspytilssnumeralsin_words(sself((s6build/bdist.linux-i686/egg/pytils/test/test_numeral.pystestWithGenderOldStylescCs|itiidtiid|itiidtiid|itiidtiid|itiidtiid|itiidtiid|itiidtiid|itiidtiiddS( sQ Unit-test for in_words_float with gender (old-style, i.e. ints) iuдвадцать одинuдвадцать однаuдвадцать одноf21.0u<двадцать одна целая ноль десятыхlN(sselfs assertEqualsspytilssnumeralsin_wordssMALEsFEMALEsNEUTER(sself((s6build/bdist.linux-i686/egg/pytils/test/test_numeral.pystestWithGenderscCs8|itiidd|itiidd|itiidd|itiidd|itiid d |itiid d |itiid d|itiidd|itiidd|itiidd|itiidddS(s0 Unit-test for general in_words i u десятьiuпятьifu сто дваi u<три тысячи пятьсот двадцать одинi u"три тысячи пятьсотiOuOпять миллионов двести тридцать одна тысячаf10.0u/десять целых ноль десятыхf2.25u6две целых двадцать пять сотыхf0.01u'ноль целых одна сотаяf0.10000000000000001u+ноль целых одна десятаяl N(sselfs assertEqualsspytilssnumeralsin_words(sself((s6build/bdist.linux-i686/egg/pytils/test/test_numeral.pys testCommons&cCsn|ittiid|ittiidd|ittiidd|ittiiddS(s< Unit-test for testing in_words' exceptions s0.2f0.20000000000000001s1iiN(sselfs assertRaisess TypeErrorspytilssnumeralsin_wordss ValueError(sself((s6build/bdist.linux-i686/egg/pytils/test/test_numeral.pystestCommonExceptionss ( s__name__s __module__s__doc__stestIntstestIntExceptionss testFloatstestFloatExceptionsstestWithGenderOldStylestestWithGenders testCommonstestCommonExceptions(((s6build/bdist.linux-i686/egg/pytils/test/test_numeral.pysInWordsTestCases       sSumStringTestCasecBsVtZdZdZdZdZdZdZdZdZ dZ RS( s1 Test case for pytils.numeral.sum_string cCs(dddf|_dddf|_dS(s2 Setting up environment for tests u гвоздьu гвоздяuгвоздейu шляпкаu шляпкиu шляпокN(sselfs variants_malesvariants_female(sself((s6build/bdist.linux-i686/egg/pytils/test/test_numeral.pyssetUpscCs)|itii|d|i|dS(sW Checks sum_string with male gender with old-style genders (i.e. ints) iN(sselfs assertEqualsspytilssnumerals sum_stringsamounts variants_males estimated(sselfsamounts estimated((s6build/bdist.linux-i686/egg/pytils/test/test_numeral.pysckMaleOldStyles  cCs/|itii|tii|i|dS(s4 Checks sum_string with male gender N( sselfs assertEqualsspytilssnumerals sum_stringsamountsMALEs variants_males estimated(sselfsamounts estimated((s6build/bdist.linux-i686/egg/pytils/test/test_numeral.pysckMales   cCs)|itii|d|i|dS(sY Checks sum_string with female gender wuth old-style genders (i.e. ints) iN(sselfs assertEqualsspytilssnumerals sum_stringsamountsvariants_females estimated(sselfsamounts estimated((s6build/bdist.linux-i686/egg/pytils/test/test_numeral.pysckFemaleOldStyle"s  cCs/|itii|tii|i|dS(s6 Checks sum_string with female gender N( sselfs assertEqualsspytilssnumerals sum_stringsamountsFEMALEsvariants_females estimated(sselfsamounts estimated((s6build/bdist.linux-i686/egg/pytils/test/test_numeral.pysckFemale+s   cCs|idd|idd|idd|idd|idd|idd |id d |id tiid d ddS(sA Unit-test for sum_string with old-style genders i uдесять гвоздейiuдва гвоздяiu&тридцать один гвоздьuдесять шляпокuдве шляпкиu&тридцать одна шляпкаlu'одиннадцать негритятi iu:негритенок,негритенка,негритятN(sselfsckMaleOldStylesckFemaleOldStyles assertEqualsspytilssnumerals sum_string(sself((s6build/bdist.linux-i686/egg/pytils/test/test_numeral.pystestSumStringOldStyle4s  cCs|idd|idd|idd|idd|idd|idd |id d |id tiid tiid dS(s* Unit-test for sum_string i uдесять гвоздейiuдва гвоздяiu&тридцать один гвоздьuдесять шляпокuдве шляпкиu&тридцать одна шляпкаlu'одиннадцать негритятi u:негритенок,негритенка,негритятN(sselfsckMalesckFemales assertEqualsspytilssnumerals sum_stringsMALE(sself((s6build/bdist.linux-i686/egg/pytils/test/test_numeral.pys testSumStringHs   cCs|ittiidd|ittiidd|ittiiddd|ittiidtiidddf|ittiidtiidf|ittiidtiiddS( s? Unit-test for testing sum_string's exceptions s1iiiiiu any,bene,rabaN(sselfs assertRaisess TypeErrorspytilssnumerals sum_stringsMALEs ValueError(sself((s6build/bdist.linux-i686/egg/pytils/test/test_numeral.pystestSumStringExceptions\s   ( s__name__s __module__s__doc__ssetUpsckMaleOldStylesckMalesckFemaleOldStylesckFemalestestSumStringOldStyles testSumStringstestSumStringExceptions(((s6build/bdist.linux-i686/egg/pytils/test/test_numeral.pysSumStringTestCases    s__main__(s__doc__s__id__s __revision__s__url__sunittestspytilssTestCasesChoosePluralTestCasesGetFloatRemainderTestCasesRublesTestCasesInWordsTestCasesSumStringTestCases__name__smain( s __revision__sChoosePluralTestCasesInWordsTestCasesunittestsSumStringTestCases__url__sGetFloatRemainderTestCasesRublesTestCases__id__spytils((s6build/bdist.linux-i686/egg/pytils/test/test_numeral.pys?s   0 zj PKt[6?ٍpytils/test/test_translit.pyc; $Ec@s`dZdZZdZdkZdkZdeifdYZedjoei ndS(s Unit-tests for pytils.translit s9$Id: test_translit.py 63 2007-01-02 09:22:16Z the.pythy $sR$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/test/test_translit.py $NsTranslitTestCasecBsztZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d ZRS( s' Test case for pytils.translit cCs |itii||dS(s" Checks translify N(sselfs assertEqualsspytilsstranslits translifysin_sout_(sselfsin_sout_((s7build/bdist.linux-i686/egg/pytils/test/test_translit.pysckTransl!scCs |itii||dS(s$ Checks detranslify N(sselfs assertEqualsspytilsstranslits detranslifysin_sout_(sselfsin_sout_((s7build/bdist.linux-i686/egg/pytils/test/test_translit.pys ckDetransl'scCs |itii||dS(s Checks slugify N(sselfs assertEqualsspytilsstranslitsslugifysin_sout_(sselfsin_sout_((s7build/bdist.linux-i686/egg/pytils/test/test_translit.pysckSlug-scCsT|idd|idd|idd|idd|id d d S( s0 Unit-test for transliterations uтестstestuпроверкаsproverkauтранслитstranslituправда ли этоs pravda li etouЩукаsSchukaN(sselfsckTransl(sself((s7build/bdist.linux-i686/egg/pytils/test/test_translit.pystestTransliteration3s cCs6|ittiid|ittiiddS(s> Unit-test for testing translify's exceptions iu¿Habla español?N(sselfs assertRaisess TypeErrorspytilsstranslits translifys ValueError(sself((s7build/bdist.linux-i686/egg/pytils/test/test_translit.pystestTransliterationExceptions=scCsT|idd|idd|idd|idd|id dd S( s2 Unit-test for detransliterations stestuтестsproverkauпроверкаstranslituтранслитsSCHukauЩукаsSchukaN(sselfs ckDetransl(sself((s7build/bdist.linux-i686/egg/pytils/test/test_translit.pystestDetransliterationDs cCs6|ittiid|ittiiddS(s@ Unit-test for testing detranslify's exceptions isтестN(sselfs assertRaisess TypeErrorspytilsstranslits detranslifys ValueError(sself((s7build/bdist.linux-i686/egg/pytils/test/test_translit.pystestDetransliterationExceptionsNscCsD|idd|idd|idd|iddd S( s% Unit-test for slugs uТеСтstestuПроверка связиsproverka-svyaziume&yous me-and-youuи еще один тестsi-esche-odin-testN(sselfsckSlug(sself((s7build/bdist.linux-i686/egg/pytils/test/test_translit.pystestSlugUs cCs6|ittiid|ittiiddS(s< Unit-test for testing slugify's exceptions isтестN(sselfs assertRaisess TypeErrorspytilsstranslitsslugifys ValueError(sself((s7build/bdist.linux-i686/egg/pytils/test/test_translit.pystestSlugExceptions^scCs4|idd|idd|idddS(sB Unit-test for testing additional unicode symbols u«Вот так вот»s "Vot tak vot"u‘Или вот так’s 'Ili vot tak'u – Да…s- Da...N(sselfsckTransl(sself((s7build/bdist.linux-i686/egg/pytils/test/test_translit.pys%testTranslifyAdditionalUnicodeSymbolsescCs4|idd|idd|idddS(s9 Unit-test for testing that bug#10 fixed uПроверка связи…sproverka-svyaziuПроверка связи 2sproverka-svyazi-2uПроверкасвязи 3sproverkasvyazi-3N(sselfsckSlug(sself((s7build/bdist.linux-i686/egg/pytils/test/test_translit.pystestSlugifyIssue10mscCs|idddS(s9 Unit-test for testing that bug#15 fixed uWorld of Warcraftsworld-of-warcraftN(sselfsckSlug(sself((s7build/bdist.linux-i686/egg/pytils/test/test_translit.pystestSlugifyIssue15us(s__name__s __module__s__doc__sckTransls ckDetranslsckSlugstestTransliterationstestTransliterationExceptionsstestDetransliterationstestDetransliterationExceptionsstestSlugstestSlugExceptionss%testTranslifyAdditionalUnicodeSymbolsstestSlugifyIssue10stestSlugifyIssue15(((s7build/bdist.linux-i686/egg/pytils/test/test_translit.pysTranslitTestCases         s__main__( s__doc__s__id__s __revision__s__url__sunittestspytilssTestCasesTranslitTestCases__name__smain(s __revision__sunittestsTranslitTestCases__url__s__id__spytils((s7build/bdist.linux-i686/egg/pytils/test/test_translit.pys?s   ` PKt[6]'^pytils/test/test_utils.pyc; $Ec@sydZdZZdZdkZdkZdeifdYZdeifdYZe djoei ndS( s Unit-tests for pytils.utils s6$Id: test_utils.py 63 2007-01-02 09:22:16Z the.pythy $sO$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/test/test_utils.py $NsUnicodeTestCasecBs;tZdZdZdZdZdZdZRS(s& Test case for unicode-utils cCs#|itii|||dS(s. Check pytils.provide_unicode N(sselfs assertEqualsspytilssutilssprovide_unicodesstextsencodingsutext(sselfsstextsencodingsutext((s4build/bdist.linux-i686/egg/pytils/test/test_utils.pysckProvideUnicodescCs#|itii|||dS(s* Check pytils.provide_str N(sselfs assertEqualsspytilssutilss provide_strsutextsencodingsstext(sselfsutextsencodingsstext((s4build/bdist.linux-i686/egg/pytils/test/test_utils.pys ckProvideStr(scCs|iddddS(s= Unit-tests for pytils.utils.provide_unicode s тест №1sutf-8u тест №1N(sselfsckProvideUnicode(sself((s4build/bdist.linux-i686/egg/pytils/test/test_utils.pystestProvideUnicode1scCs*|iddd|iddddS(s9 Unit-tests for pytils.utils.provide_str u тест №1sutf-8s тест №1skoi8-rsunknownN(sselfs ckProvideStr(sself((s4build/bdist.linux-i686/egg/pytils/test/test_utils.pystestProvideStr7scCs)|itiiddddddS(sR Unit-tests for pytils.utils.provide_str with 'default' parameter u тест №1skoi8-rsdefaultshzN(sselfs assertEqualsspytilssutilss provide_str(sself((s4build/bdist.linux-i686/egg/pytils/test/test_utils.pystestProvideStrNonDefault>s(s__name__s __module__s__doc__sckProvideUnicodes ckProvideStrstestProvideUnicodestestProvideStrstestProvideStrNonDefault(((s4build/bdist.linux-i686/egg/pytils/test/test_utils.pysUnicodeTestCases   sChecksTestCasecBs;tZdZdZdZdZdZdZRS(s% Test case for check_* utils cCsmd}d}|idtiiddd|idtiiddd|ittiiddS( s> Unit-test for pytils.utils.get_value_by_name s25isvar1sdepthisvar2svar3N( svar1svar2sselfs assertEqualsspytilssutilssget_value_by_names assertRaisess RuntimeError(sselfsvar1svar2((s4build/bdist.linux-i686/egg/pytils/test/test_utils.pystestGetValueByNameLs ""cCsd}ytiidtWn+tj o}|idt |nXytiidtt fWn/tj o#}|iddt |nX|it tiidt |it tiidt t fdS(s7 Unit-test for pytils.utils.check_type s25svars*var must be , not s,var must be (, ), snot N( svarspytilssutilss check_typesints TypeErrorserrsselfs assertEqualssstrsfloatsNones basestring(sselfserrsvar((s4build/bdist.linux-i686/egg/pytils/test/test_utils.pys testCheckTypeWs  cCsnd}|ittiiddytiiddWn+tj o}|idt |nXdS(s9 Unit-test for pytils.utils.check_length stestsvariis var's length must be 5, but it 4N( svarsselfs assertEqualssNonespytilssutilss check_lengths ValueErrorserrsstr(sselfserrsvar((s4build/bdist.linux-i686/egg/pytils/test/test_utils.pystestCheckLengthms cCsd}d}d}d}|ittii d|ittii dytii dWn+t j o}|idt |nXytii d Wn+t j o}|id t |nXd S( s; Unit-test for pytils.utils.check_positive if1.25if-2.1200000000000001svar1svar2svar3s%var3 must be positive or zero, not -2svar4s(var4 must be positive or zero, not -2.12N( svar1svar2svar3svar4sselfs assertEqualssNonespytilssutilsscheck_positives ValueErrorserrsstr(sselfsvar4svar1serrsvar3svar2((s4build/bdist.linux-i686/egg/pytils/test/test_utils.pystestCheckPositiveys"  cCsd}d}d}|ittiiddt ytiiddt Wn+t j o}|idt |nXytiidWn+t j o}|id t |nXd S( s; Unit-test for pytils.utils.check_positive iiisvar1sstrictsvar2svar2 must be positive, not 0svar3s%var3 must be positive or zero, not -2N( svar1svar2svar3sselfs assertEqualssNonespytilssutilsscheck_positivesTrues ValueErrorserrsstr(sselfsvar1serrsvar3svar2((s4build/bdist.linux-i686/egg/pytils/test/test_utils.pystestCheckPositiveStricts"  (s__name__s __module__s__doc__stestGetValueByNames testCheckTypestestCheckLengthstestCheckPositivestestCheckPositiveStrict(((s4build/bdist.linux-i686/egg/pytils/test/test_utils.pysChecksTestCaseGs   s__main__( s__doc__s__id__s __revision__s__url__sunittestspytilssTestCasesUnicodeTestCasesChecksTestCases__name__smain(s __revision__sUnicodeTestCasesunittests__url__sChecksTestCases__id__spytils((s4build/bdist.linux-i686/egg/pytils/test/test_utils.pys?s   -_ PK[6CBv$pytils/test/templatetags/__init__.py# -*- coding: utf-8 -*- # PyTils - simple processing for russian strings # Copyright (C) 2006-2007 Yury Yurevich # # http://gorod-omsk.ru/blog/pythy/projects/pytils/ # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation, version 2 # of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. """ Unit tests for pytils' templatetags for Django web framework """ __id__ = __revision__ = "$Id: __init__.py 76 2007-02-27 15:38:53Z the.pythy $" __url__ = "$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/test/templatetags/__init__.py $" __all__ = ["test_numeral", "test_dt", "test_translit"] import unittest def get_suite(): """Return TestSuite for all unit-test of PyTils' templatetags""" suite = unittest.TestSuite() for module_name in __all__: imported_module = __import__("pytils.test.templatetags."+module_name, globals(), locals(), ["pytils.test.templatetags"]) getter = getattr(imported_module, 'get_suite', False) if getter: suite.addTest(getter()) loader = unittest.defaultTestLoader suite.addTest(loader.loadTestsFromModule(imported_module)) return suite def run(verbosity=1): """Run all unit-test of PyTils' templatetags""" suite = get_suite() unittest.TextTestRunner(verbosity=verbosity).run(suite) if __name__ == '__main__': run(2) PK[6 )pytils/test/templatetags/test_translit.py# -*- coding: utf-8 -*- # PyTils - simple processing for russian strings # Copyright (C) 2006-2007 Yury Yurevich # # http://gorod-omsk.ru/blog/pythy/projects/pytils/ # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation, version 2 # of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. """ Unit tests for pytils' translit templatetags for Django web framework """ __id__ = __revision__ = "$Id: test_translit.py 76 2007-02-27 15:38:53Z the.pythy $" __url__ = "$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/test/templatetags/test_translit.py $" from pytils.test.templatetags import helpers class TranslitDefaultTestCase(helpers.TemplateTagTestCase): def test_load(self): self.check_template_tag('load_tag', '{% load pytils_translit %}', {}, '') def test_translify_filter(self): self.check_template_tag('translify_filter', '{% load pytils_translit %}{{ val|translify }}', {'val': 'проверка'}, 'proverka') def test_detranslify_filter(self): self.check_template_tag('detranslify_filter', '{% load pytils_translit %}{{ val|detranslify }}', {'val': 'proverka'}, 'проверка') def test_slugify_filter(self): self.check_template_tag('slugify_filter', '{% load pytils_translit %}{{ val|slugify }}', {'val': 'Проверка связи'}, 'proverka-svyazi') # без отладки, если ошибка -- по умолчанию пустая строка def test_detranslify_error(self): self.check_template_tag('detranslify_error', '{% load pytils_translit %}{{ val|detranslify }}', {'val': 'Проверка связи'}, '') if __name__ == '__main__': import unittest unittest.main() PK[6?c==#pytils/test/templatetags/helpers.py# -*- coding: utf-8 -*- # PyTils - simple processing for russian strings # Copyright (C) 2006-2007 Yury Yurevich # # http://gorod-omsk.ru/blog/pythy/projects/pytils/ # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation, version 2 # of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. """ Helpers for templatetags' unit tests in Django webframework """ __id__ = __revision__ = "$Id: helpers.py 76 2007-02-27 15:38:53Z the.pythy $" __url__ = "$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/test/templatetags/helpers.py $" from django.conf import settings settings.configure( TEMPLATE_DIRS=(), TEMPLATE_CONTEXT_PROCESSORS=(), TEMPLATE_LOADERS=(), INSTALLED_APPS=('pytils',), ) from django import template from django.template import loader import unittest class TemplateTagTestCase(unittest.TestCase): """ TestCase for testing template tags and filters """ def check_template_tag(self, template_name, template_string, context, result_string): """ Method validates output of template tag or filter @param template_name: name of template @type template_name: C{str} @param template_string: contents of template @type template_string: C{str} @param context: rendering context @type context: C{dict} @param result_string: reference output @type result_string: C{str} """ def test_template_loader(template_name, template_dirs=None): return template_string, template_name loader.template_source_loaders = [test_template_loader,] output = loader.get_template(template_name).render(template.Context(context)) self.assertEquals(output, result_string) PK[6#%\ \ (pytils/test/templatetags/test_numeral.py# -*- coding: utf-8 -*- # PyTils - simple processing for russian strings # Copyright (C) 2006-2007 Yury Yurevich # # http://gorod-omsk.ru/blog/pythy/projects/pytils/ # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation, version 2 # of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. """ Unit tests for pytils' numeral templatetags for Django web framework """ __id__ = __revision__ = "$Id: test_numeral.py 76 2007-02-27 15:38:53Z the.pythy $" __url__ = "$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/test/templatetags/test_numeral.py $" from pytils.test.templatetags import helpers class NumeralDefaultTestCase(helpers.TemplateTagTestCase): def test_load(self): self.check_template_tag('load_tag', '{% load pytils_numeral %}', {}, '') def test_choose_plural_filter(self): self.check_template_tag('choose_plural', '{% load pytils_numeral %}{{ val|choose_plural:"гвоздь,гвоздя,гвоздей" }}', {'val': 10}, 'гвоздей') def test_rubles_filter(self): self.check_template_tag('rubles', '{% load pytils_numeral %}{{ val|rubles }}', {'val': 10.1}, 'десять рублей десять копеек') def test_in_words_filter(self): self.check_template_tag('in_words', '{% load pytils_numeral %}{{ val|in_words }}', {'val': 21}, 'двадцать один') self.check_template_tag('in_words', '{% load pytils_numeral %}{{ val|in_words:"NEUTER" }}', {'val': 21}, 'двадцать одно') def sum_string_tag(self): self.check_template_tag('sum_string', '{% load pytils_numeral %}{% sum_string val "MALE" "пример,пример,примеров" %}', {'val': 21}, 'двадцать один пример') # без отладки, если ошибка -- по умолчанию пустая строка def test_choose_plural_error(self): self.check_template_tag('choose_plural_error', '{% load pytils_numeral %}{{ val|choose_plural:"вариант" }}', {'val': 1}, '') if __name__ == '__main__': import unittest unittest.main() PK[6,M M #pytils/test/templatetags/test_dt.py# -*- coding: utf-8 -*- # PyTils - simple processing for russian strings # Copyright (C) 2006-2007 Yury Yurevich # # http://gorod-omsk.ru/blog/pythy/projects/pytils/ # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation, version 2 # of the License. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. """ Unit tests for pytils' dt templatetags for Django web framework """ __id__ = __revision__ = "$Id: test_dt.py 76 2007-02-27 15:38:53Z the.pythy $" __url__ = "$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/test/templatetags/test_dt.py $" import datetime from pytils.test.templatetags import helpers class DtDefaultTestCase(helpers.TemplateTagTestCase): def setUp(self): self.date = datetime.datetime(2007, 1, 26, 15, 50) self.date_before = datetime.datetime.now() - datetime.timedelta(1, 2000) def test_load(self): self.check_template_tag('load_tag', '{% load pytils_dt %}', {}, '') def test_ru_strftime_filter(self): self.check_template_tag('ru_strftime_filter', '{% load pytils_dt %}{{ val|ru_strftime:"%d %B %Y, %A" }}', {'val': self.date}, '26 января 2007, пятница') def test_ru_strftime_inflected_filter(self): self.check_template_tag('ru_strftime_inflected_filter', '{% load pytils_dt %}{{ val|ru_strftime_inflected:"в %A, %d %B %Y" }}', {'val': self.date}, 'в пятницу, 26 января 2007') def test_distance_filter(self): self.check_template_tag('distance_filter', '{% load pytils_dt %}{{ val|distance_of_time }}', {'val': self.date_before}, 'вчера') self.check_template_tag('distance_filter', '{% load pytils_dt %}{{ val|distance_of_time:3 }}', {'val': self.date_before}, '1 день 0 часов 33 минуты назад') # без отладки, если ошибка -- по умолчанию пустая строка def test_ru_strftime_error(self): self.check_template_tag('ru_strftime_error', '{% load pytils_dt %}{{ val|ru_strftime:"%d %B %Y" }}', {'val': 1}, '') if __name__ == '__main__': import unittest unittest.main() PKt[6)g%pytils/test/templatetags/__init__.pyc; PEc@sbdZdZZdZdddgZdkZdZdd Zed joed ndS( s> Unit tests for pytils' templatetags for Django web framework s4$Id: __init__.py 76 2007-02-27 15:38:53Z the.pythy $sZ$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/test/templatetags/__init__.py $s test_numeralstest_dts test_translitNcCsti}x|tD]t}td|ttdg}t |dt }|o|i |nti }|i |i|qW|SdS(s:Return TestSuite for all unit-test of PyTils' templatetagsspytils.test.templatetags.spytils.test.templatetagss get_suiteN(sunittests TestSuitessuites__all__s module_names __import__sglobalsslocalssimported_modulesgetattrsFalsesgettersaddTestsdefaultTestLoadersloadersloadTestsFromModule(sloaders module_namessuitesgettersimported_module((s?build/bdist.linux-i686/egg/pytils/test/templatetags/__init__.pys get_suites    icCs&t}tid|i|dS(s)Run all unit-test of PyTils' templatetagss verbosityN(s get_suitessuitesunittestsTextTestRunners verbositysrun(s verbosityssuite((s?build/bdist.linux-i686/egg/pytils/test/templatetags/__init__.pysrun,s s__main__i( s__doc__s__id__s __revision__s__url__s__all__sunittests get_suitesruns__name__(s __revision__sruns__all__s get_suitesunittests__url__s__id__((s?build/bdist.linux-i686/egg/pytils/test/templatetags/__init__.pys?s     PKt[6BtN N *pytils/test/templatetags/test_translit.pyc; PEc@sddZdZZdZdklZdeifdYZedjodk Z e i ndS(sG Unit tests for pytils' translit templatetags for Django web framework s9$Id: test_translit.py 76 2007-02-27 15:38:53Z the.pythy $s_$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/test/templatetags/test_translit.py $(shelperssTranslitDefaultTestCasecBs5tZdZdZdZdZdZRS(NcCs|iddhddS(Nsload_tags{% load pytils_translit %}s(sselfscheck_template_tag(sself((sDbuild/bdist.linux-i686/egg/pytils/test/templatetags/test_translit.pys test_loadscCs#|iddhddbuild/bdist.linux-i686/egg/pytils/test/templatetags/helpers.pystest_template_loader;sN(sNonestest_template_loadersloaderstemplate_source_loaderss get_templates template_namesrenderstemplatesContextscontextsoutputsselfs assertEqualss result_string(sselfs template_namestemplate_stringscontexts result_stringstest_template_loadersoutput((stemplate_strings>build/bdist.linux-i686/egg/pytils/test/templatetags/helpers.pyscheck_template_tag*s  !(s__name__s __module__s__doc__scheck_template_tag(((s>build/bdist.linux-i686/egg/pytils/test/templatetags/helpers.pysTemplateTagTestCase&s (s__doc__s__id__s __revision__s__url__s django.confssettingss configuresdjangostemplatesdjango.templatesloadersunittestsTestCasesTemplateTagTestCase(s __revision__ssettingssTemplateTagTestCasesunittestsloaders__url__s__id__stemplate((s>build/bdist.linux-i686/egg/pytils/test/templatetags/helpers.pys?s       PKt[67Q1 )pytils/test/templatetags/test_numeral.pyc; PEc@sddZdZZdZdklZdeifdYZedjodk Z e i ndS(sF Unit tests for pytils' numeral templatetags for Django web framework s8$Id: test_numeral.py 76 2007-02-27 15:38:53Z the.pythy $s^$URL: https://pythy.googlecode.com/svn/trunk/pytils/pytils/test/templatetags/test_numeral.py $(shelperssNumeralDefaultTestCasecBs>tZdZdZdZdZdZdZRS(NcCs|iddhddS(Nsload_tags{% load pytils_numeral %}s(sselfscheck_template_tag(sself((sCbuild/bdist.linux-i686/egg/pytils/test/templatetags/test_numeral.pys test_loadscCs#|iddhddtZdZdZdZdZdZdZRS(NcCsDtiddddd|_tiitidd|_dS(Niiiii2i(sdatetimesselfsdatesnows timedeltas date_before(sself((s>build/bdist.linux-i686/egg/pytils/test/templatetags/test_dt.pyssetUpscCs|iddhddS(Nsload_tags{% load pytils_dt %}s(sselfscheck_template_tag(sself((s>build/bdist.linux-i686/egg/pytils/test/templatetags/test_dt.pys test_load scCs&|iddhd|ibuild/bdist.linux-i686/egg/pytils/test/templatetags/test_dt.pystest_ru_strftime_filter#s cCs&|iddhd|ibuild/bdist.linux-i686/egg/pytils/test/templatetags/test_dt.pys!test_ru_strftime_inflected_filter)s cCsH|iddhd|ibuild/bdist.linux-i686/egg/pytils/test/templatetags/test_dt.pystest_distance_filter/s  cCs#|iddhddbuild/bdist.linux-i686/egg/pytils/test/templatetags/test_dt.pystest_ru_strftime_error;s  (s__name__s __module__ssetUps test_loadstest_ru_strftime_filters!test_ru_strftime_inflected_filterstest_distance_filterstest_ru_strftime_error(((s>build/bdist.linux-i686/egg/pytils/test/templatetags/test_dt.pysDtDefaultTestCases      s__main__( s__doc__s__id__s __revision__s__url__sdatetimespytils.test.templatetagsshelperssTemplateTagTestCasesDtDefaultTestCases__name__sunittestsmain(s __revision__sDtDefaultTestCasesdatetimes__url__shelperss__id__sunittest((s>build/bdist.linux-i686/egg/pytils/test/templatetags/test_dt.pys?s   (  PKt[6j#ۣEGG-INFO/PKG-INFOMetadata-Version: 1.0 Name: pytils Version: 0.2.1 Summary: Utils for easy processing string in russian. Home-page: http://gorod-omsk.ru/blog/pythy/projects/pytils/ Author: Yury Yurevich Author-email: the.pythy@gmail.com License: GPL Download-URL: http://pythy.googlecode.com/svn/tags/pytils/0_2_1/dist/ Description: Simple tools for processing string in russian (choose proper form for plurals, in-words representation of numerals, dates in russian without locales, transliteration, etc) Platform: All Classifier: Topic :: Software Development :: Libraries :: Python Modules Classifier: Topic :: Text Processing :: Linguistic Classifier: License :: OSI Approved :: GNU General Public License (GPL) Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Natural Language :: Russian Classifier: Development Status :: 4 - Beta Classifier: Intended Audience :: Developers PKt[6ADEGG-INFO/SOURCES.txtAUTHORS Changelog LICENSE MANIFEST.in README TODO setup.py doc/INSTALL doc/INSTALL.rus.txt doc/README.rus.txt doc/WEBFRAMEWORKS.rus.txt doc/api/api-objects.txt doc/api/class-tree.html doc/api/crarr.png doc/api/epydoc.css doc/api/epydoc.js doc/api/exceptions.AssertionError-class.html doc/api/help.html doc/api/identifier-index.html doc/api/index.html doc/api/module-tree.html doc/api/pytils-module.html doc/api/pytils-pysrc.html doc/api/pytils.dt-module.html doc/api/pytils.dt-pysrc.html doc/api/pytils.numeral-module.html doc/api/pytils.numeral-pysrc.html doc/api/pytils.templatetags-module.html doc/api/pytils.templatetags-pysrc.html doc/api/pytils.templatetags.pytils_dt-module.html doc/api/pytils.templatetags.pytils_dt-pysrc.html doc/api/pytils.templatetags.pytils_numeral-module.html doc/api/pytils.templatetags.pytils_numeral-pysrc.html doc/api/pytils.templatetags.pytils_translit-module.html doc/api/pytils.templatetags.pytils_translit-pysrc.html doc/api/pytils.test-module.html doc/api/pytils.test-pysrc.html doc/api/pytils.test.templatetags-module.html doc/api/pytils.test.templatetags-pysrc.html doc/api/pytils.test.templatetags.helpers-module.html doc/api/pytils.test.templatetags.helpers-pysrc.html doc/api/pytils.test.templatetags.helpers.TemplateTagTestCase-class.html doc/api/pytils.test.templatetags.test_dt-module.html doc/api/pytils.test.templatetags.test_dt-pysrc.html doc/api/pytils.test.templatetags.test_dt.DtDefaultTestCase-class.html doc/api/pytils.test.templatetags.test_numeral-module.html doc/api/pytils.test.templatetags.test_numeral-pysrc.html doc/api/pytils.test.templatetags.test_numeral.NumeralDefaultTestCase-class.html doc/api/pytils.test.templatetags.test_translit-module.html doc/api/pytils.test.templatetags.test_translit-pysrc.html doc/api/pytils.test.templatetags.test_translit.TranslitDefaultTestCase-class.html doc/api/pytils.test.test_dt-module.html doc/api/pytils.test.test_dt-pysrc.html doc/api/pytils.test.test_dt.DistanceOfTimeInWordsTestCase-class.html doc/api/pytils.test.test_dt.RuStrftimeTestCase-class.html doc/api/pytils.test.test_numeral-module.html doc/api/pytils.test.test_numeral-pysrc.html doc/api/pytils.test.test_numeral.ChoosePluralTestCase-class.html doc/api/pytils.test.test_numeral.GetFloatRemainderTestCase-class.html doc/api/pytils.test.test_numeral.InWordsTestCase-class.html doc/api/pytils.test.test_numeral.RublesTestCase-class.html doc/api/pytils.test.test_numeral.SumStringTestCase-class.html doc/api/pytils.test.test_translit-module.html doc/api/pytils.test.test_translit-pysrc.html doc/api/pytils.test.test_translit.TranslitTestCase-class.html doc/api/pytils.test.test_utils-module.html doc/api/pytils.test.test_utils-pysrc.html doc/api/pytils.test.test_utils.ChecksTestCase-class.html doc/api/pytils.test.test_utils.UnicodeTestCase-class.html doc/api/pytils.translit-module.html doc/api/pytils.translit-pysrc.html doc/api/pytils.utils-module.html doc/api/pytils.utils-pysrc.html doc/api/redirect.html doc/examples/dt.distance_of_time_in_words.py doc/examples/dt.ru_strftime.py doc/examples/numeral.choose_plural.py doc/examples/numeral.in_words.py doc/examples/numeral.rubles.py doc/examples/numeral.sum_string.py doc/examples/translit.py doc/examples-django/README doc/examples-django/pytilsex/__init__.py doc/examples-django/pytilsex/manage.py doc/examples-django/pytilsex/settings.py doc/examples-django/pytilsex/urls.py doc/examples-django/pytilsex/static/css/style.css doc/examples-django/pytilsex/static/images/header_inner.png doc/examples-django/pytilsex/templates/base.html doc/examples-django/pytilsex/templates/dt.html doc/examples-django/pytilsex/templates/numeral.html doc/examples-django/pytilsex/templates/translit.html doc/examples-turbogears/README doc/examples-turbogears/dev.cfg doc/examples-turbogears/setup.py doc/examples-turbogears/start-pytilsex.py doc/examples-turbogears/pytilsex/__init__.py doc/examples-turbogears/pytilsex/controllers.py doc/examples-turbogears/pytilsex/model.py doc/examples-turbogears/pytilsex/config/__init__.py doc/examples-turbogears/pytilsex/config/app.cfg doc/examples-turbogears/pytilsex/config/log.cfg doc/examples-turbogears/pytilsex/static/css/style.css doc/examples-turbogears/pytilsex/static/images/favicon.ico doc/examples-turbogears/pytilsex/static/images/header_inner.png doc/examples-turbogears/pytilsex/templates/__init__.py doc/examples-turbogears/pytilsex/templates/dt.kid doc/examples-turbogears/pytilsex/templates/master.kid doc/examples-turbogears/pytilsex/templates/numeral.kid doc/examples-turbogears/pytilsex/templates/root.kid doc/examples-turbogears/pytilsex/templates/translit.kid pytils/__init__.py pytils/dt.py pytils/numeral.py pytils/translit.py pytils/utils.py pytils.egg-info/PKG-INFO pytils.egg-info/SOURCES.txt pytils.egg-info/dependency_links.txt pytils.egg-info/top_level.txt pytils.egg-info/zip-safe pytils/templatetags/__init__.py pytils/templatetags/pytils_dt.py pytils/templatetags/pytils_numeral.py pytils/templatetags/pytils_translit.py pytils/test/__init__.py pytils/test/test_dt.py pytils/test/test_numeral.py pytils/test/test_translit.py pytils/test/test_utils.py pytils/test/templatetags/__init__.py pytils/test/templatetags/helpers.py pytils/test/templatetags/test_dt.py pytils/test/templatetags/test_numeral.py pytils/test/templatetags/test_translit.py PKt[62EGG-INFO/dependency_links.txt PKt[6\_EGG-INFO/top_level.txtpytils PKP[62EGG-INFO/zip-safe PK[6,Qu u pytils/__init__.pyPKz"6lvv pytils/dt.pyPKz"6\H6H6E*pytils/numeral.pyPKz"6ZTT`pytils/translit.pyPKz"6d"6@|pytils/utils.pyPKt[6م  pytils/__init__.pycPKt[6Ϲ< _pytils/dt.pycPKt[6٪ r6r6gpytils/numeral.pycPKt[6[:W pytils/translit.pycPKt[6Txpytils/utils.pycPKz"6PsLNNpytils/templatetags/__init__.pyPKMS6|7++ pytils/templatetags/pytils_dt.pyPKMS6ܾdLL% #pytils/templatetags/pytils_numeral.pyPKMS6͸ &7pytils/templatetags/pytils_translit.pyPKt[6 Dpytils/templatetags/__init__.pycPKt[63kIm!Fpytils/templatetags/pytils_dt.pycPKt[6$&Vpytils/templatetags/pytils_numeral.pycPKt[6iW'" " 'jpytils/templatetags/pytils_translit.pycPKMS67%%Lvpytils/test/__init__.pyPKz"6Ti,,}pytils/test/test_dt.pyPKz"6 >>Ъpytils/test/test_numeral.pyPKz"6ēLpytils/test/test_translit.pyPKz"6)WD!!'pytils/test/test_utils.pyPKt[6Ypytils/test/__init__.pycPKt[6 22pytils/test/test_dt.pycPKt[6?kAAJpytils/test/test_numeral.pycPKt[6?ٍƌpytils/test/test_translit.pycPKt[6]'^pytils/test/test_utils.pycPK[6CBv$Ծpytils/test/templatetags/__init__.pyPK[6 )pytils/test/templatetags/test_translit.pyPK[6?c==#pytils/test/templatetags/helpers.pyPK[6#%\ \ (ypytils/test/templatetags/test_numeral.pyPK[6,M M #pytils/test/templatetags/test_dt.pyPKt[6)g%pytils/test/templatetags/__init__.pycPKt[6BtN N * pytils/test/templatetags/test_translit.pycPKt[6EGG-INFO/dependency_links.txtPKt[6\_E>EGG-INFO/top_level.txtPKP[62>EGG-INFO/zip-safePK++Z >