diff options
32 files changed, 345 insertions, 313 deletions
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 2598b51..f226347 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -4,8 +4,9 @@ - id: trailing-whitespace - id: end-of-file-fixer - id: autopep8-wrapper - exclude: (tests/messages/data/) + exclude: (docs/conf.py|tests/messages/data/) - id: check-docstring-first + exclude: (docs/conf.py) - id: check-json - id: check-added-large-files - id: check-yaml diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e492cee..4976273 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -39,7 +39,7 @@ For a PR to be merged, the following statements must hold true: not the author of the PR. Commits shall comply to the "Good Commits" standards outlined below. -To begin contributing have a look at the open [easy issues](https://github.com/python-babel/babel/issues?q=is%3Aopen+is%3Aissue+label%3Adifficulty%2Flow) +To begin contributing have a look at the open [easy issues](https://github.com/python-babel/babel/issues?q=is%3Aopen+is%3Aissue+label%3Adifficulty%2Flow) which could be fixed. ## Correcting PRs diff --git a/babel/__init__.py b/babel/__init__.py index d2e5259..d6b5485 100644 --- a/babel/__init__.py +++ b/babel/__init__.py @@ -18,7 +18,7 @@ """ from babel.core import UnknownLocaleError, Locale, default_locale, \ - negotiate_locale, parse_locale, get_locale_identifier + negotiate_locale, parse_locale, get_locale_identifier __version__ = '2.2.0.dev0' diff --git a/babel/dates.py b/babel/dates.py index 1af9955..8e34094 100644 --- a/babel/dates.py +++ b/babel/dates.py @@ -477,7 +477,7 @@ def get_timezone_location(dt_or_tzinfo=None, locale=LC_TIME, return_city=False): region_format = locale.zone_formats['region'] territory = get_global('zone_territories').get(zone) if territory not in locale.territories: - territory = 'ZZ' # invalid/unknown + territory = 'ZZ' # invalid/unknown territory_name = locale.territories[territory] if not return_city and territory and len(get_global('territory_zones').get(territory, [])) == 1: return region_format % (territory_name) @@ -756,7 +756,7 @@ def format_time(time=None, format='medium', tzinfo=None, locale=LC_TIME): if isinstance(time, datetime): if tzinfo is not None: time = time.astimezone(tzinfo) - if hasattr(tzinfo, 'normalize'): # pytz + if hasattr(tzinfo, 'normalize'): # pytz time = tzinfo.normalize(time) time = time.timetz() elif tzinfo is not None: @@ -807,11 +807,11 @@ def format_skeleton(skeleton, datetime=None, tzinfo=None, fuzzy=True, locale=LC_ TIMEDELTA_UNITS = ( - ('year', 3600 * 24 * 365), - ('month', 3600 * 24 * 30), - ('week', 3600 * 24 * 7), - ('day', 3600 * 24), - ('hour', 3600), + ('year', 3600 * 24 * 365), + ('month', 3600 * 24 * 30), + ('week', 3600 * 24 * 7), + ('day', 3600 * 24), + ('hour', 3600), ('minute', 60), ('second', 1) ) @@ -1250,7 +1250,7 @@ class DateTimeFormat(object): return get_month_names(width, context, self.locale)[self.value.month] def format_week(self, char, num): - if char.islower(): # week of year + if char.islower(): # week of year day_of_year = self.get_day_of_year() week = self.get_week_number(day_of_year) if week == 0: @@ -1258,7 +1258,7 @@ class DateTimeFormat(object): week = self.get_week_number(self.get_day_of_year(date), date.weekday()) return self.format(week, num) - else: # week of month + else: # week of month week = self.get_week_number(self.value.day) if week == 0: date = self.value - timedelta(days=self.value.day) @@ -1292,7 +1292,7 @@ class DateTimeFormat(object): def format_milliseconds_in_day(self, num): msecs = self.value.microsecond // 1000 + self.value.second * 1000 + \ - self.value.minute * 60000 + self.value.hour * 3600000 + self.value.minute * 60000 + self.value.hour * 3600000 return self.format(msecs, num) def format_timezone(self, char, num): diff --git a/babel/languages.py b/babel/languages.py index a770871..40f5d98 100644 --- a/babel/languages.py +++ b/babel/languages.py @@ -42,7 +42,6 @@ def get_official_languages(territory, regional=False, de_facto=False): return tuple(lang for _, lang in pairs) - def get_territory_language_info(territory): """ Get a dictionary of language information for a territory. diff --git a/babel/localedata.py b/babel/localedata.py index 437f49f..985e743 100644 --- a/babel/localedata.py +++ b/babel/localedata.py @@ -190,13 +190,13 @@ class LocaleDataDict(MutableMapping): def __getitem__(self, key): orig = val = self._data[key] - if isinstance(val, Alias): # resolve an alias + if isinstance(val, Alias): # resolve an alias val = val.resolve(self.base) - if isinstance(val, tuple): # Merge a partial dict with an alias + if isinstance(val, tuple): # Merge a partial dict with an alias alias, others = val val = alias.resolve(self.base).copy() merge(val, others) - if type(val) is dict: # Return a nested alias-resolving dict + if type(val) is dict: # Return a nested alias-resolving dict val = LocaleDataDict(val, base=self.base) if val is not orig: self._data[key] = val diff --git a/babel/localtime/__init__.py b/babel/localtime/__init__.py index 4cab236..883ff16 100644 --- a/babel/localtime/__init__.py +++ b/babel/localtime/__init__.py @@ -26,9 +26,9 @@ else: _cached_tz = None _cache_lock = RLock() -STDOFFSET = timedelta(seconds = -time.timezone) +STDOFFSET = timedelta(seconds=-time.timezone) if time.daylight: - DSTOFFSET = timedelta(seconds = -time.altzone) + DSTOFFSET = timedelta(seconds=-time.altzone) else: DSTOFFSET = STDOFFSET diff --git a/babel/localtime/_unix.py b/babel/localtime/_unix.py index b4a3b59..378a90b 100644 --- a/babel/localtime/_unix.py +++ b/babel/localtime/_unix.py @@ -27,6 +27,7 @@ def _tz_from_env(tzenv): "tzlocal() does not support non-zoneinfo timezones like %s. \n" "Please use a timezone in the form of Continent/City") + def _get_localzone(_root='/'): """Tries to find the local timezone configuration. This method prefers finding the timezone name and passing that to pytz, diff --git a/babel/messages/catalog.py b/babel/messages/catalog.py index ca4a568..8c807f8 100644 --- a/babel/messages/catalog.py +++ b/babel/messages/catalog.py @@ -378,8 +378,8 @@ class Catalog(object): headers.append(('Language', str(self.locale))) if (self.locale is not None) and ('LANGUAGE' in self.language_team): headers.append(('Language-Team', - self.language_team.replace('LANGUAGE', - str(self.locale)))) + self.language_team.replace('LANGUAGE', + str(self.locale)))) else: headers.append(('Language-Team', self.language_team)) if self.locale is not None: @@ -779,7 +779,7 @@ class Catalog(object): if no_fuzzy_matching is False: # do some fuzzy matching with difflib if isinstance(key, tuple): - matchkey = key[0] # just the msgid, no context + matchkey = key[0] # just the msgid, no context else: matchkey = key matches = get_close_matches(matchkey.lower().strip(), diff --git a/babel/messages/extract.py b/babel/messages/extract.py index c2dcd5b..b383bdb 100644 --- a/babel/messages/extract.py +++ b/babel/messages/extract.py @@ -45,8 +45,8 @@ DEFAULT_KEYWORDS = { DEFAULT_MAPPING = [('**.py', 'python')] empty_msgid_warning = ( -'%s: warning: Empty msgid. It is reserved by GNU gettext: gettext("") ' -'returns the header entry with meta information, not the empty string.') + '%s: warning: Empty msgid. It is reserved by GNU gettext: gettext("") ' + 'returns the header entry with meta information, not the empty string.') def _strip_comment_tags(comments, tags): @@ -354,8 +354,8 @@ def extract(method, fileobj, keywords=DEFAULT_KEYWORDS, comment_tags=(), first_msg_index = spec[0] - 1 if not messages[first_msg_index]: # An empty string msgid isn't valid, emit a warning - where = '%s:%i' % (hasattr(fileobj, 'name') and \ - fileobj.name or '(unknown)', lineno) + where = '%s:%i' % (hasattr(fileobj, 'name') and + fileobj.name or '(unknown)', lineno) sys.stderr.write((empty_msgid_warning % where) + '\n') continue @@ -471,7 +471,7 @@ def extract_python(fileobj, keywords, comment_tags, options): # https://sourceforge.net/tracker/?func=detail&atid=355470& # aid=617979&group_id=5470 value = eval('# coding=%s\n%s' % (str(encoding), value), - {'__builtins__':{}}, {}) + {'__builtins__': {}}, {}) if PY2 and not isinstance(value, text_type): value = value.decode(encoding) buf.append(value) @@ -487,7 +487,7 @@ def extract_python(fileobj, keywords, comment_tags, options): # Let's increase the last comment's lineno in order # for the comment to still be a valid one old_lineno, old_comment = translator_comments.pop() - translator_comments.append((old_lineno+1, old_comment)) + translator_comments.append((old_lineno + 1, old_comment)) elif call_stack > 0 and tok == OP and value == ')': call_stack -= 1 elif funcname and call_stack == -1: @@ -597,16 +597,16 @@ def extract_javascript(fileobj, keywords, comment_tags, options): concatenate_next = True elif call_stack > 0 and token.type == 'operator' \ - and token.value == ')': + and token.value == ')': call_stack -= 1 elif funcname and call_stack == -1: funcname = None elif call_stack == -1 and token.type == 'name' and \ - token.value in keywords and \ - (last_token is None or last_token.type != 'name' or - last_token.value != 'function'): + token.value in keywords and \ + (last_token is None or last_token.type != 'name' or + last_token.value != 'function'): funcname = token.value last_token = token diff --git a/babel/messages/frontend.py b/babel/messages/frontend.py index 9bb46bb..3cacec9 100644 --- a/babel/messages/frontend.py +++ b/babel/messages/frontend.py @@ -398,7 +398,6 @@ class extract_messages(Command): catalog.add(message, None, [(filepath, lineno)], auto_comments=comments, context=context) - self.log.info('writing PO template file to %s' % self.output_file) write_po(outfile, catalog, width=self.width, no_location=self.no_location, @@ -710,8 +709,8 @@ class CommandLineInterface(object): commands = { 'compile': 'compile message catalogs to MO files', 'extract': 'extract messages from source files and generate a POT file', - 'init': 'create new message catalogs from a POT file', - 'update': 'update existing message catalogs from a POT file' + 'init': 'create new message catalogs from a POT file', + 'update': 'update existing message catalogs from a POT file' } command_classes = { diff --git a/babel/messages/mofile.py b/babel/messages/mofile.py index 2ab96d5..79042e0 100644 --- a/babel/messages/mofile.py +++ b/babel/messages/mofile.py @@ -41,7 +41,7 @@ def read_mo(fileobj): # Parse the .mo file header, which consists of 5 little endian 32 # bit words. - magic = unpack('<I', buf[:4])[0] # Are we big endian or little endian? + magic = unpack('<I', buf[:4])[0] # Are we big endian or little endian? if magic == LE_MAGIC: version, msgcount, origidx, transidx = unpack('<4I', buf[4:20]) ii = '<II' @@ -79,12 +79,12 @@ def read_mo(fileobj): elif lastkey: headers[lastkey] += b'\n' + item - if b'\x04' in msg: # context + if b'\x04' in msg: # context ctxt, msg = msg.split(b'\x04') else: ctxt = None - if b'\x00' in msg: # plural forms + if b'\x00' in msg: # plural forms msg = msg.split(b'\x00') tmsg = tmsg.split(b'\x00') if catalog.charset: @@ -184,7 +184,7 @@ def write_mo(fileobj, catalog, use_fuzzy=False): msgstr = message.string.encode(catalog.charset) if message.context: msgid = b'\x04'.join([message.context.encode(catalog.charset), - msgid]) + msgid]) offsets.append((len(ids), len(msgid), len(strs), len(msgstr))) ids += msgid + b'\x00' strs += msgstr + b'\x00' @@ -204,10 +204,10 @@ def write_mo(fileobj, catalog, use_fuzzy=False): offsets = koffsets + voffsets fileobj.write(struct.pack('Iiiiiii', - LE_MAGIC, # magic - 0, # version - len(messages), # number of entries - 7 * 4, # start of key index - 7 * 4 + len(messages) * 8, # start of value index - 0, 0 # size and offset of hash table - ) + array_tobytes(array.array("i", offsets)) + ids + strs) + LE_MAGIC, # magic + 0, # version + len(messages), # number of entries + 7 * 4, # start of key index + 7 * 4 + len(messages) * 8, # start of value index + 0, 0 # size and offset of hash table + ) + array_tobytes(array.array("i", offsets)) + ids + strs) diff --git a/babel/messages/pofile.py b/babel/messages/pofile.py index 1fb2c1c..00a21f4 100644 --- a/babel/messages/pofile.py +++ b/babel/messages/pofile.py @@ -163,8 +163,13 @@ def read_po(fileobj, locale=None, domain=None, ignore_obsolete=False, charset=No catalog.obsolete[msgid] = message else: catalog[msgid] = message - del messages[:]; del translations[:]; del context[:]; del locations[:]; - del flags[:]; del auto_comments[:]; del user_comments[:]; + del messages[:] + del translations[:] + del context[:] + del locations[:] + del flags[:] + del auto_comments[:] + del user_comments[:] obsolete[0] = False counter[0] += 1 @@ -230,7 +235,7 @@ def read_po(fileobj, locale=None, domain=None, ignore_obsolete=False, charset=No elif line[1:].startswith('.'): # These are called auto-comments comment = line[2:].strip() - if comment: # Just check that we're not adding empty comments + if comment: # Just check that we're not adding empty comments auto_comments.append(comment) else: # These are called user comments @@ -252,10 +257,10 @@ def read_po(fileobj, locale=None, domain=None, ignore_obsolete=False, charset=No WORD_SEP = re.compile('(' - r'\s+|' # any whitespace - r'[^\s\w]*\w+[a-zA-Z]-(?=\w+[a-zA-Z])|' # hyphenated words - r'(?<=[\w\!\"\'\&\.\,\?])-{2,}(?=\w)' # em-dash -')') + r'\s+|' # any whitespace + r'[^\s\w]*\w+[a-zA-Z]-(?=\w+[a-zA-Z])|' # hyphenated words + r'(?<=[\w\!\"\'\&\.\,\?])-{2,}(?=\w)' # em-dash + ')') def escape(string): @@ -434,7 +439,7 @@ def write_po(fileobj, catalog, width=76, no_location=False, omit_header=False, sort_by = "location" for message in _sort_messages(catalog, sort_by=sort_by): - if not message.id: # This is the header "message" + if not message.id: # This is the header "message" if omit_header: continue comment_header = catalog.header_comment diff --git a/babel/numbers.py b/babel/numbers.py index e4b3e8e..c4a2b20 100644 --- a/babel/numbers.py +++ b/babel/numbers.py @@ -137,8 +137,8 @@ def get_territory_currencies(territory, start_date=None, end_date=None, start = date_(*start) if end: end = date_(*end) - if ((is_tender and tender) or \ - (not is_tender and non_tender)) and _is_active(start, end): + if ((is_tender and tender) or + (not is_tender and non_tender)) and _is_active(start, end): if include_details: result.append({ 'currency': currency_code, @@ -438,7 +438,7 @@ def parse_decimal(string, locale=LC_NUMERIC): locale = Locale.parse(locale) try: return Decimal(string.replace(get_group_symbol(locale), '') - .replace(get_decimal_symbol(locale), '.')) + .replace(get_decimal_symbol(locale), '.')) except InvalidOperation: raise NumberFormatError('%r is not a valid decimal number' % string) @@ -528,7 +528,7 @@ def parse_pattern(pattern): int_prec = parse_precision(integer) frac_prec = parse_precision(fraction) if exp: - frac_prec = parse_precision(integer+fraction) + frac_prec = parse_precision(integer + fraction) exp_plus = exp.startswith('+') exp = exp.lstrip('+') exp_prec = parse_precision(exp) @@ -570,7 +570,7 @@ class NumberPattern(object): value = Decimal(str(value)) value = value.scaleb(self.scale) is_negative = int(value.is_signed()) - if self.exp_prec: # Scientific notation + if self.exp_prec: # Scientific notation exp = value.adjusted() value = abs(value) # Minimum number of integer digits @@ -590,11 +590,11 @@ class NumberPattern(object): exp_sign = get_plus_sign_symbol(locale) exp = abs(exp) number = u'%s%s%s%s' % \ - (self._format_significant(value, frac_prec[0], frac_prec[1]), - get_exponential_symbol(locale), exp_sign, - self._format_int(str(exp), self.exp_prec[0], - self.exp_prec[1], locale)) - elif '@' in self.pattern: # Is it a siginificant digits pattern? + (self._format_significant(value, frac_prec[0], frac_prec[1]), + get_exponential_symbol(locale), exp_sign, + self._format_int(str(exp), self.exp_prec[0], + self.exp_prec[1], locale)) + elif '@' in self.pattern: # Is it a siginificant digits pattern? text = self._format_significant(abs(value), self.int_prec[0], self.int_prec[1]) @@ -602,7 +602,7 @@ class NumberPattern(object): number = self._format_int(a, 0, 1000, locale) if sep: number += get_decimal_symbol(locale) + b - else: # A normal number pattern + else: # A normal number pattern precision = Decimal('1.' + '1' * frac_prec[1]) rounded = value.quantize(precision, ROUND_HALF_EVEN) a, sep, b = str(abs(rounded)).partition(".") @@ -610,10 +610,10 @@ class NumberPattern(object): self.int_prec[1], locale) + self._format_frac(b or '0', locale, force_frac)) retval = u'%s%s%s' % (self.prefix[is_negative], number, - self.suffix[is_negative]) + self.suffix[is_negative]) if u'¤' in retval: retval = retval.replace(u'¤¤¤', - get_currency_name(currency, value, locale)) + get_currency_name(currency, value, locale)) retval = retval.replace(u'¤¤', currency.upper()) retval = retval.replace(u'¤', get_currency_symbol(currency, locale)) return retval @@ -649,11 +649,11 @@ class NumberPattern(object): i = len(intpart) j = i + max(minimum - i, 0) result = "{intpart}.{pad:0<{fill}}{fracpart}{fracextra}".format( - intpart=intpart or '0', - pad='', - fill=-min(exp + 1, 0), - fracpart=digits[i:j], - fracextra=digits[j:].rstrip('0'), + intpart=intpart or '0', + pad='', + fill=-min(exp + 1, 0), + fracpart=digits[i:j], + fracextra=digits[j:].rstrip('0'), ).rstrip('.') return result diff --git a/babel/plural.py b/babel/plural.py index 9cb1d5c..980629d 100644 --- a/babel/plural.py +++ b/babel/plural.py @@ -186,9 +186,9 @@ def to_python(rule): :raise RuleError: if the expression is malformed """ namespace = { - 'IN': in_range_list, - 'WITHIN': within_range_list, - 'MOD': cldr_modulo, + 'IN': in_range_list, + 'WITHIN': within_range_list, + 'MOD': cldr_modulo, 'extract_operands': extract_operands, } to_python_func = _PythonCompiler().compile diff --git a/babel/support.py b/babel/support.py index e803138..24bc9aa 100644 --- a/babel/support.py +++ b/babel/support.py @@ -17,9 +17,9 @@ import locale from babel.core import Locale from babel.dates import format_date, format_datetime, format_time, \ - format_timedelta + format_timedelta from babel.numbers import format_number, format_decimal, format_currency, \ - format_percent, format_scientific + format_percent, format_scientific from babel._compat import PY2, text_type, text_to_native @@ -340,7 +340,7 @@ class NullTranslations(gettext.NullTranslations, object): """ return self._domains.get(domain, self).ungettext(singular, plural, num) # backward compatibility with 0.9 - dungettext = udngettext + dungettext = udngettext # Most of the downwards code, until it get's included in stdlib, from: # http://bugs.python.org/file10036/gettext-pgettext.patch diff --git a/babel/util.py b/babel/util.py index 54f7d2d..c0a9417 100644 --- a/babel/util.py +++ b/babel/util.py @@ -41,6 +41,8 @@ def distinct(iterable): # Regexp to match python magic encoding line PYTHON_MAGIC_COMMENT_re = re.compile( br'[ \t\f]* \# .* coding[=:][ \t]*([-\w.]+)', re.VERBOSE) + + def parse_encoding(fp): """Deduce the encoding of a source file from magic comment. @@ -90,6 +92,7 @@ def parse_encoding(fp): finally: fp.seek(pos) + def pathmatch(pattern, filename): """Extended pathname pattern matching. @@ -119,12 +122,12 @@ def pathmatch(pattern, filename): :param filename: the path name of the file to match against """ symbols = { - '?': '[^/]', - '?/': '[^/]/', - '*': '[^/]+', - '*/': '[^/]+/', + '?': '[^/]', + '?/': '[^/]/', + '*': '[^/]+', + '*/': '[^/]+/', '**/': '(?:.+/)*?', - '**': '(?:.+/)*?[^/]+', + '**': '(?:.+/)*?[^/]+', } buf = [] for idx, part in enumerate(re.split('([?*]+/?)', pattern)): @@ -165,6 +168,7 @@ class odict(dict): :see: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/107747 """ + def __init__(self, data=None): dict.__init__(self, data or {}) self._keys = list(dict.keys(self)) @@ -216,7 +220,7 @@ class odict(dict): self._keys.remove(key) return dict.popitem(key) - def setdefault(self, key, failobj = None): + def setdefault(self, key, failobj=None): dict.setdefault(self, key, failobj) if key not in self._keys: self._keys.append(key) diff --git a/contrib/babel.js b/contrib/babel.js index 8ebab97..506efeb 100644 --- a/contrib/babel.js +++ b/contrib/babel.js @@ -138,7 +138,7 @@ var babel = new function() { * * babel.format(_('Hello %s'), name) * babel.format(_('Progress: %(percent)s%%'), {percent: 100}) - */ + */ this.format = function() { var arg, string = arguments[0], idx = 0; if (arguments.length == 1) @@ -153,7 +153,7 @@ var babel = new function() { return string.replace(formatRegex, function(all, name, type) { if (all[0] == all[1]) return all.substring(1); var value = arg[name || idx++]; - return (type == 'i' || type == 'd') ? +value : value; + return (type == 'i' || type == 'd') ? +value : value; }); } diff --git a/scripts/make-release.py b/scripts/make-release.py index 463ab28..a695da2 100755 --- a/scripts/make-release.py +++ b/scripts/make-release.py @@ -63,6 +63,7 @@ def parse_date(string): def set_filename_version(filename, version_number, pattern): changed = [] + def inject_version(match): before, old, after = match.groups() changed.append(True) @@ -31,8 +31,7 @@ setup( name='Babel', version=__version__, description='Internationalization utilities', - long_description=\ -"""A collection of tools for internationalizing Python applications.""", + long_description="""A collection of tools for internationalizing Python applications.""", author='Armin Ronacher', author_email='armin.ronacher@active-4.com', license='BSD', diff --git a/tests/messages/test_catalog.py b/tests/messages/test_catalog.py index 3eeaf64..5194a78 100644 --- a/tests/messages/test_catalog.py +++ b/tests/messages/test_catalog.py @@ -44,9 +44,9 @@ class MessageTestCase(unittest.TestCase): self.assertEqual(mess.user_comments, ['Comment About `foo`']) mess = catalog.Message('foo', auto_comments=['Comment 1 About `foo`', - 'Comment 2 About `foo`']) + 'Comment 2 About `foo`']) self.assertEqual(mess.auto_comments, ['Comment 1 About `foo`', - 'Comment 2 About `foo`']) + 'Comment 2 About `foo`']) def test_clone_message_object(self): msg = catalog.Message('foo', locations=[('foo.py', 42)]) @@ -58,6 +58,7 @@ class MessageTestCase(unittest.TestCase): class CatalogTestCase(unittest.TestCase): + def test_add_returns_message_instance(self): cat = catalog.Catalog() message = cat.add('foo') @@ -254,7 +255,7 @@ class CatalogTestCase(unittest.TestCase): self.assertEqual(template.creation_date, localized_catalog.creation_date) template.creation_date = datetime.datetime.now() - \ - datetime.timedelta(minutes=5) + datetime.timedelta(minutes=5) localized_catalog.update(template) self.assertEqual(template.creation_date, localized_catalog.creation_date) @@ -270,7 +271,7 @@ class CatalogTestCase(unittest.TestCase): self.assertEqual(template.creation_date, localized_catalog.creation_date) template.creation_date = datetime.datetime.now() - \ - datetime.timedelta(minutes=5) + datetime.timedelta(minutes=5) localized_catalog.update(template) self.assertEqual(localized_catalog.revision_date, fake_rev_date) @@ -278,8 +279,8 @@ class CatalogTestCase(unittest.TestCase): localized = catalog.Catalog() localized.locale = 'de_DE' localized[''] = catalog.Message('', - "POT-Creation-Date: 2009-03-09 15:47-0700\n" + - "PO-Revision-Date: 2009-03-09 15:47-0700\n") + "POT-Creation-Date: 2009-03-09 15:47-0700\n" + + "PO-Revision-Date: 2009-03-09 15:47-0700\n") for key, value in localized.mime_headers: if key in ('POT-Creation-Date', 'PO-Revision-Date'): self.assertEqual(value, '2009-03-09 15:47-0700') @@ -287,10 +288,10 @@ class CatalogTestCase(unittest.TestCase): def test_mime_headers_contain_same_information_as_attributes(self): cat = catalog.Catalog() cat[''] = catalog.Message('', - "Last-Translator: Foo Bar <foo.bar@example.com>\n" + - "Language-Team: de <de@example.com>\n" + - "POT-Creation-Date: 2009-03-01 11:20+0200\n" + - "PO-Revision-Date: 2009-03-09 15:47-0700\n") + "Last-Translator: Foo Bar <foo.bar@example.com>\n" + + "Language-Team: de <de@example.com>\n" + + "POT-Creation-Date: 2009-03-01 11:20+0200\n" + + "PO-Revision-Date: 2009-03-09 15:47-0700\n") self.assertEqual(None, cat.locale) mime_headers = dict(cat.mime_headers) @@ -313,10 +314,12 @@ def test_message_fuzzy(): assert msg.fuzzy assert msg.id == 'foo' + def test_message_pluralizable(): assert not catalog.Message('foo').pluralizable assert catalog.Message(('foo', 'bar')).pluralizable + def test_message_python_format(): assert catalog.Message('foo %(name)s bar').python_format assert catalog.Message(('foo %(name)s', 'foo %(name)s')).python_format @@ -329,7 +332,7 @@ def test_catalog(): '# Translations template for Foobar.\n' '# Copyright (C) %(year)d Foo Company\n' '# This file is distributed under the same ' - 'license as the Foobar project.\n' + 'license as the Foobar project.\n' '# FIRST AUTHOR <EMAIL@ADDRESS>, %(year)d.\n' '#') % {'year': datetime.date.today().year} @@ -436,7 +439,7 @@ def test_catalog_update(): cat.add('blue', u'blau', locations=[('main.py', 98)]) cat.add('head', u'Kopf', locations=[('util.py', 33)]) cat.add(('salad', 'salads'), (u'Salat', u'Salate'), - locations=[('util.py', 38)]) + locations=[('util.py', 38)]) cat.update(template) assert len(cat) == 3 diff --git a/tests/messages/test_checkers.py b/tests/messages/test_checkers.py index b954acb..e9c34bc 100644 --- a/tests/messages/test_checkers.py +++ b/tests/messages/test_checkers.py @@ -67,15 +67,15 @@ msgid "foobar" msgid_plural "foobars" msgstr[0] "" -""" % dict(locale = _locale, - english_name = locale.english_name, - version = VERSION, - year = time.strftime('%Y'), - date = format_datetime(datetime.now(LOCALTZ), - 'yyyy-MM-dd HH:mmZ', - tzinfo=LOCALTZ, locale=_locale), - num_plurals = PLURALS[_locale][0], - plural_expr = PLURALS[_locale][0])).encode('utf-8') +""" % dict(locale=_locale, + english_name=locale.english_name, + version=VERSION, + year=time.strftime('%Y'), + date=format_datetime(datetime.now(LOCALTZ), + 'yyyy-MM-dd HH:mmZ', + tzinfo=LOCALTZ, locale=_locale), + num_plurals=PLURALS[_locale][0], + plural_expr=PLURALS[_locale][0])).encode('utf-8') # This test will fail for revisions <= 406 because so far # catalog.num_plurals was neglected @@ -89,11 +89,11 @@ msgstr[0] "" for _locale in [p for p in PLURALS if PLURALS[p][0] == 2]: if _locale in ['nn', 'no']: _locale = 'nn_NO' - num_plurals = PLURALS[_locale.split('_')[0]][0] - plural_expr = PLURALS[_locale.split('_')[0]][1] + num_plurals = PLURALS[_locale.split('_')[0]][0] + plural_expr = PLURALS[_locale.split('_')[0]][1] else: - num_plurals = PLURALS[_locale][0] - plural_expr = PLURALS[_locale][1] + num_plurals = PLURALS[_locale][0] + plural_expr = PLURALS[_locale][1] try: locale = Locale(_locale) date = format_datetime(datetime.now(LOCALTZ), @@ -136,13 +136,13 @@ msgstr[0] "" msgstr[1] "" msgstr[2] "" -""" % dict(locale = _locale, - english_name = locale.english_name, - version = VERSION, - year = time.strftime('%Y'), - date = date, - num_plurals = num_plurals, - plural_expr = plural_expr)).encode('utf-8') +""" % dict(locale=_locale, + english_name=locale.english_name, + version=VERSION, + year=time.strftime('%Y'), + date=date, + num_plurals=num_plurals, + plural_expr=plural_expr)).encode('utf-8') # we should be adding the missing msgstr[0] # This test will fail for revisions <= 406 because so far @@ -186,15 +186,15 @@ msgid_plural "foobars" msgstr[0] "" msgstr[1] "" -""" % dict(locale = _locale, - english_name = Locale.parse(_locale).english_name, - version = VERSION, - year = time.strftime('%Y'), - date = format_datetime(datetime.now(LOCALTZ), - 'yyyy-MM-dd HH:mmZ', - tzinfo=LOCALTZ, locale=_locale), - num_plurals = PLURALS[_locale][0], - plural_expr = PLURALS[_locale][0])).encode('utf-8') +""" % dict(locale=_locale, + english_name=Locale.parse(_locale).english_name, + version=VERSION, + year=time.strftime('%Y'), + date=format_datetime(datetime.now(LOCALTZ), + 'yyyy-MM-dd HH:mmZ', + tzinfo=LOCALTZ, locale=_locale), + num_plurals=PLURALS[_locale][0], + plural_expr=PLURALS[_locale][0])).encode('utf-8') # This test will fail for revisions <= 406 because so far # catalog.num_plurals was neglected @@ -238,15 +238,15 @@ msgstr[0] "" msgstr[1] "" msgstr[2] "" -""" % dict(locale = _locale, - english_name = Locale.parse(_locale).english_name, - version = VERSION, - year = time.strftime('%Y'), - date = format_datetime(datetime.now(LOCALTZ), - 'yyyy-MM-dd HH:mmZ', - tzinfo=LOCALTZ, locale=_locale), - num_plurals = PLURALS[_locale][0], - plural_expr = PLURALS[_locale][0])).encode('utf-8') +""" % dict(locale=_locale, + english_name=Locale.parse(_locale).english_name, + version=VERSION, + year=time.strftime('%Y'), + date=format_datetime(datetime.now(LOCALTZ), + 'yyyy-MM-dd HH:mmZ', + tzinfo=LOCALTZ, locale=_locale), + num_plurals=PLURALS[_locale][0], + plural_expr=PLURALS[_locale][0])).encode('utf-8') # This test will fail for revisions <= 406 because so far # catalog.num_plurals was neglected @@ -291,15 +291,15 @@ msgstr[1] "" msgstr[2] "" msgstr[3] "" -""" % dict(locale = _locale, - english_name = Locale.parse(_locale).english_name, - version = VERSION, - year = time.strftime('%Y'), - date = format_datetime(datetime.now(LOCALTZ), - 'yyyy-MM-dd HH:mmZ', - tzinfo=LOCALTZ, locale=_locale), - num_plurals = PLURALS[_locale][0], - plural_expr = PLURALS[_locale][0])).encode('utf-8') +""" % dict(locale=_locale, + english_name=Locale.parse(_locale).english_name, + version=VERSION, + year=time.strftime('%Y'), + date=format_datetime(datetime.now(LOCALTZ), + 'yyyy-MM-dd HH:mmZ', + tzinfo=LOCALTZ, locale=_locale), + num_plurals=PLURALS[_locale][0], + plural_expr=PLURALS[_locale][0])).encode('utf-8') # This test will fail for revisions <= 406 because so far # catalog.num_plurals was neglected @@ -345,15 +345,15 @@ msgstr[2] "" msgstr[3] "" msgstr[4] "" -""" % dict(locale = _locale, - english_name = Locale.parse(_locale).english_name, - version = VERSION, - year = time.strftime('%Y'), - date = format_datetime(datetime.now(LOCALTZ), - 'yyyy-MM-dd HH:mmZ', - tzinfo=LOCALTZ, locale=_locale), - num_plurals = PLURALS[_locale][0], - plural_expr = PLURALS[_locale][0])).encode('utf-8') +""" % dict(locale=_locale, + english_name=Locale.parse(_locale).english_name, + version=VERSION, + year=time.strftime('%Y'), + date=format_datetime(datetime.now(LOCALTZ), + 'yyyy-MM-dd HH:mmZ', + tzinfo=LOCALTZ, locale=_locale), + num_plurals=PLURALS[_locale][0], + plural_expr=PLURALS[_locale][0])).encode('utf-8') # This test will fail for revisions <= 406 because so far # catalog.num_plurals was neglected diff --git a/tests/messages/test_extract.py b/tests/messages/test_extract.py index 66c8cd9..74d3101 100644 --- a/tests/messages/test_extract.py +++ b/tests/messages/test_extract.py @@ -38,17 +38,17 @@ msg10 = dngettext(getDomain(), 'Page', 'Pages', 3) extract.DEFAULT_KEYWORDS.keys(), [], {})) self.assertEqual([ - (1, '_', None, []), - (2, 'ungettext', (None, None, None), []), - (3, 'ungettext', (u'Babel', None, None), []), - (4, 'ungettext', (None, u'Babels', None), []), - (5, 'ungettext', (u'bunny', u'bunnies', None), []), - (6, 'ungettext', (None, u'bunnies', None), []), - (7, '_', None, []), - (8, 'gettext', u'Rabbit', []), - (9, 'dgettext', (u'wiki', None), []), - (10, 'dngettext', (None, u'Page', u'Pages', None), [])], - messages) + (1, '_', None, []), + (2, 'ungettext', (None, None, None), []), + (3, 'ungettext', (u'Babel', None, None), []), + (4, 'ungettext', (None, u'Babels', None), []), + (5, 'ungettext', (u'bunny', u'bunnies', None), []), + (6, 'ungettext', (None, u'bunnies', None), []), + (7, '_', None, []), + (8, 'gettext', u'Rabbit', []), + (9, 'dgettext', (u'wiki', None), []), + (10, 'dngettext', (None, u'Page', u'Pages', None), [])], + messages) def test_nested_comments(self): buf = BytesIO(b"""\ @@ -79,9 +79,9 @@ add_notice(req, ngettext("Foo deleted.", "Foos deleted.", len(selected))) add_notice(req, ngettext("Bar deleted.", "Bars deleted.", len(selected))) """) - messages = list(extract.extract_python(buf, ('ngettext','_'), ['NOTE:'], + messages = list(extract.extract_python(buf, ('ngettext', '_'), ['NOTE:'], - {'strip_comment_tags':False})) + {'strip_comment_tags': False})) self.assertEqual((6, '_', 'Locale deleted.', [u'NOTE: This Comment SHOULD Be Extracted']), messages[1]) @@ -90,9 +90,9 @@ add_notice(req, ngettext("Bar deleted.", [u'NOTE: This Comment SHOULD Be Extracted']), messages[2]) self.assertEqual((3, 'ngettext', - (u'Catalog deleted.', - u'Catalogs deleted.', None), - [u'NOTE: This Comment SHOULD Be Extracted']), + (u'Catalog deleted.', + u'Catalogs deleted.', None), + [u'NOTE: This Comment SHOULD Be Extracted']), messages[0]) self.assertEqual((15, 'ngettext', (u'Bar deleted.', u'Bars deleted.', None), @@ -143,7 +143,7 @@ msg2 = npgettext('Strings','elvis', messages = list(extract.extract_python(buf, ('npgettext',), [], {})) self.assertEqual([(1, 'npgettext', (u'Strings', u'pylon', u'pylons', None), []), (3, 'npgettext', (u'Strings', u'elvis', u'elvises', None), [])], - messages) + messages) buf = BytesIO(b"""\ msg = npgettext('Strings', 'pylon', # TRANSLATORS: shouldn't be 'pylons', # TRANSLATORS: seeing this diff --git a/tests/messages/test_frontend.py b/tests/messages/test_frontend.py index 42e3e38..df48033 100644 --- a/tests/messages/test_frontend.py +++ b/tests/messages/test_frontend.py @@ -32,13 +32,14 @@ from babel._compat import StringIO this_dir = os.path.abspath(os.path.dirname(__file__)) + class CompileCatalogTestCase(unittest.TestCase): def setUp(self): self.olddir = os.getcwd() self.datadir = os.path.join(this_dir, 'data') os.chdir(self.datadir) - _global_log.threshold = 5 # shut up distutils logging + _global_log.threshold = 5 # shut up distutils logging self.dist = Distribution(dict( name='TestProject', @@ -68,7 +69,7 @@ class ExtractMessagesTestCase(unittest.TestCase): self.olddir = os.getcwd() self.datadir = os.path.join(this_dir, 'data') os.chdir(self.datadir) - _global_log.threshold = 5 # shut up distutils logging + _global_log.threshold = 5 # shut up distutils logging self.dist = Distribution(dict( name='TestProject', @@ -195,9 +196,9 @@ msgstr[0] "" msgstr[1] "" """ % {'version': VERSION, - 'year': time.strftime('%Y'), - 'date': format_datetime(datetime.now(LOCALTZ), 'yyyy-MM-dd HH:mmZ', - tzinfo=LOCALTZ, locale='en')} + 'year': time.strftime('%Y'), + 'date': format_datetime(datetime.now(LOCALTZ), 'yyyy-MM-dd HH:mmZ', + tzinfo=LOCALTZ, locale='en')} with open(self._pot_file(), 'U') as f: actual_content = f.read() self.assertEqual(expected_content, actual_content) @@ -247,9 +248,9 @@ msgstr[0] "" msgstr[1] "" """ % {'version': VERSION, - 'year': time.strftime('%Y'), - 'date': format_datetime(datetime.now(LOCALTZ), 'yyyy-MM-dd HH:mmZ', - tzinfo=LOCALTZ, locale='en')} + 'year': time.strftime('%Y'), + 'date': format_datetime(datetime.now(LOCALTZ), 'yyyy-MM-dd HH:mmZ', + tzinfo=LOCALTZ, locale='en')} with open(self._pot_file(), 'U') as f: actual_content = f.read() self.assertEqual(expected_content, actual_content) @@ -257,8 +258,8 @@ msgstr[1] "" def test_extraction_with_mapping_dict(self): self.dist.message_extractors = { 'project': [ - ('**/ignored/**.*', 'ignore', None), - ('**.py', 'python', None), + ('**/ignored/**.*', 'ignore', None), + ('**.py', 'python', None), ] } self.cmd.copyright_holder = 'FooBar, Inc.' @@ -304,9 +305,9 @@ msgstr[0] "" msgstr[1] "" """ % {'version': VERSION, - 'year': time.strftime('%Y'), - 'date': format_datetime(datetime.now(LOCALTZ), 'yyyy-MM-dd HH:mmZ', - tzinfo=LOCALTZ, locale='en')} + 'year': time.strftime('%Y'), + 'date': format_datetime(datetime.now(LOCALTZ), 'yyyy-MM-dd HH:mmZ', + tzinfo=LOCALTZ, locale='en')} with open(self._pot_file(), 'U') as f: actual_content = f.read() self.assertEqual(expected_content, actual_content) @@ -318,7 +319,7 @@ class InitCatalogTestCase(unittest.TestCase): self.olddir = os.getcwd() self.datadir = os.path.join(this_dir, 'data') os.chdir(self.datadir) - _global_log.threshold = 5 # shut up distutils logging + _global_log.threshold = 5 # shut up distutils logging self.dist = Distribution(dict( name='TestProject', @@ -336,7 +337,7 @@ class InitCatalogTestCase(unittest.TestCase): os.chdir(self.olddir) - def _i18n_dir(self): + def _i18n_dir(self): return os.path.join(self.datadir, 'project', 'i18n') def _po_file(self, locale): @@ -398,8 +399,8 @@ msgstr[0] "" msgstr[1] "" """ % {'version': VERSION, - 'date': format_datetime(datetime.now(LOCALTZ), 'yyyy-MM-dd HH:mmZ', - tzinfo=LOCALTZ, locale='en')} + 'date': format_datetime(datetime.now(LOCALTZ), 'yyyy-MM-dd HH:mmZ', + tzinfo=LOCALTZ, locale='en')} with open(po_file, 'U') as f: actual_content = f.read() self.assertEqual(expected_content, actual_content) @@ -449,8 +450,8 @@ msgstr[0] "" msgstr[1] "" """ % {'version': VERSION, - 'date': format_datetime(datetime.now(LOCALTZ), 'yyyy-MM-dd HH:mmZ', - tzinfo=LOCALTZ, locale='en')} + 'date': format_datetime(datetime.now(LOCALTZ), 'yyyy-MM-dd HH:mmZ', + tzinfo=LOCALTZ, locale='en')} with open(po_file, 'U') as f: actual_content = f.read() self.assertEqual(expected_content, actual_content) @@ -502,8 +503,8 @@ msgstr[1] "" msgstr[2] "" """ % {'version': VERSION, - 'date': format_datetime(datetime.now(LOCALTZ), 'yyyy-MM-dd HH:mmZ', - tzinfo=LOCALTZ, locale='en')} + 'date': format_datetime(datetime.now(LOCALTZ), 'yyyy-MM-dd HH:mmZ', + tzinfo=LOCALTZ, locale='en')} with open(po_file, 'U') as f: actual_content = f.read() self.assertEqual(expected_content, actual_content) @@ -552,8 +553,8 @@ msgid_plural "foobars" msgstr[0] "" """ % {'version': VERSION, - 'date': format_datetime(datetime.now(LOCALTZ), 'yyyy-MM-dd HH:mmZ', - tzinfo=LOCALTZ, locale='ja_JP')} + 'date': format_datetime(datetime.now(LOCALTZ), 'yyyy-MM-dd HH:mmZ', + tzinfo=LOCALTZ, locale='ja_JP')} with open(po_file, 'U') as f: actual_content = f.read() self.assertEqual(expected_content, actual_content) @@ -563,7 +564,7 @@ msgstr[0] "" self.cmd.locale = 'en_US' self.cmd.output_dir = 'project/i18n' - long_message = '"'+ 'xxxxx '*15 + '"' + long_message = '"' + 'xxxxx ' * 15 + '"' with open('project/i18n/messages.pot', 'rb') as f: pot_contents = f.read().decode('latin-1') @@ -611,9 +612,9 @@ msgstr[0] "" msgstr[1] "" """ % {'version': VERSION, - 'date': format_datetime(datetime.now(LOCALTZ), 'yyyy-MM-dd HH:mmZ', - tzinfo=LOCALTZ, locale='en_US'), - 'long_message': long_message} + 'date': format_datetime(datetime.now(LOCALTZ), 'yyyy-MM-dd HH:mmZ', + tzinfo=LOCALTZ, locale='en_US'), + 'long_message': long_message} with open(po_file, 'U') as f: actual_content = f.read() self.assertEqual(expected_content, actual_content) @@ -623,7 +624,7 @@ msgstr[1] "" self.cmd.locale = 'en_US' self.cmd.output_dir = 'project/i18n' - long_message = '"'+ 'xxxxx '*15 + '"' + long_message = '"' + 'xxxxx ' * 15 + '"' with open('project/i18n/messages.pot', 'rb') as f: pot_contents = f.read().decode('latin-1') @@ -670,9 +671,9 @@ msgstr[0] "" msgstr[1] "" """ % {'version': VERSION, - 'date': format_datetime(datetime.now(LOCALTZ), 'yyyy-MM-dd HH:mmZ', - tzinfo=LOCALTZ, locale='en_US'), - 'long_message': long_message} + 'date': format_datetime(datetime.now(LOCALTZ), 'yyyy-MM-dd HH:mmZ', + tzinfo=LOCALTZ, locale='en_US'), + 'long_message': long_message} with open(po_file, 'U') as f: actual_content = f.read() self.assertEqual(expected_content, actual_content) @@ -785,11 +786,11 @@ commands: def test_extract_with_default_mapping(self): pot_file = self._pot_file() self.cli.run(sys.argv + ['extract', - '--copyright-holder', 'FooBar, Inc.', - '--project', 'TestProject', '--version', '0.1', - '--msgid-bugs-address', 'bugs.address@email.tld', - '-c', 'TRANSLATOR', '-c', 'TRANSLATORS:', - '-o', pot_file, 'project']) + '--copyright-holder', 'FooBar, Inc.', + '--project', 'TestProject', '--version', '0.1', + '--msgid-bugs-address', 'bugs.address@email.tld', + '-c', 'TRANSLATOR', '-c', 'TRANSLATORS:', + '-o', pot_file, 'project']) self.assert_pot_file_exists() expected_content = r"""# Translations template for TestProject. # Copyright (C) %(year)s FooBar, Inc. @@ -830,9 +831,9 @@ msgstr[0] "" msgstr[1] "" """ % {'version': VERSION, - 'year': time.strftime('%Y'), - 'date': format_datetime(datetime.now(LOCALTZ), 'yyyy-MM-dd HH:mmZ', - tzinfo=LOCALTZ, locale='en')} + 'year': time.strftime('%Y'), + 'date': format_datetime(datetime.now(LOCALTZ), 'yyyy-MM-dd HH:mmZ', + tzinfo=LOCALTZ, locale='en')} with open(pot_file, 'U') as f: actual_content = f.read() self.assertEqual(expected_content, actual_content) @@ -840,12 +841,12 @@ msgstr[1] "" def test_extract_with_mapping_file(self): pot_file = self._pot_file() self.cli.run(sys.argv + ['extract', - '--copyright-holder', 'FooBar, Inc.', - '--project', 'TestProject', '--version', '0.1', - '--msgid-bugs-address', 'bugs.address@email.tld', - '--mapping', os.path.join(self.datadir, 'mapping.cfg'), - '-c', 'TRANSLATOR', '-c', 'TRANSLATORS:', - '-o', pot_file, 'project']) + '--copyright-holder', 'FooBar, Inc.', + '--project', 'TestProject', '--version', '0.1', + '--msgid-bugs-address', 'bugs.address@email.tld', + '--mapping', os.path.join(self.datadir, 'mapping.cfg'), + '-c', 'TRANSLATOR', '-c', 'TRANSLATORS:', + '-o', pot_file, 'project']) self.assert_pot_file_exists() expected_content = r"""# Translations template for TestProject. # Copyright (C) %(year)s FooBar, Inc. @@ -880,9 +881,9 @@ msgstr[0] "" msgstr[1] "" """ % {'version': VERSION, - 'year': time.strftime('%Y'), - 'date': format_datetime(datetime.now(LOCALTZ), 'yyyy-MM-dd HH:mmZ', - tzinfo=LOCALTZ, locale='en')} + 'year': time.strftime('%Y'), + 'date': format_datetime(datetime.now(LOCALTZ), 'yyyy-MM-dd HH:mmZ', + tzinfo=LOCALTZ, locale='en')} with open(pot_file, 'U') as f: actual_content = f.read() self.assertEqual(expected_content, actual_content) @@ -894,12 +895,12 @@ msgstr[1] "" pot_file = self._pot_file() file_to_extract = os.path.join(self.datadir, 'project', 'file2.py') self.cli.run(sys.argv + ['extract', - '--copyright-holder', 'FooBar, Inc.', - '--project', 'TestProject', '--version', '0.1', - '--msgid-bugs-address', 'bugs.address@email.tld', - '--mapping', os.path.join(self.datadir, 'mapping.cfg'), - '-c', 'TRANSLATOR', '-c', 'TRANSLATORS:', - '-o', pot_file, file_to_extract]) + '--copyright-holder', 'FooBar, Inc.', + '--project', 'TestProject', '--version', '0.1', + '--msgid-bugs-address', 'bugs.address@email.tld', + '--mapping', os.path.join(self.datadir, 'mapping.cfg'), + '-c', 'TRANSLATOR', '-c', 'TRANSLATORS:', + '-o', pot_file, file_to_extract]) self.assert_pot_file_exists() expected_content = r"""# Translations template for TestProject. # Copyright (C) %(year)s FooBar, Inc. @@ -928,9 +929,9 @@ msgstr[0] "" msgstr[1] "" """ % {'version': VERSION, - 'year': time.strftime('%Y'), - 'date': format_datetime(datetime.now(LOCALTZ), 'yyyy-MM-dd HH:mmZ', - tzinfo=LOCALTZ, locale='en')} + 'year': time.strftime('%Y'), + 'date': format_datetime(datetime.now(LOCALTZ), 'yyyy-MM-dd HH:mmZ', + tzinfo=LOCALTZ, locale='en')} with open(pot_file, 'U') as f: actual_content = f.read() self.assertEqual(expected_content, actual_content) @@ -938,9 +939,9 @@ msgstr[1] "" def test_init_with_output_dir(self): po_file = self._po_file('en_US') self.cli.run(sys.argv + ['init', - '--locale', 'en_US', - '-d', os.path.join(self._i18n_dir()), - '-i', os.path.join(self._i18n_dir(), 'messages.pot')]) + '--locale', 'en_US', + '-d', os.path.join(self._i18n_dir()), + '-i', os.path.join(self._i18n_dir(), 'messages.pot')]) assert os.path.isfile(po_file) expected_content = r"""# English (United States) translations for TestProject. # Copyright (C) 2007 FooBar, Inc. @@ -976,21 +977,21 @@ msgstr[0] "" msgstr[1] "" """ % {'version': VERSION, - 'date': format_datetime(datetime.now(LOCALTZ), 'yyyy-MM-dd HH:mmZ', - tzinfo=LOCALTZ, locale='en')} + 'date': format_datetime(datetime.now(LOCALTZ), 'yyyy-MM-dd HH:mmZ', + tzinfo=LOCALTZ, locale='en')} with open(po_file, 'U') as f: actual_content = f.read() self.assertEqual(expected_content, actual_content) - def _i18n_dir(self): + def _i18n_dir(self): return os.path.join(self.datadir, 'project', 'i18n') def test_init_singular_plural_forms(self): po_file = self._po_file('ja_JP') self.cli.run(sys.argv + ['init', - '--locale', 'ja_JP', - '-d', os.path.join(self._i18n_dir()), - '-i', os.path.join(self._i18n_dir(), 'messages.pot')]) + '--locale', 'ja_JP', + '-d', os.path.join(self._i18n_dir()), + '-i', os.path.join(self._i18n_dir(), 'messages.pot')]) assert os.path.isfile(po_file) expected_content = r"""# Japanese (Japan) translations for TestProject. # Copyright (C) 2007 FooBar, Inc. @@ -1025,8 +1026,8 @@ msgid_plural "foobars" msgstr[0] "" """ % {'version': VERSION, - 'date': format_datetime(datetime.now(LOCALTZ), 'yyyy-MM-dd HH:mmZ', - tzinfo=LOCALTZ, locale='en')} + 'date': format_datetime(datetime.now(LOCALTZ), 'yyyy-MM-dd HH:mmZ', + tzinfo=LOCALTZ, locale='en')} with open(po_file, 'U') as f: actual_content = f.read() self.assertEqual(expected_content, actual_content) @@ -1034,9 +1035,9 @@ msgstr[0] "" def test_init_more_than_2_plural_forms(self): po_file = self._po_file('lv_LV') self.cli.run(sys.argv + ['init', - '--locale', 'lv_LV', - '-d', self._i18n_dir(), - '-i', os.path.join(self._i18n_dir(), 'messages.pot')]) + '--locale', 'lv_LV', + '-d', self._i18n_dir(), + '-i', os.path.join(self._i18n_dir(), 'messages.pot')]) assert os.path.isfile(po_file) expected_content = r"""# Latvian (Latvia) translations for TestProject. # Copyright (C) 2007 FooBar, Inc. @@ -1074,8 +1075,8 @@ msgstr[1] "" msgstr[2] "" """ % {'version': VERSION, - 'date': format_datetime(datetime.now(LOCALTZ), 'yyyy-MM-dd HH:mmZ', - tzinfo=LOCALTZ, locale='en')} + 'date': format_datetime(datetime.now(LOCALTZ), 'yyyy-MM-dd HH:mmZ', + tzinfo=LOCALTZ, locale='en')} with open(po_file, 'U') as f: actual_content = f.read() self.assertEqual(expected_content, actual_content) @@ -1084,8 +1085,8 @@ msgstr[2] "" po_file = self._po_file('de_DE') mo_file = po_file.replace('.po', '.mo') self.cli.run(sys.argv + ['compile', - '--locale', 'de_DE', - '-d', self._i18n_dir()]) + '--locale', 'de_DE', + '-d', self._i18n_dir()]) assert not os.path.isfile(mo_file), 'Expected no file at %r' % mo_file self.assertEqual("""\ catalog %r is marked as fuzzy, skipping @@ -1096,8 +1097,8 @@ catalog %r is marked as fuzzy, skipping mo_file = po_file.replace('.po', '.mo') try: self.cli.run(sys.argv + ['compile', - '--locale', 'de_DE', '--use-fuzzy', - '-d', self._i18n_dir()]) + '--locale', 'de_DE', '--use-fuzzy', + '-d', self._i18n_dir()]) assert os.path.isfile(mo_file) self.assertEqual("""\ compiling catalog %r to %r @@ -1115,8 +1116,8 @@ compiling catalog %r to %r mo_file = po_file.replace('.po', '.mo') try: self.cli.run(sys.argv + ['compile', - '--locale', 'ru_RU', '--use-fuzzy', - '-d', self._i18n_dir()]) + '--locale', 'ru_RU', '--use-fuzzy', + '-d', self._i18n_dir()]) assert os.path.isfile(mo_file) self.assertEqual("""\ compiling catalog %r to %r @@ -1134,8 +1135,8 @@ compiling catalog %r to %r mo_bar = po_bar.replace('.po', '.mo') try: self.cli.run(sys.argv + ['compile', - '--locale', 'de_DE', '--domain', 'foo bar', '--use-fuzzy', - '-d', self._i18n_dir()]) + '--locale', 'de_DE', '--domain', 'foo bar', '--use-fuzzy', + '-d', self._i18n_dir()]) for mo_file in [mo_foo, mo_bar]: assert os.path.isfile(mo_file) self.assertEqual("""\ @@ -1158,10 +1159,10 @@ compiling catalog %r to %r write_po(outfp, template) po_file = os.path.join(self._i18n_dir(), 'temp1.po') self.cli.run(sys.argv + ['init', - '-l', 'fi', - '-o', po_file, - '-i', tmpl_file - ]) + '-l', 'fi', + '-o', po_file, + '-i', tmpl_file + ]) with open(po_file, "r") as infp: catalog = read_po(infp) assert len(catalog) == 3 @@ -1174,14 +1175,15 @@ compiling catalog %r to %r write_po(outfp, template) self.cli.run(sys.argv + ['update', - '-l', 'fi_FI', - '-o', po_file, - '-i', tmpl_file]) + '-l', 'fi_FI', + '-o', po_file, + '-i', tmpl_file]) with open(po_file, "r") as infp: catalog = read_po(infp) assert len(catalog) == 4 # Catalog was updated + def test_parse_mapping(): buf = StringIO( '[extractors]\n' diff --git a/tests/messages/test_pofile.py b/tests/messages/test_pofile.py index f375a1a..1bac360 100644 --- a/tests/messages/test_pofile.py +++ b/tests/messages/test_pofile.py @@ -188,7 +188,7 @@ msgstr "Bahr" out_buf = BytesIO() pofile.write_po(out_buf, catalog, omit_header=True) assert out_buf.getvalue().strip() == buf.getvalue().strip(), \ - out_buf.getvalue() + out_buf.getvalue() def test_with_context_two(self): buf = BytesIO(b'''msgctxt "Menu" @@ -299,7 +299,7 @@ not be removed catalog.add(text, locations=[('main.py', 1)]) buf = BytesIO() pofile.write_po(buf, catalog, no_location=True, omit_header=True, - width=42) + width=42) self.assertEqual(b'''msgid "" "Here's some text where\\n" "white space and line breaks matter, and" @@ -317,7 +317,7 @@ includesareallylongwordthatmightbutshouldnt throw us into an infinite loop catalog.add(text, locations=[('main.py', 1)]) buf = BytesIO() pofile.write_po(buf, catalog, no_location=True, omit_header=True, - width=32) + width=32) self.assertEqual(b'''msgid "" "Here's some text that\\n" "includesareallylongwordthatmightbutshouldnt" diff --git a/tests/test_core.py b/tests/test_core.py index 54cf37d..b9de4cb 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -31,6 +31,7 @@ def test_locale_repr(): assert ("Locale('zh', territory='CN', script='Hans')" == repr(Locale('zh', 'CN', script='Hans'))) + def test_locale_comparison(): en_US = Locale('en', 'US') en_US_2 = Locale('en', 'US') @@ -72,6 +73,7 @@ def test_hash(): class TestLocaleClass: + def test_attributes(self): locale = Locale('en', 'US') assert locale.language == 'en' @@ -306,6 +308,7 @@ def test_compatible_classes_in_global_and_localedata(filename): import pickle class Unpickler(pickle.Unpickler): + def find_class(self, module, name): # *.dat files must have compatible classes between Python 2 and 3 if module.split('.')[0] == 'babel': diff --git a/tests/test_dates.py b/tests/test_dates.py index 5155c0c..069c9bd 100644 --- a/tests/test_dates.py +++ b/tests/test_dates.py @@ -36,9 +36,9 @@ class DateTimeFormatTestCase(unittest.TestCase): def test_month_context(self): d = date(2006, 2, 8) fmt = dates.DateTimeFormat(d, locale='mt_MT') - self.assertEqual(u'F', fmt['MMMMM']) # narrow format + self.assertEqual(u'F', fmt['MMMMM']) # narrow format fmt = dates.DateTimeFormat(d, locale='mt_MT') - self.assertEqual(u'Fr', fmt['LLLLL']) # narrow standalone + self.assertEqual(u'Fr', fmt['LLLLL']) # narrow standalone def test_abbreviated_month_alias(self): d = date(2006, 3, 8) @@ -122,38 +122,38 @@ class DateTimeFormatTestCase(unittest.TestCase): self.assertEqual('5', fmt['F']) def test_local_day_of_week(self): - d = date(2007, 4, 1) # a sunday + d = date(2007, 4, 1) # a sunday fmt = dates.DateTimeFormat(d, locale='de_DE') - self.assertEqual('7', fmt['e']) # monday is first day of week + self.assertEqual('7', fmt['e']) # monday is first day of week fmt = dates.DateTimeFormat(d, locale='en_US') - self.assertEqual('01', fmt['ee']) # sunday is first day of week + self.assertEqual('01', fmt['ee']) # sunday is first day of week fmt = dates.DateTimeFormat(d, locale='bn_BD') - self.assertEqual('03', fmt['ee']) # friday is first day of week + self.assertEqual('03', fmt['ee']) # friday is first day of week - d = date(2007, 4, 2) # a monday + d = date(2007, 4, 2) # a monday fmt = dates.DateTimeFormat(d, locale='de_DE') - self.assertEqual('1', fmt['e']) # monday is first day of week + self.assertEqual('1', fmt['e']) # monday is first day of week fmt = dates.DateTimeFormat(d, locale='en_US') - self.assertEqual('02', fmt['ee']) # sunday is first day of week + self.assertEqual('02', fmt['ee']) # sunday is first day of week fmt = dates.DateTimeFormat(d, locale='bn_BD') - self.assertEqual('04', fmt['ee']) # friday is first day of week + self.assertEqual('04', fmt['ee']) # friday is first day of week def test_local_day_of_week_standalone(self): - d = date(2007, 4, 1) # a sunday + d = date(2007, 4, 1) # a sunday fmt = dates.DateTimeFormat(d, locale='de_DE') - self.assertEqual('7', fmt['c']) # monday is first day of week + self.assertEqual('7', fmt['c']) # monday is first day of week fmt = dates.DateTimeFormat(d, locale='en_US') - self.assertEqual('1', fmt['c']) # sunday is first day of week + self.assertEqual('1', fmt['c']) # sunday is first day of week fmt = dates.DateTimeFormat(d, locale='bn_BD') - self.assertEqual('3', fmt['c']) # friday is first day of week + self.assertEqual('3', fmt['c']) # friday is first day of week - d = date(2007, 4, 2) # a monday + d = date(2007, 4, 2) # a monday fmt = dates.DateTimeFormat(d, locale='de_DE') - self.assertEqual('1', fmt['c']) # monday is first day of week + self.assertEqual('1', fmt['c']) # monday is first day of week fmt = dates.DateTimeFormat(d, locale='en_US') - self.assertEqual('2', fmt['c']) # sunday is first day of week + self.assertEqual('2', fmt['c']) # sunday is first day of week fmt = dates.DateTimeFormat(d, locale='bn_BD') - self.assertEqual('4', fmt['c']) # friday is first day of week + self.assertEqual('4', fmt['c']) # friday is first day of week def test_fractional_seconds(self): t = time(15, 30, 12, 34567) @@ -451,8 +451,10 @@ class FormatTimedeltaTestCase(unittest.TestCase): class TimeZoneAdjustTestCase(unittest.TestCase): + def _utc(self): class EvilFixedOffsetTimezone(FixedOffsetTimezone): + def localize(self, dt, is_dst=False): raise NotImplementedError() UTC = EvilFixedOffsetTimezone(0, 'UTC') @@ -702,6 +704,7 @@ def test_format_current_moment(monkeypatch): frozen_instant = datetime.utcnow() class frozen_datetime(datetime): + @classmethod def utcnow(cls): return frozen_instant diff --git a/tests/test_localedata.py b/tests/test_localedata.py index 80dd118..1c568ed 100644 --- a/tests/test_localedata.py +++ b/tests/test_localedata.py @@ -73,6 +73,7 @@ def test_merge(): localedata.merge(d, {1: 'Foo', 2: 'Bar'}) assert d == {1: 'Foo', 2: 'Bar', 3: 'baz'} + def test_locale_identification(): for l in localedata.locale_identifiers(): assert localedata.exists(l) diff --git a/tests/test_numbers.py b/tests/test_numbers.py index 4b8a48d..19f9bc7 100644 --- a/tests/test_numbers.py +++ b/tests/test_numbers.py @@ -24,7 +24,7 @@ class FormatDecimalTestCase(unittest.TestCase): def test_patterns(self): self.assertEqual(numbers.format_decimal(12345, '##0', - locale='en_US'), '12345') + locale='en_US'), '12345') self.assertEqual(numbers.format_decimal(6.5, '0.00', locale='sv'), '6,50') self.assertEqual(numbers.format_decimal(10.0**20, @@ -35,13 +35,13 @@ class FormatDecimalTestCase(unittest.TestCase): # significant digits self.assertEqual(u'12,345,678.05', numbers.format_decimal(12345678.051, '#,##0.00', - locale='en_US')) + locale='en_US')) def test_subpatterns(self): self.assertEqual(numbers.format_decimal(-12345, '#,##0.##;-#', - locale='en_US'), '-12,345') + locale='en_US'), '-12,345') self.assertEqual(numbers.format_decimal(-12345, '#,##0.##;(#)', - locale='en_US'), '(12,345)') + locale='en_US'), '(12,345)') def test_default_rounding(self): """ @@ -57,8 +57,8 @@ class FormatDecimalTestCase(unittest.TestCase): def test_significant_digits(self): """Test significant digits patterns""" - self.assertEqual(numbers.format_decimal(123004, '@@',locale='en_US'), - '120000') + self.assertEqual(numbers.format_decimal(123004, '@@', locale='en_US'), + '120000') self.assertEqual(numbers.format_decimal(1.12, '@', locale='sv'), '1') self.assertEqual(numbers.format_decimal(1.1, '@@', locale='sv'), '1,1') self.assertEqual(numbers.format_decimal(1.1, '@@@@@##', locale='sv'), @@ -67,27 +67,27 @@ class FormatDecimalTestCase(unittest.TestCase): '0,000100') self.assertEqual(numbers.format_decimal(0.0001234, '@@@', locale='sv'), '0,000123') - self.assertEqual(numbers.format_decimal(0.0001234, '@@@#',locale='sv'), + self.assertEqual(numbers.format_decimal(0.0001234, '@@@#', locale='sv'), '0,0001234') - self.assertEqual(numbers.format_decimal(0.0001234, '@@@#',locale='sv'), + self.assertEqual(numbers.format_decimal(0.0001234, '@@@#', locale='sv'), '0,0001234') - self.assertEqual(numbers.format_decimal(0.12345, '@@@',locale='sv'), + self.assertEqual(numbers.format_decimal(0.12345, '@@@', locale='sv'), '0,123') - self.assertEqual(numbers.format_decimal(3.14159, '@@##',locale='sv'), + self.assertEqual(numbers.format_decimal(3.14159, '@@##', locale='sv'), '3,142') - self.assertEqual(numbers.format_decimal(1.23004, '@@##',locale='sv'), + self.assertEqual(numbers.format_decimal(1.23004, '@@##', locale='sv'), '1,23') - self.assertEqual(numbers.format_decimal(1230.04, '@@,@@',locale='en_US'), + self.assertEqual(numbers.format_decimal(1230.04, '@@,@@', locale='en_US'), '12,30') - self.assertEqual(numbers.format_decimal(123.41, '@@##',locale='en_US'), + self.assertEqual(numbers.format_decimal(123.41, '@@##', locale='en_US'), '123.4') - self.assertEqual(numbers.format_decimal(1, '@@',locale='en_US'), + self.assertEqual(numbers.format_decimal(1, '@@', locale='en_US'), '1.0') - self.assertEqual(numbers.format_decimal(0, '@',locale='en_US'), + self.assertEqual(numbers.format_decimal(0, '@', locale='en_US'), '0') - self.assertEqual(numbers.format_decimal(0.1, '@',locale='en_US'), + self.assertEqual(numbers.format_decimal(0.1, '@', locale='en_US'), '0.1') - self.assertEqual(numbers.format_decimal(0.1, '@#',locale='en_US'), + self.assertEqual(numbers.format_decimal(0.1, '@#', locale='en_US'), '0.1') self.assertEqual(numbers.format_decimal(0.1, '@@', locale='en_US'), '0.10') @@ -137,7 +137,7 @@ class FormatDecimalTestCase(unittest.TestCase): fmt = numbers.format_scientific(0.012345, '#.##E00 m/s', locale='en_US') self.assertEqual(fmt, '1.23E-02 m/s') fmt = numbers.format_scientific(Decimal('12345'), '#.##E+00 m/s', - locale='en_US') + locale='en_US') self.assertEqual(fmt, '1.23E+04 m/s') # 0 (see ticket #99) fmt = numbers.format_scientific(0, '#E0', locale='en_US') @@ -152,11 +152,12 @@ class FormatDecimalTestCase(unittest.TestCase): class NumberParsingTestCase(unittest.TestCase): + def test_can_parse_decimals(self): self.assertEqual(Decimal('1099.98'), - numbers.parse_decimal('1,099.98', locale='en_US')) + numbers.parse_decimal('1,099.98', locale='en_US')) self.assertEqual(Decimal('1099.98'), - numbers.parse_decimal('1.099,98', locale='de')) + numbers.parse_decimal('1.099,98', locale='de')) self.assertRaises(numbers.NumberFormatError, lambda: numbers.parse_decimal('2,109,998', locale='de')) @@ -176,15 +177,15 @@ def test_get_territory_currencies(): assert numbers.get_territory_currencies('US', date(2013, 1, 1)) == ['USD'] assert sorted(numbers.get_territory_currencies('US', date(2013, 1, 1), - non_tender=True)) == ['USD', 'USN', 'USS'] + non_tender=True)) == ['USD', 'USN', 'USS'] assert numbers.get_territory_currencies('US', date(2013, 1, 1), - include_details=True) == [{ - 'currency': 'USD', - 'from': date(1792, 1, 1), - 'to': None, - 'tender': True - }] + include_details=True) == [{ + 'currency': 'USD', + 'from': date(1792, 1, 1), + 'to': None, + 'tender': True + }] assert numbers.get_territory_currencies('LS', date(2013, 1, 1)) == ['ZAR', 'LSL'] @@ -254,7 +255,7 @@ def test_format_currency_format_type(): with pytest.raises(numbers.UnknownCurrencyFormatError) as excinfo: numbers.format_currency(1099.98, 'USD', locale='en_US', - format_type='unknown') + format_type='unknown') assert excinfo.value.args[0] == "'unknown' is not a known currency format type" assert (numbers.format_currency(1099.98, 'JPY', locale='en_US') diff --git a/tests/test_plural.py b/tests/test_plural.py index d51efef..60a2de4 100644 --- a/tests/test_plural.py +++ b/tests/test_plural.py @@ -145,7 +145,7 @@ WELL_FORMED_TOKEN_TESTS = ( ('n = 1 @integer 1', [('value', '1'), ('symbol', '='), ('word', 'n'), ]), ('n is 1', [('value', '1'), ('word', 'is'), ('word', 'n'), ]), ('n % 100 = 3..10', [('value', '10'), ('ellipsis', '..'), ('value', '3'), - ('symbol', '='), ('value', '100'), ('symbol', '%'), + ('symbol', '='), ('value', '100'), ('symbol', '%'), ('word', 'n'), ]), ) @@ -167,6 +167,7 @@ def test_tokenize_malformed(rule_text): class TestNextTokenTestCase(unittest.TestCase): + def test_empty(self): assert not plural.test_next_token([], '') @@ -197,6 +198,7 @@ def make_range_list(*values): class PluralRuleParserTestCase(unittest.TestCase): + def setUp(self): self.n = plural.ident_node('n') diff --git a/tests/test_support.py b/tests/test_support.py index efdddeb..f2a99b7 100644 --- a/tests/test_support.py +++ b/tests/test_support.py @@ -186,6 +186,7 @@ class TranslationsTestCase(unittest.TestCase): class NullTranslationsTestCase(unittest.TestCase): + def setUp(self): fp = BytesIO() write_mo(fp, Catalog(locale='de')) @@ -225,8 +226,10 @@ class NullTranslationsTestCase(unittest.TestCase): class LazyProxyTestCase(unittest.TestCase): + def test_proxy_caches_result_of_function_call(self): self.counter = 0 + def add_one(): self.counter += 1 return self.counter @@ -236,6 +239,7 @@ class LazyProxyTestCase(unittest.TestCase): def test_can_disable_proxy_cache(self): self.counter = 0 + def add_one(): self.counter += 1 return self.counter @@ -246,7 +250,8 @@ class LazyProxyTestCase(unittest.TestCase): def test_can_copy_proxy(self): from copy import copy - numbers = [1,2] + numbers = [1, 2] + def first(xs): return xs[0] @@ -259,7 +264,8 @@ class LazyProxyTestCase(unittest.TestCase): def test_can_deepcopy_proxy(self): from copy import deepcopy - numbers = [1,2] + numbers = [1, 2] + def first(xs): return xs[0] diff --git a/tests/test_util.py b/tests/test_util.py index d4b4be5..068a102 100644 --- a/tests/test_util.py +++ b/tests/test_util.py @@ -29,6 +29,7 @@ def test_pathmatch(): assert util.pathmatch('**/templates/*.html', 'templates/index.html') assert not util.pathmatch('**/templates/*.html', 'templates/foo/bar.html') + def test_odict_pop(): odict = util.odict() odict[0] = 1 @@ -44,6 +45,7 @@ def test_odict_pop(): class FixedOffsetTimezoneTestCase(unittest.TestCase): + def test_zone_negative_offset(self): self.assertEqual('Etc/GMT-60', util.FixedOffsetTimezone(-60).zone) |