itervalues = lambda d: iter(d.values())
iteritems = lambda d: iter(d.items())
- from io import StringIO
+ from io import StringIO, BytesIO
import pickle
izip = zip
imap = map
+ range_type = range
+
else:
text_type = unicode
itervalues = lambda d: d.itervalues()
iteritems = lambda d: d.iteritems()
- from cStringIO import StringIO
+ from cStringIO import StringIO as BytesIO
+ from StringIO import StringIO
import cPickle as pickle
from itertools import izip, imap
+ range_type = xrange
number_types = integer_types + (float,)
import struct
from babel.messages.catalog import Catalog, Message
+from babel._compat import range_type
__all__ = ['read_mo', 'write_mo']
-LE_MAGIC = 0x950412deL
-BE_MAGIC = 0xde120495L
+LE_MAGIC = 0x950412de
+BE_MAGIC = 0xde120495
def read_mo(fileobj):
"""Read a binary MO file from the given file-like object and return a
# Now put all messages from the .mo file buffer into the catalog
# dictionary
- for i in xrange(0, msgcount):
+ for i in range_type(0, msgcount):
mlen, moff = unpack(ii, buf[origidx:origidx + 8])
mend = moff + mlen
tlen, toff = unpack(ii, buf[transidx:transidx + 8])
def parse_number(string, locale=LC_NUMERIC):
- """Parse localized number string into a long integer.
+ """Parse localized number string into an integer.
>>> parse_number('1,099', locale='en_US')
- 1099L
+ 1099
>>> parse_number('1.099', locale='de_DE')
- 1099L
+ 1099
When the given string cannot be parsed, an exception is raised:
:param string: the string to parse
:param locale: the `Locale` object or locale identifier
:return: the parsed number
- :rtype: `long`
:raise `NumberFormatError`: if the string can not be converted to a number
"""
try:
- return long(string.replace(get_group_symbol(locale), ''))
+ return int(string.replace(get_group_symbol(locale), ''))
except ValueError:
raise NumberFormatError('%r is not a valid number' % string)
int_part = []
frac_part = []
- digits = map(str, digits)
+ digits = list(map(str, digits))
# get figures after decimal point
for i in range(-exp):
except UnknownLocaleError:
# Just an alias? Not what we're testing here, let's continue
continue
- po_file = (ur"""\
+ po_file = (u"""\
# %(english_name)s translations for TestProject.
# Copyright (C) 2007 FooBar, Inc.
# This file is distributed under the same license as the TestProject
#
msgid ""
msgstr ""
-"Project-Id-Version: TestProject 0.1\n"
-"Report-Msgid-Bugs-To: bugs.address@email.tld\n"
-"POT-Creation-Date: 2007-04-01 15:30+0200\n"
-"PO-Revision-Date: %(date)s\n"
-"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
+"Project-Id-Version: TestProject 0.1\\n"
+"Report-Msgid-Bugs-To: bugs.address@email.tld\\n"
+"POT-Creation-Date: 2007-04-01 15:30+0200\\n"
+"PO-Revision-Date: %(date)s\\n"
+"Last-Translator: FULL NAME <EMAIL@ADDRESS>\\n"
"Language-Team: %(locale)s <LL@li.org>\n"
-"Plural-Forms: nplurals=%(num_plurals)s; plural=%(plural_expr)s\n"
-"MIME-Version: 1.0\n"
-"Content-Type: text/plain; charset=utf-8\n"
-"Content-Transfer-Encoding: 8bit\n"
-"Generated-By: Babel %(version)s\n"
+"Plural-Forms: nplurals=%(num_plurals)s; plural=%(plural_expr)s\\n"
+"MIME-Version: 1.0\\n"
+"Content-Type: text/plain; charset=utf-8\\n"
+"Content-Transfer-Encoding: 8bit\\n"
+"Generated-By: Babel %(version)s\\n"
#. This will be a translator comment,
#. that will include several lines
# history and logs, available at http://babel.edgewall.org/log/.
import codecs
-import doctest
-from StringIO import StringIO
import sys
import unittest
from babel.messages import extract
+from babel._compat import BytesIO, StringIO
class ExtractPythonTestCase(unittest.TestCase):
def test_nested_calls(self):
- buf = StringIO("""\
+ buf = BytesIO(b"""\
msg1 = _(i18n_arg.replace(r'\"', '"'))
msg2 = ungettext(i18n_arg.replace(r'\"', '"'), multi_arg.replace(r'\"', '"'), 2)
msg3 = ungettext("Babel", multi_arg.replace(r'\"', '"'), 2)
messages)
def test_nested_comments(self):
- buf = StringIO("""\
+ buf = BytesIO(b"""\
msg = ngettext('pylon', # TRANSLATORS: shouldn't be
'pylons', # TRANSLATORS: seeing this
count)
messages)
def test_comments_with_calls_that_spawn_multiple_lines(self):
- buf = StringIO("""\
+ buf = BytesIO(b"""\
# NOTE: This Comment SHOULD Be Extracted
add_notice(req, ngettext("Catalog deleted.",
"Catalogs deleted.", len(selected)))
messages[3])
def test_declarations(self):
- buf = StringIO("""\
+ buf = BytesIO(b"""\
class gettext(object):
pass
def render_body(context,x,y=_('Page arg 1'),z=_('Page arg 2'),**pageargs):
messages)
def test_multiline(self):
- buf = StringIO("""\
+ buf = BytesIO(b"""\
msg1 = ngettext('pylon',
'pylons', count)
msg2 = ngettext('elvis',
messages)
def test_triple_quoted_strings(self):
- buf = StringIO("""\
+ buf = BytesIO(b"""\
msg1 = _('''pylons''')
msg2 = ngettext(r'''elvis''', \"\"\"elvises\"\"\", count)
msg2 = ngettext(\"\"\"elvis\"\"\", 'elvises', count)
messages)
def test_multiline_strings(self):
- buf = StringIO("""\
+ buf = BytesIO(b"""\
_('''This module provides internationalization and localization
support for your Python programs by providing an interface to the GNU
gettext message catalog library.''')
messages)
def test_concatenated_strings(self):
- buf = StringIO("""\
+ buf = BytesIO(b"""\
foobar = _('foo' 'bar')
""")
messages = list(extract.extract_python(buf,
self.assertEqual(u'foobar', messages[0][2])
def test_unicode_string_arg(self):
- buf = StringIO("msg = _(u'Foo Bar')")
+ buf = BytesIO(b"msg = _(u'Foo Bar')")
messages = list(extract.extract_python(buf, ('_',), [], {}))
self.assertEqual(u'Foo Bar', messages[0][2])
def test_comment_tag(self):
- buf = StringIO("""
+ buf = BytesIO(b"""
# NOTE: A translation comment
msg = _(u'Foo Bar')
""")
self.assertEqual([u'NOTE: A translation comment'], messages[0][3])
def test_comment_tag_multiline(self):
- buf = StringIO("""
+ buf = BytesIO(b"""
# NOTE: A translation comment
# with a second line
msg = _(u'Foo Bar')
messages[0][3])
def test_translator_comments_with_previous_non_translator_comments(self):
- buf = StringIO("""
+ buf = BytesIO(b"""
# This shouldn't be in the output
# because it didn't start with a comment tag
# NOTE: A translation comment
messages[0][3])
def test_comment_tags_not_on_start_of_comment(self):
- buf = StringIO("""
+ buf = BytesIO(b"""
# This shouldn't be in the output
# because it didn't start with a comment tag
# do NOTE: this will not be a translation comment
self.assertEqual([u'NOTE: This one will be'], messages[0][3])
def test_multiple_comment_tags(self):
- buf = StringIO("""
+ buf = BytesIO(b"""
# NOTE1: A translation comment for tag1
# with a second line
msg = _(u'Foo Bar1')
self.assertEqual([u'NOTE2: A translation comment for tag2'], messages[1][3])
def test_two_succeeding_comments(self):
- buf = StringIO("""
+ buf = BytesIO(b"""
# NOTE: one
# NOTE: two
msg = _(u'Foo Bar')
self.assertEqual([u'NOTE: one', u'NOTE: two'], messages[0][3])
def test_invalid_translator_comments(self):
- buf = StringIO("""
+ buf = BytesIO(b"""
# NOTE: this shouldn't apply to any messages
hello = 'there'
self.assertEqual([], messages[0][3])
def test_invalid_translator_comments2(self):
- buf = StringIO("""
+ buf = BytesIO(b"""
# NOTE: Hi!
hithere = _('Hi there!')
self.assertEqual([], messages[1][3])
def test_invalid_translator_comments3(self):
- buf = StringIO("""
+ buf = BytesIO(b"""
# NOTE: Hi,
# there!
self.assertEqual([], messages[0][3])
def test_comment_tag_with_leading_space(self):
- buf = StringIO("""
+ buf = BytesIO(b"""
#: A translation comment
#: with leading spaces
msg = _(u'Foo Bar')
messages[0][3])
def test_different_signatures(self):
- buf = StringIO("""
+ buf = BytesIO(b"""
foo = _('foo', 'bar')
n = ngettext('hello', 'there', n=3)
n = ngettext(n=3, 'hello', 'there')
self.assertEqual(('foo'), messages[5][2])
def test_utf8_message(self):
- buf = StringIO("""
+ buf = BytesIO(b"""
# NOTE: hello
msg = _('Bonjour à tous')
""")
self.assertEqual([u'NOTE: hello'], messages[0][3])
def test_utf8_message_with_magic_comment(self):
- buf = StringIO("""# -*- coding: utf-8 -*-
+ buf = BytesIO(b"""# -*- coding: utf-8 -*-
# NOTE: hello
msg = _('Bonjour à tous')
""")
self.assertEqual(messages[0][2], messages[1][2])
def test_extract_strip_comment_tags(self):
- buf = StringIO("""\
+ buf = BytesIO(b"""\
#: This is a comment with a very simple
#: prefix specified
_('Servus')
class ExtractJavaScriptTestCase(unittest.TestCase):
def test_simple_extract(self):
- buf = StringIO("""\
+ buf = BytesIO(b"""\
msg1 = _('simple')
msg2 = gettext('simple')
msg3 = ngettext('s', 'p', 42)
(3, ('s', 'p'), [], None)], messages)
def test_various_calls(self):
- buf = StringIO("""\
+ buf = BytesIO(b"""\
msg1 = _(i18n_arg.replace(/"/, '"'))
msg2 = ungettext(i18n_arg.replace(/"/, '"'), multi_arg.replace(/"/, '"'), 2)
msg3 = ungettext("Babel", multi_arg.replace(/"/, '"'), 2)
(10, (u'Page', u'Pages'), [], None)], messages)
def test_message_with_line_comment(self):
- buf = StringIO("""\
+ buf = BytesIO(b"""\
// NOTE: hello
msg = _('Bonjour à tous')
""")
self.assertEqual([u'NOTE: hello'], messages[0][3])
def test_message_with_multiline_comment(self):
- buf = StringIO("""\
+ buf = BytesIO(b"""\
/* NOTE: hello
and bonjour
and servus */
self.assertEqual([u'NOTE: hello', 'and bonjour', ' and servus'], messages[0][3])
def test_ignore_function_definitions(self):
- buf = StringIO("""\
+ buf = BytesIO(b"""\
function gettext(value) {
return translations[language][value] || value;
}""")
self.assertEqual(messages, [])
def test_misplaced_comments(self):
- buf = StringIO("""\
+ buf = BytesIO(b"""\
/* NOTE: this won't show up */
foo()
class ExtractTestCase(unittest.TestCase):
def test_invalid_filter(self):
- buf = StringIO("""\
+ buf = BytesIO(b"""\
msg1 = _(i18n_arg.replace(r'\"', '"'))
msg2 = ungettext(i18n_arg.replace(r'\"', '"'), multi_arg.replace(r'\"', '"'), 2)
msg3 = ungettext("Babel", multi_arg.replace(r'\"', '"'), 2)
self.assertRaises(ValueError, list, extract.extract('spam', buf))
def test_different_signatures(self):
- buf = StringIO("""
+ buf = BytesIO(b"""
foo = _('foo', 'bar')
n = ngettext('hello', 'there', n=3)
n = ngettext(n=3, 'hello', 'there')
self.assertEqual((u'hello', u'there'), messages[1][1])
def test_empty_string_msgid(self):
- buf = StringIO("""\
+ buf = BytesIO(b"""\
msg = _('')
""")
stderr = sys.stderr
sys.stderr = stderr
def test_warn_if_empty_string_msgid_found_in_context_aware_extraction_method(self):
- buf = StringIO("\nmsg = pgettext('ctxt', '')\n")
+ buf = BytesIO(b"\nmsg = pgettext('ctxt', '')\n")
stderr = sys.stderr
sys.stderr = StringIO()
try:
from distutils.dist import Distribution
from distutils.errors import DistutilsOptionError
from distutils.log import _global_log
-import doctest
import logging
import os
import shutil
try:
self.cli.run(sys.argv)
self.fail('Expected SystemExit')
- except SystemExit, e:
+ except SystemExit as e:
self.assertEqual(2, e.code)
self.assertEqual("""\
usage: pybabel command [options] [args]
import calendar
from datetime import date, datetime, time, timedelta
-import new
+import types
import unittest
from pytz import timezone
class FormatDateTestCase(unittest.TestCase):
def test_with_time_fields_in_pattern(self):
- self.assertRaises(AttributeError, dates.format_date, date(2007, 04, 01),
+ self.assertRaises(AttributeError, dates.format_date, date(2007, 4, 1),
"yyyy-MM-dd HH:mm", locale='en_US')
def test_with_time_fields_in_pattern_and_datetime_param(self):
self.assertRaises(AttributeError, dates.format_date,
- datetime(2007, 04, 01, 15, 30),
+ datetime(2007, 4, 1, 15, 30),
"yyyy-MM-dd HH:mm", locale='en_US')
def test_with_day_of_year_in_pattern_and_datetime_param(self):
# format_date should work on datetimes just as well (see #282)
- d = datetime(2007, 04, 01)
+ d = datetime(2007, 4, 1)
self.assertEqual('14', dates.format_date(d, 'w', locale='en_US'))
def test_with_date_fields_in_pattern(self):
- self.assertRaises(AttributeError, dates.format_time, date(2007, 04, 01),
+ self.assertRaises(AttributeError, dates.format_time, date(2007, 4, 1),
"yyyy-MM-dd HH:mm", locale='en_US')
def test_with_date_fields_in_pattern_and_datetime_param(self):
self.assertRaises(AttributeError, dates.format_time,
- datetime(2007, 04, 01, 15, 30),
+ datetime(2007, 4, 1, 15, 30),
"yyyy-MM-dd HH:mm", locale='en_US')
UTC = FixedOffsetTimezone(0, 'UTC')
def fake_localize(self, dt, is_dst=False):
raise NotImplementedError()
- UTC.localize = new.instancemethod(fake_localize, UTC, UTC.__class__)
+ UTC.localize = types.MethodType(fake_localize, UTC, UTC.__class__)
# This is important to trigger the actual bug (#257)
self.assertEqual(False, hasattr(UTC, 'normalize'))
return UTC
def test_format_date():
- d = date(2007, 04, 01)
+ d = date(2007, 4, 1)
assert dates.format_date(d, locale='en_US') == u'Apr 1, 2007'
assert (dates.format_date(d, format='full', locale='de_DE') ==
u'Sonntag, 1. April 2007')
def test_format_datetime():
- dt = datetime(2007, 04, 01, 15, 30)
+ dt = datetime(2007, 4, 1, 15, 30)
assert (dates.format_datetime(dt, locale='en_US') ==
u'Apr 1, 2007, 3:30:00 PM')
# individuals. For the exact contribution history, see the revision
# history and logs, available at http://babel.edgewall.org/log/.
-import doctest
import inspect
import os
import shutil
-from StringIO import StringIO
import tempfile
import unittest
import pytest
from babel import support
from babel.messages import Catalog
from babel.messages.mofile import write_mo
+from babel._compat import StringIO
@pytest.mark.usefixtures("os_environ")