From 7dfe6f9e01a4c157f69b6495ca1f293def3acc76 Mon Sep 17 00:00:00 2001 From: Michael Birtwell Date: Wed, 12 Oct 2016 17:46:06 +0100 Subject: [PATCH] Fix read_pofile handling of missing plurals --- babel/messages/pofile.py | 14 ++++++------ tests/messages/test_pofile.py | 40 +++++++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 7 deletions(-) diff --git a/babel/messages/pofile.py b/babel/messages/pofile.py index 47db8a9f..696ec3e9 100644 --- a/babel/messages/pofile.py +++ b/babel/messages/pofile.py @@ -135,13 +135,13 @@ class PoFileParser(object): else: msgid = self.messages[0].denormalize() if isinstance(msgid, (list, tuple)): - string = [] - for idx in range(self.catalog.num_plurals): - try: - string.append(self.translations[idx]) - except IndexError: - string.append((idx, '')) - string = tuple([t[1].denormalize() for t in string]) + string = ['' for _ in range(self.catalog.num_plurals)] + for idx, translation in self.translations: + if idx >= self.catalog.num_plurals: + self._invalid_pofile("", self.offset, "msg has more translations than num_plurals of catalog") + continue + string[idx] = translation.denormalize() + string = tuple(string) else: string = self.translations[0][1].denormalize() if self.context: diff --git a/tests/messages/test_pofile.py b/tests/messages/test_pofile.py index 64bf7148..cef69138 100644 --- a/tests/messages/test_pofile.py +++ b/tests/messages/test_pofile.py @@ -383,6 +383,46 @@ msgstr[1] "Vohs [text]"''') self.assertEqual("Voh [text]", message.string[0]) self.assertEqual("Vohs [text]", message.string[1]) + def test_missing_plural(self): + buf = StringIO('''\ +msgid "" +msgstr "" +"Plural-Forms: nplurals=3; plural=(n < 2) ? n : 2\n" + +msgid "foo" +msgid_plural "foos" +msgstr[0] "Voh [text]" +msgstr[1] "Vohs [text]" +''') + catalog = pofile.read_po(buf, locale='nb_NO') + self.assertEqual(1, len(catalog)) + self.assertEqual(3, catalog.num_plurals) + message = catalog['foo'] + self.assertEqual(3, len(message.string)) + self.assertEqual("Voh [text]", message.string[0]) + self.assertEqual("Vohs [text]", message.string[1]) + self.assertEqual("", message.string[2]) + + def test_missing_plural_in_the_middle(self): + buf = StringIO('''\ +msgid "" +msgstr "" +"Plural-Forms: nplurals=3; plural=(n < 2) ? n : 2\n" + +msgid "foo" +msgid_plural "foos" +msgstr[0] "Voh [text]" +msgstr[2] "Vohs [text]" +''') + catalog = pofile.read_po(buf, locale='nb_NO') + self.assertEqual(1, len(catalog)) + self.assertEqual(3, catalog.num_plurals) + message = catalog['foo'] + self.assertEqual(3, len(message.string)) + self.assertEqual("Voh [text]", message.string[0]) + self.assertEqual("", message.string[1]) + self.assertEqual("Vohs [text]", message.string[2]) + class WritePoTestCase(unittest.TestCase): -- 2.47.2