]> git.ipfire.org Git - thirdparty/babel.git/commitdiff
More work on making tests work on Python 3
authorArmin Ronacher <armin.ronacher@active-4.com>
Sat, 6 Jul 2013 14:39:44 +0000 (16:39 +0200)
committerArmin Ronacher <armin.ronacher@active-4.com>
Sat, 6 Jul 2013 14:39:44 +0000 (16:39 +0200)
babel/_compat.py
babel/messages/mofile.py
babel/numbers.py
tests/messages/test_checkers.py
tests/messages/test_extract.py
tests/messages/test_frontend.py
tests/test_dates.py
tests/test_support.py

index f8248c5f1bc5c3f3c2d9fda6f591c2195cd3d3ca..b03fc64d6629ad03e8047391cd3c65887950c7e7 100644 (file)
@@ -28,11 +28,13 @@ if not PY2:
     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
@@ -43,10 +45,12 @@ else:
     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,)
index 55d9368a948cbdb91ac5f3c653a388007c448f6b..313e3b463173ee8d9a00f7707d63bde59b83df1e 100644 (file)
@@ -22,13 +22,14 @@ import array
 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
@@ -65,7 +66,7 @@ def read_mo(fileobj):
 
     # 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])
index 9c0f8c66d9b24496fc297c8967dc690b81686ee0..7db1d67ac9d0e6cf4e16a172c0d5793ada30af27 100644 (file)
@@ -268,12 +268,12 @@ class NumberFormatError(ValueError):
 
 
 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:
 
@@ -285,11 +285,10 @@ def parse_number(string, locale=LC_NUMERIC):
     :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)
 
@@ -345,7 +344,7 @@ def split_number(value):
         int_part = []
         frac_part = []
 
-        digits = map(str, digits)
+        digits = list(map(str, digits))
 
         # get figures after decimal point
         for i in range(-exp):
index 5c94d848303ccc1de7950b62fb94bf62188ff74c..4eb4cc9d63a19ae1495995adb31a218bb6bc9cde 100644 (file)
@@ -35,7 +35,7 @@ class CheckersTestCase(unittest.TestCase):
             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
@@ -44,17 +44,17 @@ class CheckersTestCase(unittest.TestCase):
 #
 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
index 7cd7393abda6ab6d992f8f217f4277aff549e649..569b4839daa1af8fce59c11dd2a32d6b61f688d4 100644 (file)
 # 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)
@@ -52,7 +51,7 @@ msg10 = dngettext(getDomain(), 'Page', 'Pages', 3)
                          messages)
 
     def test_nested_comments(self):
-        buf = StringIO("""\
+        buf = BytesIO(b"""\
 msg = ngettext('pylon',  # TRANSLATORS: shouldn't be
                'pylons', # TRANSLATORS: seeing this
                count)
@@ -63,7 +62,7 @@ msg = ngettext('pylon',  # TRANSLATORS: shouldn't be
                          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)))
@@ -102,7 +101,7 @@ add_notice(req, ngettext("Bar deleted.",
                          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):
@@ -121,7 +120,7 @@ class Meta:
                          messages)
 
     def test_multiline(self):
-        buf = StringIO("""\
+        buf = BytesIO(b"""\
 msg1 = ngettext('pylon',
                 'pylons', count)
 msg2 = ngettext('elvis',
@@ -134,7 +133,7 @@ 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)
@@ -148,7 +147,7 @@ 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.''')
@@ -164,7 +163,7 @@ gettext message catalog library.''')
             messages)
 
     def test_concatenated_strings(self):
-        buf = StringIO("""\
+        buf = BytesIO(b"""\
 foobar = _('foo' 'bar')
 """)
         messages = list(extract.extract_python(buf,
@@ -173,12 +172,12 @@ foobar = _('foo' 'bar')
         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')
 """)
@@ -187,7 +186,7 @@ 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')
@@ -198,7 +197,7 @@ 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
@@ -211,7 +210,7 @@ msg = _(u'Foo Bar')
                          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
@@ -223,7 +222,7 @@ msg = _(u'Foo Bar')
         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')
@@ -240,7 +239,7 @@ msg = _(u'Foo Bar2')
         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')
@@ -250,7 +249,7 @@ 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'
 
@@ -261,7 +260,7 @@ msg = _(u'Foo Bar')
         self.assertEqual([], messages[0][3])
 
     def test_invalid_translator_comments2(self):
-        buf = StringIO("""
+        buf = BytesIO(b"""
 # NOTE: Hi!
 hithere = _('Hi there!')
 
@@ -278,7 +277,7 @@ hello = _('Hello')
         self.assertEqual([], messages[1][3])
 
     def test_invalid_translator_comments3(self):
-        buf = StringIO("""
+        buf = BytesIO(b"""
 # NOTE: Hi,
 
 # there!
@@ -289,7 +288,7 @@ hithere = _('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')
@@ -300,7 +299,7 @@ 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')
@@ -317,7 +316,7 @@ n = ngettext('foo')
         self.assertEqual(('foo'), messages[5][2])
 
     def test_utf8_message(self):
-        buf = StringIO("""
+        buf = BytesIO(b"""
 # NOTE: hello
 msg = _('Bonjour à tous')
 """)
@@ -327,7 +326,7 @@ 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')
 """)
@@ -354,7 +353,7 @@ msgu = _(u'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')
@@ -375,7 +374,7 @@ _('Babatschi')""")
 class ExtractJavaScriptTestCase(unittest.TestCase):
 
     def test_simple_extract(self):
-        buf = StringIO("""\
+        buf = BytesIO(b"""\
 msg1 = _('simple')
 msg2 = gettext('simple')
 msg3 = ngettext('s', 'p', 42)
@@ -389,7 +388,7 @@ 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)
@@ -409,7 +408,7 @@ msg10 = dngettext(domain, 'Page', 'Pages', 3)
                           (10, (u'Page', u'Pages'), [], None)], messages)
 
     def test_message_with_line_comment(self):
-        buf = StringIO("""\
+        buf = BytesIO(b"""\
 // NOTE: hello
 msg = _('Bonjour à tous')
 """)
@@ -418,7 +417,7 @@ 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 */
@@ -429,7 +428,7 @@ msg = _('Bonjour à tous')
         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;
 }""")
@@ -438,7 +437,7 @@ function gettext(value) {
         self.assertEqual(messages, [])
 
     def test_misplaced_comments(self):
-        buf = StringIO("""\
+        buf = BytesIO(b"""\
 /* NOTE: this won't show up */
 foo()
 
@@ -466,7 +465,7 @@ _('no comment here')
 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)
@@ -490,7 +489,7 @@ msg10 = dngettext(domain, 'Page', 'Pages', 3)
         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')
@@ -506,7 +505,7 @@ n = ngettext('foo')
         self.assertEqual((u'hello', u'there'), messages[1][1])
 
     def test_empty_string_msgid(self):
-        buf = StringIO("""\
+        buf = BytesIO(b"""\
 msg = _('')
 """)
         stderr = sys.stderr
@@ -521,7 +520,7 @@ msg = _('')
             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:
index 9e8b6fd77d4fea5d4def6acb6eb82a4315f78087..88315fbcb1480296b425ce2d863f873d6f5ab6ea 100644 (file)
@@ -15,7 +15,6 @@ from datetime import datetime
 from distutils.dist import Distribution
 from distutils.errors import DistutilsOptionError
 from distutils.log import _global_log
-import doctest
 import logging
 import os
 import shutil
@@ -695,7 +694,7 @@ class CommandLineInterfaceTestCase(unittest.TestCase):
         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]
index 9d559ae27d81b0f5f3513c6b36b350394a554a5d..25202a9fc770d12c101034f7b7a87a33c08e5077 100644 (file)
@@ -13,7 +13,7 @@
 
 import calendar
 from datetime import date, datetime, time, timedelta
-import new
+import types
 import unittest
 
 from pytz import timezone
@@ -228,17 +228,17 @@ class DateTimeFormatTestCase(unittest.TestCase):
 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'))
 
 
@@ -267,12 +267,12 @@ class FormatTimeTestCase(unittest.TestCase):
 
 
     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')
 
 
@@ -317,7 +317,7 @@ class TimeZoneAdjustTestCase(unittest.TestCase):
         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
@@ -421,7 +421,7 @@ def test_get_timezone_name():
 
 
 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')
@@ -430,7 +430,7 @@ def test_format_date():
 
 
 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')
 
index 303fb3bd3b01a1f73fbde36c7e995074ae873655..5d9bf3675be0f0d9e76dbe858e59e84bc0bba041 100644 (file)
 # 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
@@ -24,6 +22,7 @@ from datetime import date, datetime, timedelta
 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")