From d06dcbf2a0cc34c3172fd175cfb3c43684cfd37c Mon Sep 17 00:00:00 2001 From: Aarni Koskela Date: Tue, 10 May 2022 11:52:35 +0300 Subject: [PATCH 1/2] tests: Use regular asserts instead of unittest functions Automated conversion initially applied with https://github.com/warlo/codemod-unittest-to-pytest-asserts, followed by some manual changes for brevity. --- tests/messages/test_catalog.py | 123 ++++----- tests/messages/test_extract.py | 233 ++++++++-------- tests/messages/test_frontend.py | 125 ++++----- tests/messages/test_mofile.py | 28 +- tests/messages/test_pofile.py | 271 +++++++++---------- tests/test_dates.py | 463 ++++++++++++-------------------- tests/test_localedata.py | 21 +- tests/test_numbers.py | 219 ++++++--------- tests/test_support.py | 29 +- tests/test_util.py | 6 +- 10 files changed, 639 insertions(+), 879 deletions(-) diff --git a/tests/messages/test_catalog.py b/tests/messages/test_catalog.py index f32023620..cc5fb49fc 100644 --- a/tests/messages/test_catalog.py +++ b/tests/messages/test_catalog.py @@ -41,18 +41,17 @@ def test_python_format(self): def test_translator_comments(self): mess = catalog.Message('foo', user_comments=['Comment About `foo`']) - self.assertEqual(mess.user_comments, ['Comment About `foo`']) + assert mess.user_comments == ['Comment About `foo`'] mess = catalog.Message('foo', auto_comments=['Comment 1 About `foo`', 'Comment 2 About `foo`']) - self.assertEqual(mess.auto_comments, ['Comment 1 About `foo`', - 'Comment 2 About `foo`']) + assert mess.auto_comments == ['Comment 1 About `foo`', 'Comment 2 About `foo`'] def test_clone_message_object(self): msg = catalog.Message('foo', locations=[('foo.py', 42)]) clone = msg.clone() clone.locations.append(('bar.py', 42)) - self.assertEqual(msg.locations, [('foo.py', 42)]) + assert msg.locations == [('foo.py', 42)] msg.flags.add('fuzzy') assert not clone.fuzzy and msg.fuzzy @@ -62,33 +61,31 @@ class CatalogTestCase(unittest.TestCase): def test_add_returns_message_instance(self): cat = catalog.Catalog() message = cat.add('foo') - self.assertEqual('foo', message.id) + assert message.id == 'foo' def test_two_messages_with_same_singular(self): cat = catalog.Catalog() cat.add('foo') cat.add(('foo', 'foos')) - self.assertEqual(1, len(cat)) + assert len(cat) == 1 def test_duplicate_auto_comment(self): cat = catalog.Catalog() cat.add('foo', auto_comments=['A comment']) cat.add('foo', auto_comments=['A comment', 'Another comment']) - self.assertEqual(['A comment', 'Another comment'], - cat['foo'].auto_comments) + assert cat['foo'].auto_comments == ['A comment', 'Another comment'] def test_duplicate_user_comment(self): cat = catalog.Catalog() cat.add('foo', user_comments=['A comment']) cat.add('foo', user_comments=['A comment', 'Another comment']) - self.assertEqual(['A comment', 'Another comment'], - cat['foo'].user_comments) + assert cat['foo'].user_comments == ['A comment', 'Another comment'] def test_duplicate_location(self): cat = catalog.Catalog() cat.add('foo', locations=[('foo.py', 1)]) cat.add('foo', locations=[('foo.py', 1)]) - self.assertEqual([('foo.py', 1)], cat['foo'].locations) + assert cat['foo'].locations == [('foo.py', 1)] def test_update_message_changed_to_plural(self): cat = catalog.Catalog() @@ -96,7 +93,7 @@ def test_update_message_changed_to_plural(self): tmpl = catalog.Catalog() tmpl.add((u'foo', u'foos')) cat.update(tmpl) - self.assertEqual((u'Voh', ''), cat['foo'].string) + assert cat['foo'].string == ('Voh', '') assert cat['foo'].fuzzy def test_update_message_changed_to_simple(self): @@ -105,22 +102,22 @@ def test_update_message_changed_to_simple(self): tmpl = catalog.Catalog() tmpl.add(u'foo') cat.update(tmpl) - self.assertEqual(u'Voh', cat['foo'].string) + assert cat['foo'].string == 'Voh' assert cat['foo'].fuzzy def test_update_message_updates_comments(self): cat = catalog.Catalog() cat[u'foo'] = catalog.Message('foo', locations=[('main.py', 5)]) - self.assertEqual(cat[u'foo'].auto_comments, []) - self.assertEqual(cat[u'foo'].user_comments, []) + assert cat['foo'].auto_comments == [] + assert cat['foo'].user_comments == [] # Update cat[u'foo'] with a new location and a comment cat[u'foo'] = catalog.Message('foo', locations=[('main.py', 7)], user_comments=['Foo Bar comment 1']) - self.assertEqual(cat[u'foo'].user_comments, ['Foo Bar comment 1']) + assert cat['foo'].user_comments == ['Foo Bar comment 1'] # now add yet another location with another comment cat[u'foo'] = catalog.Message('foo', locations=[('main.py', 9)], auto_comments=['Foo Bar comment 2']) - self.assertEqual(cat[u'foo'].auto_comments, ['Foo Bar comment 2']) + assert cat['foo'].auto_comments == ['Foo Bar comment 2'] def test_update_fuzzy_matching_with_case_change(self): cat = catalog.Catalog() @@ -129,11 +126,11 @@ def test_update_fuzzy_matching_with_case_change(self): tmpl = catalog.Catalog() tmpl.add('Foo') cat.update(tmpl) - self.assertEqual(1, len(cat.obsolete)) + assert len(cat.obsolete) == 1 assert 'foo' not in cat - self.assertEqual('Voh', cat['Foo'].string) - self.assertEqual(True, cat['Foo'].fuzzy) + assert cat['Foo'].string == 'Voh' + assert cat['Foo'].fuzzy is True def test_update_fuzzy_matching_with_char_change(self): cat = catalog.Catalog() @@ -142,11 +139,11 @@ def test_update_fuzzy_matching_with_char_change(self): tmpl = catalog.Catalog() tmpl.add('foo') cat.update(tmpl) - self.assertEqual(1, len(cat.obsolete)) + assert len(cat.obsolete) == 1 assert 'fo' not in cat - self.assertEqual('Voh', cat['foo'].string) - self.assertEqual(True, cat['foo'].fuzzy) + assert cat['foo'].string == 'Voh' + assert cat['foo'].fuzzy is True def test_update_fuzzy_matching_no_msgstr(self): cat = catalog.Catalog() @@ -158,10 +155,10 @@ def test_update_fuzzy_matching_no_msgstr(self): assert 'fo' in cat assert 'foo' in cat - self.assertEqual('', cat['fo'].string) - self.assertEqual(False, cat['fo'].fuzzy) - self.assertEqual(None, cat['foo'].string) - self.assertEqual(False, cat['foo'].fuzzy) + assert cat['fo'].string == '' + assert cat['fo'].fuzzy is False + assert cat['foo'].string is None + assert cat['foo'].fuzzy is False def test_update_fuzzy_matching_with_new_context(self): cat = catalog.Catalog() @@ -170,13 +167,13 @@ def test_update_fuzzy_matching_with_new_context(self): tmpl = catalog.Catalog() tmpl.add('Foo', context='Menu') cat.update(tmpl) - self.assertEqual(1, len(cat.obsolete)) + assert len(cat.obsolete) == 1 assert 'foo' not in cat message = cat.get('Foo', 'Menu') - self.assertEqual('Voh', message.string) - self.assertEqual(True, message.fuzzy) - self.assertEqual('Menu', message.context) + assert message.string == 'Voh' + assert message.fuzzy is True + assert message.context == 'Menu' def test_update_fuzzy_matching_with_changed_context(self): cat = catalog.Catalog() @@ -185,13 +182,13 @@ def test_update_fuzzy_matching_with_changed_context(self): tmpl = catalog.Catalog() tmpl.add('Foo', context='Menu|Edit') cat.update(tmpl) - self.assertEqual(1, len(cat.obsolete)) + assert len(cat.obsolete) == 1 assert cat.get('Foo', 'Menu|File') is None message = cat.get('Foo', 'Menu|Edit') - self.assertEqual('Voh', message.string) - self.assertEqual(True, message.fuzzy) - self.assertEqual('Menu|Edit', message.context) + assert message.string == 'Voh' + assert message.fuzzy is True + assert message.context == 'Menu|Edit' def test_update_fuzzy_matching_no_cascading(self): cat = catalog.Catalog() @@ -205,12 +202,12 @@ def test_update_fuzzy_matching_no_cascading(self): assert 'fo' in cat assert 'foo' in cat - self.assertEqual('Voh', cat['fo'].string) - self.assertEqual(False, cat['fo'].fuzzy) - self.assertEqual('Vohe', cat['foo'].string) - self.assertEqual(False, cat['foo'].fuzzy) - self.assertEqual('Vohe', cat['fooo'].string) - self.assertEqual(True, cat['fooo'].fuzzy) + assert cat['fo'].string == 'Voh' + assert cat['fo'].fuzzy is False + assert cat['foo'].string == 'Vohe' + assert cat['foo'].fuzzy is False + assert cat['fooo'].string == 'Vohe' + assert cat['fooo'].fuzzy is True def test_update_without_fuzzy_matching(self): cat = catalog.Catalog() @@ -219,7 +216,7 @@ def test_update_without_fuzzy_matching(self): tmpl = catalog.Catalog() tmpl.add('foo') cat.update(tmpl, no_fuzzy_matching=True) - self.assertEqual(2, len(cat.obsolete)) + assert len(cat.obsolete) == 2 def test_fuzzy_matching_regarding_plurals(self): cat = catalog.Catalog() @@ -227,12 +224,12 @@ def test_fuzzy_matching_regarding_plurals(self): ru = copy.copy(cat) ru.locale = 'ru_RU' ru.update(cat) - self.assertEqual(True, ru['foo'].fuzzy) + assert ru['foo'].fuzzy is True ru = copy.copy(cat) ru.locale = 'ru_RU' ru['foo'].string = ('foh', 'fohh', 'fohhh') ru.update(cat) - self.assertEqual(False, ru['foo'].fuzzy) + assert ru['foo'].fuzzy is False def test_update_no_template_mutation(self): tmpl = catalog.Catalog() @@ -243,22 +240,19 @@ def test_update_no_template_mutation(self): cat2 = catalog.Catalog() cat2.update(tmpl) - self.assertEqual(None, cat2['foo'].string) - self.assertEqual(False, cat2['foo'].fuzzy) + assert cat2['foo'].string is None + assert cat2['foo'].fuzzy is False def test_update_po_updates_pot_creation_date(self): template = catalog.Catalog() localized_catalog = copy.deepcopy(template) localized_catalog.locale = 'de_DE' - self.assertNotEqual(template.mime_headers, - localized_catalog.mime_headers) - self.assertEqual(template.creation_date, - localized_catalog.creation_date) + assert template.mime_headers != localized_catalog.mime_headers + assert template.creation_date == localized_catalog.creation_date template.creation_date = datetime.datetime.now() - \ datetime.timedelta(minutes=5) localized_catalog.update(template) - self.assertEqual(template.creation_date, - localized_catalog.creation_date) + assert template.creation_date == localized_catalog.creation_date def test_update_po_keeps_po_revision_date(self): template = catalog.Catalog() @@ -266,14 +260,12 @@ def test_update_po_keeps_po_revision_date(self): localized_catalog.locale = 'de_DE' fake_rev_date = datetime.datetime.now() - datetime.timedelta(days=5) localized_catalog.revision_date = fake_rev_date - self.assertNotEqual(template.mime_headers, - localized_catalog.mime_headers) - self.assertEqual(template.creation_date, - localized_catalog.creation_date) + assert template.mime_headers != localized_catalog.mime_headers + assert template.creation_date == localized_catalog.creation_date template.creation_date = datetime.datetime.now() - \ datetime.timedelta(minutes=5) localized_catalog.update(template) - self.assertEqual(localized_catalog.revision_date, fake_rev_date) + assert localized_catalog.revision_date == fake_rev_date def test_stores_datetime_correctly(self): localized = catalog.Catalog() @@ -283,7 +275,7 @@ def test_stores_datetime_correctly(self): "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') + assert value == '2009-03-09 15:47-0700' def test_mime_headers_contain_same_information_as_attributes(self): cat = catalog.Catalog() @@ -292,20 +284,19 @@ def test_mime_headers_contain_same_information_as_attributes(self): "Language-Team: de \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) + assert cat.locale is None mime_headers = dict(cat.mime_headers) - self.assertEqual('Foo Bar ', cat.last_translator) - self.assertEqual('Foo Bar ', - mime_headers['Last-Translator']) + assert cat.last_translator == 'Foo Bar ' + assert mime_headers['Last-Translator'] == 'Foo Bar ' - self.assertEqual('de ', cat.language_team) - self.assertEqual('de ', mime_headers['Language-Team']) + assert cat.language_team == 'de ' + assert mime_headers['Language-Team'] == 'de ' dt = datetime.datetime(2009, 3, 9, 15, 47, tzinfo=FixedOffsetTimezone(-7 * 60)) - self.assertEqual(dt, cat.revision_date) + assert cat.revision_date == dt formatted_dt = format_datetime(dt, 'yyyy-MM-dd HH:mmZ', locale='en') - self.assertEqual(formatted_dt, mime_headers['PO-Revision-Date']) + assert mime_headers['PO-Revision-Date'] == formatted_dt def test_message_fuzzy(): diff --git a/tests/messages/test_extract.py b/tests/messages/test_extract.py index 3ed71de44..e3d925e5d 100644 --- a/tests/messages/test_extract.py +++ b/tests/messages/test_extract.py @@ -36,7 +36,7 @@ def test_nested_calls(self): messages = list(extract.extract_python(buf, extract.DEFAULT_KEYWORDS.keys(), [], {})) - self.assertEqual([ + assert messages == [ (1, '_', None, []), (2, 'ungettext', (None, None, None), []), (3, 'ungettext', (u'Babel', None, None), []), @@ -46,8 +46,8 @@ def test_nested_calls(self): (7, '_', None, []), (8, 'gettext', u'Rabbit', []), (9, 'dgettext', (u'wiki', None), []), - (10, 'dngettext', (None, u'Page', u'Pages', None), [])], - messages) + (10, 'dngettext', (None, u'Page', u'Pages', None), []), + ] def test_extract_default_encoding_ascii(self): buf = BytesIO(b'_("a")') @@ -55,14 +55,14 @@ def test_extract_default_encoding_ascii(self): buf, list(extract.DEFAULT_KEYWORDS), [], {}, )) # Should work great in both py2 and py3 - self.assertEqual([(1, '_', 'a', [])], messages) + assert messages == [(1, '_', 'a', [])] def test_extract_default_encoding_utf8(self): buf = BytesIO(u'_("☃")'.encode('UTF-8')) messages = list(extract.extract_python( buf, list(extract.DEFAULT_KEYWORDS), [], {}, )) - self.assertEqual([(1, '_', u'☃', [])], messages) + assert messages == [(1, '_', '☃', [])] def test_nested_comments(self): buf = BytesIO(b"""\ @@ -72,8 +72,7 @@ def test_nested_comments(self): """) messages = list(extract.extract_python(buf, ('ngettext',), ['TRANSLATORS:'], {})) - self.assertEqual([(1, 'ngettext', (u'pylon', u'pylons', None), [])], - messages) + assert messages == [(1, 'ngettext', ('pylon', 'pylons', None), [])] def test_comments_with_calls_that_spawn_multiple_lines(self): buf = BytesIO(b"""\ @@ -96,23 +95,10 @@ def test_comments_with_calls_that_spawn_multiple_lines(self): messages = list(extract.extract_python(buf, ('ngettext', '_'), ['NOTE:'], {'strip_comment_tags': False})) - self.assertEqual((6, '_', 'Locale deleted.', - [u'NOTE: This Comment SHOULD Be Extracted']), - messages[1]) - self.assertEqual((10, 'ngettext', (u'Foo deleted.', u'Foos deleted.', - None), - [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']), - messages[0]) - self.assertEqual((15, 'ngettext', (u'Bar deleted.', u'Bars deleted.', - None), - [u'NOTE: This Comment SHOULD Be Extracted', - u'NOTE: And This One Too']), - messages[3]) + assert messages[0] == (3, 'ngettext', ('Catalog deleted.', 'Catalogs deleted.', None), ['NOTE: This Comment SHOULD Be Extracted']) + assert messages[1] == (6, '_', 'Locale deleted.', ['NOTE: This Comment SHOULD Be Extracted']) + assert messages[2] == (10, 'ngettext', ('Foo deleted.', 'Foos deleted.', None), ['NOTE: This Comment SHOULD Be Extracted']) + assert messages[3] == (15, 'ngettext', ('Bar deleted.', 'Bars deleted.', None), ['NOTE: This Comment SHOULD Be Extracted', 'NOTE: And This One Too']) def test_declarations(self): buf = BytesIO(b"""\ @@ -128,10 +114,11 @@ class Meta: messages = list(extract.extract_python(buf, extract.DEFAULT_KEYWORDS.keys(), [], {})) - self.assertEqual([(3, '_', u'Page arg 1', []), - (3, '_', u'Page arg 2', []), - (8, '_', u'log entry', [])], - messages) + assert messages == [ + (3, '_', 'Page arg 1', []), + (3, '_', 'Page arg 2', []), + (8, '_', 'log entry', []) + ] def test_multiline(self): buf = BytesIO(b"""\ @@ -142,9 +129,10 @@ def test_multiline(self): count) """) messages = list(extract.extract_python(buf, ('ngettext',), [], {})) - self.assertEqual([(1, 'ngettext', (u'pylon', u'pylons', None), []), - (3, 'ngettext', (u'elvis', u'elvises', None), [])], - messages) + assert messages == [ + (1, 'ngettext', ('pylon', 'pylons', None), []), + (3, 'ngettext', ('elvis', 'elvises', None), []), + ] def test_npgettext(self): buf = BytesIO(b"""\ @@ -155,9 +143,10 @@ def test_npgettext(self): count) """) 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) + assert messages == [ + (1, 'npgettext', ('Strings', 'pylon', 'pylons', None), []), + (3, 'npgettext', ('Strings', 'elvis', 'elvises', None), []), + ] buf = BytesIO(b"""\ msg = npgettext('Strings', 'pylon', # TRANSLATORS: shouldn't be 'pylons', # TRANSLATORS: seeing this @@ -165,8 +154,9 @@ def test_npgettext(self): """) messages = list(extract.extract_python(buf, ('npgettext',), ['TRANSLATORS:'], {})) - self.assertEqual([(1, 'npgettext', (u'Strings', u'pylon', u'pylons', None), [])], - messages) + assert messages == [ + (1, 'npgettext', ('Strings', 'pylon', 'pylons', None), []), + ] def test_triple_quoted_strings(self): buf = BytesIO(b"""\ @@ -177,10 +167,11 @@ def test_triple_quoted_strings(self): messages = list(extract.extract_python(buf, extract.DEFAULT_KEYWORDS.keys(), [], {})) - self.assertEqual([(1, '_', u'pylons', []), - (2, 'ngettext', (u'elvis', u'elvises', None), []), - (3, 'ngettext', (u'elvis', u'elvises', None), [])], - messages) + assert messages == [ + (1, '_', 'pylons', []), + (2, 'ngettext', ('elvis', 'elvises', None), []), + (3, 'ngettext', ('elvis', 'elvises', None), []), + ] def test_multiline_strings(self): buf = BytesIO(b"""\ @@ -191,12 +182,12 @@ def test_multiline_strings(self): messages = list(extract.extract_python(buf, extract.DEFAULT_KEYWORDS.keys(), [], {})) - self.assertEqual( - [(1, '_', - u'This module provides internationalization and localization\n' - 'support for your Python programs by providing an interface to ' - 'the GNU\ngettext message catalog library.', [])], - messages) + assert messages == [ + (1, '_', + 'This module provides internationalization and localization\n' + 'support for your Python programs by providing an interface to ' + 'the GNU\ngettext message catalog library.', []), + ] def test_concatenated_strings(self): buf = BytesIO(b"""\ @@ -205,12 +196,12 @@ def test_concatenated_strings(self): messages = list(extract.extract_python(buf, extract.DEFAULT_KEYWORDS.keys(), [], {})) - self.assertEqual(u'foobar', messages[0][2]) + assert messages[0][2] == 'foobar' def test_unicode_string_arg(self): buf = BytesIO(b"msg = _(u'Foo Bar')") messages = list(extract.extract_python(buf, ('_',), [], {})) - self.assertEqual(u'Foo Bar', messages[0][2]) + assert messages[0][2] == 'Foo Bar' def test_comment_tag(self): buf = BytesIO(b""" @@ -218,8 +209,8 @@ def test_comment_tag(self): msg = _(u'Foo Bar') """) messages = list(extract.extract_python(buf, ('_',), ['NOTE:'], {})) - self.assertEqual(u'Foo Bar', messages[0][2]) - self.assertEqual([u'NOTE: A translation comment'], messages[0][3]) + assert messages[0][2] == 'Foo Bar' + assert messages[0][3] == ['NOTE: A translation comment'] def test_comment_tag_multiline(self): buf = BytesIO(b""" @@ -228,9 +219,8 @@ def test_comment_tag_multiline(self): msg = _(u'Foo Bar') """) messages = list(extract.extract_python(buf, ('_',), ['NOTE:'], {})) - self.assertEqual(u'Foo Bar', messages[0][2]) - self.assertEqual([u'NOTE: A translation comment', u'with a second line'], - messages[0][3]) + assert messages[0][2] == 'Foo Bar' + assert messages[0][3] == ['NOTE: A translation comment', 'with a second line'] def test_translator_comments_with_previous_non_translator_comments(self): buf = BytesIO(b""" @@ -241,9 +231,8 @@ def test_translator_comments_with_previous_non_translator_comments(self): msg = _(u'Foo Bar') """) messages = list(extract.extract_python(buf, ('_',), ['NOTE:'], {})) - self.assertEqual(u'Foo Bar', messages[0][2]) - self.assertEqual([u'NOTE: A translation comment', u'with a second line'], - messages[0][3]) + assert messages[0][2] == 'Foo Bar' + assert messages[0][3] == ['NOTE: A translation comment', 'with a second line'] def test_comment_tags_not_on_start_of_comment(self): buf = BytesIO(b""" @@ -254,8 +243,8 @@ def test_comment_tags_not_on_start_of_comment(self): msg = _(u'Foo Bar') """) messages = list(extract.extract_python(buf, ('_',), ['NOTE:'], {})) - self.assertEqual(u'Foo Bar', messages[0][2]) - self.assertEqual([u'NOTE: This one will be'], messages[0][3]) + assert messages[0][2] == 'Foo Bar' + assert messages[0][3] == ['NOTE: This one will be'] def test_multiple_comment_tags(self): buf = BytesIO(b""" @@ -268,11 +257,10 @@ def test_multiple_comment_tags(self): """) messages = list(extract.extract_python(buf, ('_',), ['NOTE1:', 'NOTE2:'], {})) - self.assertEqual(u'Foo Bar1', messages[0][2]) - self.assertEqual([u'NOTE1: A translation comment for tag1', - u'with a second line'], messages[0][3]) - self.assertEqual(u'Foo Bar2', messages[1][2]) - self.assertEqual([u'NOTE2: A translation comment for tag2'], messages[1][3]) + assert messages[0][2] == 'Foo Bar1' + assert messages[0][3] == ['NOTE1: A translation comment for tag1', 'with a second line'] + assert messages[1][2] == 'Foo Bar2' + assert messages[1][3] == ['NOTE2: A translation comment for tag2'] def test_two_succeeding_comments(self): buf = BytesIO(b""" @@ -281,8 +269,8 @@ def test_two_succeeding_comments(self): msg = _(u'Foo Bar') """) messages = list(extract.extract_python(buf, ('_',), ['NOTE:'], {})) - self.assertEqual(u'Foo Bar', messages[0][2]) - self.assertEqual([u'NOTE: one', u'NOTE: two'], messages[0][3]) + assert messages[0][2] == 'Foo Bar' + assert messages[0][3] == ['NOTE: one', 'NOTE: two'] def test_invalid_translator_comments(self): buf = BytesIO(b""" @@ -292,8 +280,8 @@ def test_invalid_translator_comments(self): msg = _(u'Foo Bar') """) messages = list(extract.extract_python(buf, ('_',), ['NOTE:'], {})) - self.assertEqual(u'Foo Bar', messages[0][2]) - self.assertEqual([], messages[0][3]) + assert messages[0][2] == 'Foo Bar' + assert messages[0][3] == [] def test_invalid_translator_comments2(self): buf = BytesIO(b""" @@ -307,10 +295,10 @@ def test_invalid_translator_comments2(self): hello = _('Hello') """) messages = list(extract.extract_python(buf, ('_',), ['NOTE:'], {})) - self.assertEqual(u'Hi there!', messages[0][2]) - self.assertEqual([u'NOTE: Hi!'], messages[0][3]) - self.assertEqual(u'Hello', messages[1][2]) - self.assertEqual([], messages[1][3]) + assert messages[0][2] == 'Hi there!' + assert messages[0][3] == ['NOTE: Hi!'] + assert messages[1][2] == 'Hello' + assert messages[1][3] == [] def test_invalid_translator_comments3(self): buf = BytesIO(b""" @@ -320,8 +308,8 @@ def test_invalid_translator_comments3(self): hithere = _('Hi there!') """) messages = list(extract.extract_python(buf, ('_',), ['NOTE:'], {})) - self.assertEqual(u'Hi there!', messages[0][2]) - self.assertEqual([], messages[0][3]) + assert messages[0][2] == 'Hi there!' + assert messages[0][3] == [] def test_comment_tag_with_leading_space(self): buf = BytesIO(b""" @@ -330,9 +318,8 @@ def test_comment_tag_with_leading_space(self): msg = _(u'Foo Bar') """) messages = list(extract.extract_python(buf, ('_',), [':'], {})) - self.assertEqual(u'Foo Bar', messages[0][2]) - self.assertEqual([u': A translation comment', u': with leading spaces'], - messages[0][3]) + assert messages[0][2] == 'Foo Bar' + assert messages[0][3] == [': A translation comment', ': with leading spaces'] def test_different_signatures(self): buf = BytesIO(b""" @@ -344,22 +331,22 @@ def test_different_signatures(self): n = ngettext('foo') """) messages = list(extract.extract_python(buf, ('_', 'ngettext'), [], {})) - self.assertEqual((u'foo', u'bar'), messages[0][2]) - self.assertEqual((u'hello', u'there', None), messages[1][2]) - self.assertEqual((None, u'hello', u'there'), messages[2][2]) - self.assertEqual((None, None), messages[3][2]) - self.assertEqual(None, messages[4][2]) - self.assertEqual('foo', messages[5][2]) + assert messages[0][2] == ('foo', 'bar') + assert messages[1][2] == ('hello', 'there', None) + assert messages[2][2] == (None, 'hello', 'there') + assert messages[3][2] == (None, None) + assert messages[4][2] is None + assert messages[5][2] == 'foo' def test_utf8_message(self): - buf = BytesIO(u""" + buf = BytesIO(""" # NOTE: hello msg = _('Bonjour à tous') """.encode('utf-8')) messages = list(extract.extract_python(buf, ('_',), ['NOTE:'], {'encoding': 'utf-8'})) - self.assertEqual(u'Bonjour à tous', messages[0][2]) - self.assertEqual([u'NOTE: hello'], messages[0][3]) + assert messages[0][2] == 'Bonjour à tous' + assert messages[0][3] == ['NOTE: hello'] def test_utf8_message_with_magic_comment(self): buf = BytesIO(u"""# -*- coding: utf-8 -*- @@ -367,8 +354,8 @@ def test_utf8_message_with_magic_comment(self): msg = _('Bonjour à tous') """.encode('utf-8')) messages = list(extract.extract_python(buf, ('_',), ['NOTE:'], {})) - self.assertEqual(u'Bonjour à tous', messages[0][2]) - self.assertEqual([u'NOTE: hello'], messages[0][3]) + assert messages[0][2] == 'Bonjour à tous' + assert messages[0][3] == ['NOTE: hello'] def test_utf8_message_with_utf8_bom(self): buf = BytesIO(codecs.BOM_UTF8 + u""" @@ -376,8 +363,8 @@ def test_utf8_message_with_utf8_bom(self): msg = _('Bonjour à tous') """.encode('utf-8')) messages = list(extract.extract_python(buf, ('_',), ['NOTE:'], {})) - self.assertEqual(u'Bonjour à tous', messages[0][2]) - self.assertEqual([u'NOTE: hello'], messages[0][3]) + assert messages[0][2] == 'Bonjour à tous' + assert messages[0][3] == ['NOTE: hello'] def test_utf8_message_with_utf8_bom_and_magic_comment(self): buf = BytesIO(codecs.BOM_UTF8 + u"""# -*- coding: utf-8 -*- @@ -385,8 +372,8 @@ def test_utf8_message_with_utf8_bom_and_magic_comment(self): msg = _('Bonjour à tous') """.encode('utf-8')) messages = list(extract.extract_python(buf, ('_',), ['NOTE:'], {})) - self.assertEqual(u'Bonjour à tous', messages[0][2]) - self.assertEqual([u'NOTE: hello'], messages[0][3]) + assert messages[0][2] == 'Bonjour à tous' + assert messages[0][3] == ['NOTE: hello'] def test_utf8_bom_with_latin_magic_comment_fails(self): buf = BytesIO(codecs.BOM_UTF8 + u"""# -*- coding: latin-1 -*- @@ -402,8 +389,8 @@ def test_utf8_raw_strings_match_unicode_strings(self): msgu = _(u'Bonjour à tous') """.encode('utf-8')) messages = list(extract.extract_python(buf, ('_',), ['NOTE:'], {})) - self.assertEqual(u'Bonjour à tous', messages[0][2]) - self.assertEqual(messages[0][2], messages[1][2]) + assert messages[0][2] == 'Bonjour à tous' + assert messages[0][2] == messages[1][2] def test_extract_strip_comment_tags(self): buf = BytesIO(b"""\ @@ -416,12 +403,10 @@ def test_extract_strip_comment_tags(self): _('Babatschi')""") messages = list(extract.extract('python', buf, comment_tags=['NOTE:', ':'], strip_comment_tags=True)) - self.assertEqual(u'Servus', messages[0][1]) - self.assertEqual([u'This is a comment with a very simple', - u'prefix specified'], messages[0][2]) - self.assertEqual(u'Babatschi', messages[1][1]) - self.assertEqual([u'This is a multiline comment with', - u'a prefix too'], messages[1][2]) + assert messages[0][1] == 'Servus' + assert messages[0][2] == ['This is a comment with a very simple', 'prefix specified'] + assert messages[1][1] == 'Babatschi' + assert messages[1][2] == ['This is a multiline comment with', 'a prefix too'] def test_nested_messages(self): buf = BytesIO(b""" @@ -437,22 +422,22 @@ def test_nested_messages(self): _(u'Armin')) """) messages = list(extract.extract_python(buf, ('_',), ['NOTE:'], {})) - self.assertEqual((u'Hello, {name}!', None), messages[0][2]) - self.assertEqual([u'NOTE: First'], messages[0][3]) - self.assertEqual(u'Foo Bar', messages[1][2]) - self.assertEqual([], messages[1][3]) - self.assertEqual((u'Hello, {name1} and {name2}!', None), messages[2][2]) - self.assertEqual([u'NOTE: Second'], messages[2][3]) - self.assertEqual(u'Heungsub', messages[3][2]) - self.assertEqual([], messages[3][3]) - self.assertEqual(u'Armin', messages[4][2]) - self.assertEqual([], messages[4][3]) - self.assertEqual((u'Hello, {0} and {1}!', None), messages[5][2]) - self.assertEqual([u'NOTE: Third'], messages[5][3]) - self.assertEqual(u'Heungsub', messages[6][2]) - self.assertEqual([], messages[6][3]) - self.assertEqual(u'Armin', messages[7][2]) - self.assertEqual([], messages[7][3]) + assert messages[0][2] == ('Hello, {name}!', None) + assert messages[0][3] == ['NOTE: First'] + assert messages[1][2] == 'Foo Bar' + assert messages[1][3] == [] + assert messages[2][2] == ('Hello, {name1} and {name2}!', None) + assert messages[2][3] == ['NOTE: Second'] + assert messages[3][2] == 'Heungsub' + assert messages[3][3] == [] + assert messages[4][2] == 'Armin' + assert messages[4][3] == [] + assert messages[5][2] == ('Hello, {0} and {1}!', None) + assert messages[5][3] == ['NOTE: Third'] + assert messages[6][2] == 'Heungsub' + assert messages[6][3] == [] + assert messages[7][2] == 'Armin' + assert messages[7][3] == [] class ExtractTestCase(unittest.TestCase): @@ -473,9 +458,11 @@ def test_invalid_filter(self): messages = \ list(extract.extract('python', buf, extract.DEFAULT_KEYWORDS, [], {})) - self.assertEqual([(5, (u'bunny', u'bunnies'), [], None), - (8, u'Rabbit', [], None), - (10, (u'Page', u'Pages'), [], None)], messages) + assert messages == [ + (5, ('bunny', 'bunnies'), [], None), + (8, 'Rabbit', [], None), + (10, ('Page', 'Pages'), [], None), + ] def test_invalid_extract_method(self): buf = BytesIO(b'') @@ -493,9 +480,9 @@ def test_different_signatures(self): messages = \ list(extract.extract('python', buf, extract.DEFAULT_KEYWORDS, [], {})) - self.assertEqual(len(messages), 2) - self.assertEqual(u'foo', messages[0][1]) - self.assertEqual((u'hello', u'there'), messages[1][1]) + assert len(messages) == 2 + assert messages[0][1] == 'foo' + assert messages[1][1] == ('hello', 'there') def test_empty_string_msgid(self): buf = BytesIO(b"""\ @@ -507,7 +494,7 @@ def test_empty_string_msgid(self): messages = \ list(extract.extract('python', buf, extract.DEFAULT_KEYWORDS, [], {})) - self.assertEqual([], messages) + assert messages == [] assert 'warning: Empty msgid.' in sys.stderr.getvalue() finally: sys.stderr = stderr @@ -518,7 +505,7 @@ def test_warn_if_empty_string_msgid_found_in_context_aware_extraction_method(sel sys.stderr = StringIO() try: messages = extract.extract('python', buf) - self.assertEqual([], list(messages)) + assert list(messages) == [] assert 'warning: Empty msgid.' in sys.stderr.getvalue() finally: sys.stderr = stderr diff --git a/tests/messages/test_frontend.py b/tests/messages/test_frontend.py index bacb0e2d4..0eb7e8f3a 100644 --- a/tests/messages/test_frontend.py +++ b/tests/messages/test_frontend.py @@ -61,12 +61,14 @@ def tearDown(self): def test_no_directory_or_output_file_specified(self): self.cmd.locale = 'en_US' self.cmd.input_file = 'dummy' - self.assertRaises(OptionError, self.cmd.finalize_options) + with pytest.raises(OptionError): + self.cmd.finalize_options() def test_no_directory_or_input_file_specified(self): self.cmd.locale = 'en_US' self.cmd.output_file = 'dummy' - self.assertRaises(OptionError, self.cmd.finalize_options) + with pytest.raises(OptionError): + self.cmd.finalize_options() class ExtractMessagesTestCase(unittest.TestCase): @@ -95,21 +97,25 @@ def assert_pot_file_exists(self): def test_neither_default_nor_custom_keywords(self): self.cmd.output_file = 'dummy' self.cmd.no_default_keywords = True - self.assertRaises(OptionError, self.cmd.finalize_options) + with pytest.raises(OptionError): + self.cmd.finalize_options() def test_no_output_file_specified(self): - self.assertRaises(OptionError, self.cmd.finalize_options) + with pytest.raises(OptionError): + self.cmd.finalize_options() def test_both_sort_output_and_sort_by_file(self): self.cmd.output_file = 'dummy' self.cmd.sort_output = True self.cmd.sort_by_file = True - self.assertRaises(OptionError, self.cmd.finalize_options) + with pytest.raises(OptionError): + self.cmd.finalize_options() def test_invalid_file_or_dir_input_path(self): self.cmd.input_paths = 'nonexistent_path' self.cmd.output_file = 'dummy' - self.assertRaises(OptionError, self.cmd.finalize_options) + with pytest.raises(OptionError): + self.cmd.finalize_options() def test_input_paths_is_treated_as_list(self): self.cmd.input_paths = data_dir @@ -120,15 +126,14 @@ def test_input_paths_is_treated_as_list(self): with open(pot_file) as f: catalog = read_po(f) msg = catalog.get('bar') - self.assertEqual(1, len(msg.locations)) - self.assertTrue('file1.py' in msg.locations[0][0]) + assert len(msg.locations) == 1 + assert ('file1.py' in msg.locations[0][0]) def test_input_paths_handle_spaces_after_comma(self): self.cmd.input_paths = '%s, %s' % (this_dir, data_dir) self.cmd.output_file = pot_file self.cmd.finalize_options() - - self.assertEqual([this_dir, data_dir], self.cmd.input_paths) + assert self.cmd.input_paths == [this_dir, data_dir] def test_input_dirs_is_alias_for_input_paths(self): self.cmd.input_dirs = this_dir @@ -141,7 +146,8 @@ def test_input_dirs_is_mutually_exclusive_with_input_paths(self): self.cmd.input_dirs = this_dir self.cmd.input_paths = this_dir self.cmd.output_file = pot_file - self.assertRaises(OptionError, self.cmd.finalize_options) + with pytest.raises(OptionError): + self.cmd.finalize_options() @freeze_time("1994-11-11") def test_extraction_with_default_mapping(self): @@ -199,7 +205,7 @@ def test_extraction_with_default_mapping(self): tzinfo=LOCALTZ, locale='en')} with open(pot_file) as f: actual_content = f.read() - self.assertEqual(expected_content, actual_content) + assert expected_content == actual_content @freeze_time("1994-11-11") def test_extraction_with_mapping_file(self): @@ -252,7 +258,7 @@ def test_extraction_with_mapping_file(self): tzinfo=LOCALTZ, locale='en')} with open(pot_file) as f: actual_content = f.read() - self.assertEqual(expected_content, actual_content) + assert expected_content == actual_content @freeze_time("1994-11-11") def test_extraction_with_mapping_dict(self): @@ -310,7 +316,7 @@ def test_extraction_with_mapping_dict(self): tzinfo=LOCALTZ, locale='en')} with open(pot_file) as f: actual_content = f.read() - self.assertEqual(expected_content, actual_content) + assert expected_content == actual_content def test_extraction_add_location_file(self): self.dist.message_extractors = { @@ -341,7 +347,7 @@ def test_extraction_add_location_file(self): """ with open(pot_file) as f: actual_content = f.read() - self.assertEqual(expected_content, actual_content) + assert expected_content == actual_content class InitCatalogTestCase(unittest.TestCase): @@ -369,12 +375,14 @@ def tearDown(self): def test_no_input_file(self): self.cmd.locale = 'en_US' self.cmd.output_file = 'dummy' - self.assertRaises(OptionError, self.cmd.finalize_options) + with pytest.raises(OptionError): + self.cmd.finalize_options() def test_no_locale(self): self.cmd.input_file = 'dummy' self.cmd.output_file = 'dummy' - self.assertRaises(OptionError, self.cmd.finalize_options) + with pytest.raises(OptionError): + self.cmd.finalize_options() @freeze_time("1994-11-11") def test_with_output_dir(self): @@ -426,7 +434,7 @@ def test_with_output_dir(self): tzinfo=LOCALTZ, locale='en')} with open(po_file) as f: actual_content = f.read() - self.assertEqual(expected_content, actual_content) + assert expected_content == actual_content @freeze_time("1994-11-11") def test_keeps_catalog_non_fuzzy(self): @@ -478,7 +486,7 @@ def test_keeps_catalog_non_fuzzy(self): tzinfo=LOCALTZ, locale='en')} with open(po_file) as f: actual_content = f.read() - self.assertEqual(expected_content, actual_content) + assert expected_content == actual_content @freeze_time("1994-11-11") def test_correct_init_more_than_2_plurals(self): @@ -532,7 +540,7 @@ def test_correct_init_more_than_2_plurals(self): tzinfo=LOCALTZ, locale='en')} with open(po_file) as f: actual_content = f.read() - self.assertEqual(expected_content, actual_content) + assert expected_content == actual_content @freeze_time("1994-11-11") def test_correct_init_singular_plural_forms(self): @@ -583,7 +591,7 @@ def test_correct_init_singular_plural_forms(self): tzinfo=LOCALTZ, locale='ja_JP')} with open(po_file) as f: actual_content = f.read() - self.assertEqual(expected_content, actual_content) + assert expected_content == actual_content @freeze_time("1994-11-11") def test_supports_no_wrap(self): @@ -644,7 +652,7 @@ def test_supports_no_wrap(self): 'long_message': long_message} with open(po_file) as f: actual_content = f.read() - self.assertEqual(expected_content, actual_content) + assert expected_content == actual_content @freeze_time("1994-11-11") def test_supports_width(self): @@ -704,7 +712,7 @@ def test_supports_width(self): 'long_message': long_message} with open(po_file) as f: actual_content = f.read() - self.assertEqual(expected_content, actual_content) + assert expected_content == actual_content class CommandLineInterfaceTestCase(unittest.TestCase): @@ -748,12 +756,12 @@ def test_usage(self): self.cli.run(sys.argv) self.fail('Expected SystemExit') except SystemExit as e: - self.assertEqual(2, e.code) - self.assertEqual("""\ + assert e.code == 2 + assert sys.stderr.getvalue().lower() == """\ usage: pybabel command [options] [args] pybabel: error: no valid command or option passed. try the -h/--help option for more information. -""", sys.stderr.getvalue().lower()) +""" def test_list_locales(self): """ @@ -781,7 +789,7 @@ def test_no_duplicated_output_for_multiple_runs(self): # in case the log message is not duplicated we should get the same # output as before - self.assertEqual(first_output, second_output) + assert first_output == second_output def test_frontend_can_log_to_predefined_handler(self): custom_stream = StringIO() @@ -789,32 +797,19 @@ def test_frontend_can_log_to_predefined_handler(self): log.addHandler(logging.StreamHandler(custom_stream)) self._run_init_catalog() - self.assertNotEqual(id(sys.stderr), id(custom_stream)) - self.assertEqual('', sys.stderr.getvalue()) - assert len(custom_stream.getvalue()) > 0 + assert id(sys.stderr) != id(custom_stream) + assert not sys.stderr.getvalue() + assert custom_stream.getvalue() def test_help(self): try: self.cli.run(sys.argv + ['--help']) self.fail('Expected SystemExit') except SystemExit as e: - self.assertEqual(0, e.code) - self.assertEqual("""\ -usage: pybabel command [options] [args] - -options: - --version show program's version number and exit - -h, --help show this help message and exit - --list-locales print all known locales and exit - -v, --verbose print as much as possible - -q, --quiet print as little as possible - -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 -""", sys.stdout.getvalue().lower()) + assert not e.code + content = sys.stdout.getvalue().lower() + assert 'options:' in content + assert all(command in content for command in ('init', 'update', 'compile', 'extract')) def assert_pot_file_exists(self): assert os.path.isfile(pot_file) @@ -872,7 +867,7 @@ def test_extract_with_default_mapping(self): tzinfo=LOCALTZ, locale='en')} with open(pot_file) as f: actual_content = f.read() - self.assertEqual(expected_content, actual_content) + assert expected_content == actual_content @freeze_time("1994-11-11") def test_extract_with_mapping_file(self): @@ -922,7 +917,7 @@ def test_extract_with_mapping_file(self): tzinfo=LOCALTZ, locale='en')} with open(pot_file) as f: actual_content = f.read() - self.assertEqual(expected_content, actual_content) + assert expected_content == actual_content @freeze_time("1994-11-11") def test_extract_with_exact_file(self): @@ -970,7 +965,7 @@ def test_extract_with_exact_file(self): tzinfo=LOCALTZ, locale='en')} with open(pot_file) as f: actual_content = f.read() - self.assertEqual(expected_content, actual_content) + assert expected_content == actual_content @freeze_time("1994-11-11") def test_init_with_output_dir(self): @@ -1018,7 +1013,7 @@ def test_init_with_output_dir(self): tzinfo=LOCALTZ, locale='en')} with open(po_file) as f: actual_content = f.read() - self.assertEqual(expected_content, actual_content) + assert expected_content == actual_content @freeze_time("1994-11-11") def test_init_singular_plural_forms(self): @@ -1065,7 +1060,7 @@ def test_init_singular_plural_forms(self): tzinfo=LOCALTZ, locale='en')} with open(po_file) as f: actual_content = f.read() - self.assertEqual(expected_content, actual_content) + assert expected_content == actual_content @freeze_time("1994-11-11") def test_init_more_than_2_plural_forms(self): @@ -1115,7 +1110,7 @@ def test_init_more_than_2_plural_forms(self): tzinfo=LOCALTZ, locale='en')} with open(po_file) as f: actual_content = f.read() - self.assertEqual(expected_content, actual_content) + assert expected_content == actual_content def test_compile_catalog(self): po_file = _po_file('de_DE') @@ -1124,9 +1119,7 @@ def test_compile_catalog(self): '--locale', 'de_DE', '-d', i18n_dir]) assert not os.path.isfile(mo_file), 'Expected no file at %r' % mo_file - self.assertEqual("""\ -catalog %s is marked as fuzzy, skipping -""" % po_file, sys.stderr.getvalue()) + assert sys.stderr.getvalue() == f'catalog {po_file} is marked as fuzzy, skipping\n' def test_compile_fuzzy_catalog(self): po_file = _po_file('de_DE') @@ -1136,9 +1129,7 @@ def test_compile_fuzzy_catalog(self): '--locale', 'de_DE', '--use-fuzzy', '-d', i18n_dir]) assert os.path.isfile(mo_file) - self.assertEqual("""\ -compiling catalog %s to %s -""" % (po_file, mo_file), sys.stderr.getvalue()) + assert sys.stderr.getvalue() == f'compiling catalog {po_file} to {mo_file}\n' finally: if os.path.isfile(mo_file): os.unlink(mo_file) @@ -1151,9 +1142,7 @@ def test_compile_catalog_with_more_than_2_plural_forms(self): '--locale', 'ru_RU', '--use-fuzzy', '-d', i18n_dir]) assert os.path.isfile(mo_file) - self.assertEqual("""\ -compiling catalog %s to %s -""" % (po_file, mo_file), sys.stderr.getvalue()) + assert sys.stderr.getvalue() == f'compiling catalog {po_file} to {mo_file}\n' finally: if os.path.isfile(mo_file): os.unlink(mo_file) @@ -1169,10 +1158,10 @@ def test_compile_catalog_multidomain(self): '-d', i18n_dir]) for mo_file in [mo_foo, mo_bar]: assert os.path.isfile(mo_file) - self.assertEqual("""\ -compiling catalog %s to %s -compiling catalog %s to %s -""" % (po_foo, mo_foo, po_bar, mo_bar), sys.stderr.getvalue()) + assert sys.stderr.getvalue() == ( + f'compiling catalog {po_foo} to {mo_foo}\n' + f'compiling catalog {po_bar} to {mo_bar}\n' + ) finally: for mo_file in [mo_foo, mo_bar]: @@ -1246,7 +1235,7 @@ def test_check(self): with open(tmpl_file, "wb") as outfp: write_po(outfp, template) - with self.assertRaises(BaseError): + with pytest.raises(BaseError): self.cli.run(sys.argv + ['update', '--check', '-l', 'fi_FI', @@ -1264,7 +1253,7 @@ def test_check(self): with open(tmpl_file, "wb") as outfp: write_po(outfp, template) - with self.assertRaises(BaseError): + with pytest.raises(BaseError): self.cli.run(sys.argv + ['update', '--check', '-l', 'fi_FI', diff --git a/tests/messages/test_mofile.py b/tests/messages/test_mofile.py index bf6ef5eb0..6e026a846 100644 --- a/tests/messages/test_mofile.py +++ b/tests/messages/test_mofile.py @@ -28,12 +28,11 @@ def test_basics(self): 'LC_MESSAGES', 'messages.mo') with open(mo_path, 'rb') as mo_file: catalog = mofile.read_mo(mo_file) - self.assertEqual(2, len(catalog)) - self.assertEqual('TestProject', catalog.project) - self.assertEqual('0.1', catalog.version) - self.assertEqual('Stange', catalog['bar'].string) - self.assertEqual(['Fuhstange', 'Fuhstangen'], - catalog['foobar'].string) + assert len(catalog) == 2 + assert catalog.project == 'TestProject' + assert catalog.version == '0.1' + assert catalog['bar'].string == 'Stange' + assert catalog['foobar'].string == ['Fuhstange', 'Fuhstangen'] class WriteMoTestCase(unittest.TestCase): @@ -54,16 +53,11 @@ def test_sorting(self): mofile.write_mo(buf, catalog) buf.seek(0) translations = Translations(fp=buf) - self.assertEqual(u'Voh', translations.ugettext('foo')) - assert isinstance(translations.ugettext('foo'), str) - self.assertEqual(u'Es gibt', translations.ungettext('There is', 'There are', 1)) - assert isinstance(translations.ungettext('There is', 'There are', 1), str) - self.assertEqual(u'Fizz', translations.ugettext('Fizz')) - assert isinstance(translations.ugettext('Fizz'), str) - self.assertEqual(u'Fuzz', translations.ugettext('Fuzz')) - assert isinstance(translations.ugettext('Fuzz'), str) - self.assertEqual(u'Fuzzes', translations.ugettext('Fuzzes')) - assert isinstance(translations.ugettext('Fuzzes'), str) + assert translations.ugettext('foo') == 'Voh' + assert translations.ungettext('There is', 'There are', 1) == 'Es gibt' + assert translations.ugettext('Fizz') == 'Fizz' + assert translations.ugettext('Fuzz') == 'Fuzz' + assert translations.ugettext('Fuzzes') == 'Fuzzes' def test_more_plural_forms(self): catalog2 = Catalog(locale='ru_RU') @@ -92,4 +86,4 @@ def test_empty_translation_with_fallback(self): translations = Translations(fp=buf1) translations.add_fallback(Translations(fp=buf2)) - self.assertEqual(u'Flou', translations.ugettext('Fuzz')) + assert translations.ugettext('Fuzz') == 'Flou' diff --git a/tests/messages/test_pofile.py b/tests/messages/test_pofile.py index 632efe7b6..73a7b0ebb 100644 --- a/tests/messages/test_pofile.py +++ b/tests/messages/test_pofile.py @@ -13,6 +13,7 @@ from datetime import datetime import unittest from io import BytesIO, StringIO +import pytest from babel.core import Locale from babel.messages.catalog import Catalog, Message @@ -25,7 +26,7 @@ def test_preserve_locale(self): buf = StringIO(r'''msgid "foo" msgstr "Voh"''') catalog = pofile.read_po(buf, locale='en_US') - self.assertEqual(Locale('en', 'US'), catalog.locale) + assert Locale('en', 'US') == catalog.locale def test_locale_gets_overridden_by_file(self): buf = StringIO(r''' @@ -33,19 +34,19 @@ def test_locale_gets_overridden_by_file(self): msgstr "" "Language: en_US\n"''') catalog = pofile.read_po(buf, locale='de') - self.assertEqual(Locale('en', 'US'), catalog.locale) + assert Locale('en', 'US') == catalog.locale buf = StringIO(r''' msgid "" msgstr "" "Language: ko-KR\n"''') catalog = pofile.read_po(buf, locale='de') - self.assertEqual(Locale('ko', 'KR'), catalog.locale) + assert Locale('ko', 'KR') == catalog.locale def test_preserve_domain(self): buf = StringIO(r'''msgid "foo" msgstr "Voh"''') catalog = pofile.read_po(buf, domain='mydomain') - self.assertEqual('mydomain', catalog.domain) + assert catalog.domain == 'mydomain' def test_applies_specified_encoding_during_read(self): buf = BytesIO(u''' @@ -66,7 +67,7 @@ def test_applies_specified_encoding_during_read(self): msgid "foo" msgstr "bär"'''.encode('iso-8859-1')) catalog = pofile.read_po(buf, locale='de_DE') - self.assertEqual(u'bär', catalog.get('foo').string) + assert catalog.get('foo').string == 'bär' def test_read_multiline(self): buf = StringIO(r'''msgid "" @@ -76,11 +77,12 @@ def test_read_multiline(self): "loop\n" msgstr ""''') catalog = pofile.read_po(buf) - self.assertEqual(1, len(catalog)) + assert len(catalog) == 1 message = list(catalog)[1] - self.assertEqual("Here's some text that\nincludesareallylongwordthat" - "mightbutshouldnt throw us into an infinite loop\n", - message.id) + assert message.id == ( + "Here's some text that\nincludesareallylongwordthat" + "mightbutshouldnt throw us into an infinite loop\n" + ) def test_fuzzy_header(self): buf = StringIO(r''' @@ -93,8 +95,8 @@ def test_fuzzy_header(self): #, fuzzy ''') catalog = pofile.read_po(buf) - self.assertEqual(1, len(list(catalog))) - self.assertEqual(True, list(catalog)[0].fuzzy) + assert len(list(catalog)) == 1 + assert list(catalog)[0].fuzzy def test_not_fuzzy_header(self): buf = StringIO(r''' @@ -106,8 +108,8 @@ def test_not_fuzzy_header(self): # ''') catalog = pofile.read_po(buf) - self.assertEqual(1, len(list(catalog))) - self.assertEqual(False, list(catalog)[0].fuzzy) + assert len(list(catalog)) == 1 + assert not list(catalog)[0].fuzzy def test_header_entry(self): buf = StringIO(r''' @@ -133,18 +135,15 @@ def test_header_entry(self): "Generated-By: Babel 1.0dev-r313\n" ''') catalog = pofile.read_po(buf) - self.assertEqual(1, len(list(catalog))) - self.assertEqual(u'3.15', catalog.version) - self.assertEqual(u'Fliegender Zirkus ', - catalog.msgid_bugs_address) - self.assertEqual(datetime(2007, 9, 27, 11, 19, - tzinfo=FixedOffsetTimezone(7 * 60)), - catalog.creation_date) - self.assertEqual(u'John ', catalog.last_translator) - self.assertEqual(Locale('de'), catalog.locale) - self.assertEqual(u'German Lang ', catalog.language_team) - self.assertEqual(u'iso-8859-2', catalog.charset) - self.assertEqual(True, list(catalog)[0].fuzzy) + assert len(list(catalog)) == 1 + assert catalog.version == '3.15' + assert catalog.msgid_bugs_address == 'Fliegender Zirkus ' + assert datetime(2007, 9, 27, 11, 19, tzinfo=FixedOffsetTimezone(7 * 60)) == catalog.creation_date + assert catalog.last_translator == 'John ' + assert Locale('de') == catalog.locale + assert catalog.language_team == 'German Lang ' + assert catalog.charset == 'iso-8859-2' + assert list(catalog)[0].fuzzy def test_obsolete_message(self): buf = StringIO(r'''# This is an obsolete message @@ -157,12 +156,12 @@ def test_obsolete_message(self): msgstr "Bahr" ''') catalog = pofile.read_po(buf) - self.assertEqual(1, len(catalog)) - self.assertEqual(1, len(catalog.obsolete)) - message = catalog.obsolete[u'foo'] - self.assertEqual(u'foo', message.id) - self.assertEqual(u'Voh', message.string) - self.assertEqual(['This is an obsolete message'], message.user_comments) + assert len(catalog) == 1 + assert len(catalog.obsolete) == 1 + message = catalog.obsolete['foo'] + assert message.id == 'foo' + assert message.string == 'Voh' + assert message.user_comments == ['This is an obsolete message'] def test_obsolete_message_ignored(self): buf = StringIO(r'''# This is an obsolete message @@ -175,8 +174,8 @@ def test_obsolete_message_ignored(self): msgstr "Bahr" ''') catalog = pofile.read_po(buf, ignore_obsolete=True) - self.assertEqual(1, len(catalog)) - self.assertEqual(0, len(catalog.obsolete)) + assert len(catalog) == 1 + assert len(catalog.obsolete) == 0 def test_multi_line_obsolete_message(self): buf = StringIO(r'''# This is an obsolete message @@ -193,11 +192,11 @@ def test_multi_line_obsolete_message(self): msgstr "Bahr" ''') catalog = pofile.read_po(buf) - self.assertEqual(1, len(catalog.obsolete)) + assert len(catalog.obsolete) == 1 message = catalog.obsolete[u'foofoo'] - self.assertEqual(u'foofoo', message.id) - self.assertEqual(u'VohVooooh', message.string) - self.assertEqual(['This is an obsolete message'], message.user_comments) + assert message.id == 'foofoo' + assert message.string == 'VohVooooh' + assert message.user_comments == ['This is an obsolete message'] def test_unit_following_multi_line_obsolete_message(self): buf = StringIO(r'''# This is an obsolete message @@ -214,11 +213,11 @@ def test_unit_following_multi_line_obsolete_message(self): msgstr "Bahr" ''') catalog = pofile.read_po(buf) - self.assertEqual(1, len(catalog)) + assert len(catalog) == 1 message = catalog[u'bar'] - self.assertEqual(u'bar', message.id) - self.assertEqual(u'Bahr', message.string) - self.assertEqual(['This message is not obsolete'], message.user_comments) + assert message.id == 'bar' + assert message.string == 'Bahr' + assert message.user_comments == ['This message is not obsolete'] def test_unit_before_obsolete_is_not_obsoleted(self): buf = StringIO(r''' @@ -236,11 +235,11 @@ def test_unit_before_obsolete_is_not_obsoleted(self): #~ "Vooooh" ''') catalog = pofile.read_po(buf) - self.assertEqual(1, len(catalog)) + assert len(catalog) == 1 message = catalog[u'bar'] - self.assertEqual(u'bar', message.id) - self.assertEqual(u'Bahr', message.string) - self.assertEqual(['This message is not obsolete'], message.user_comments) + assert message.id == 'bar' + assert message.string == 'Bahr' + assert message.user_comments == ['This message is not obsolete'] def test_with_context(self): buf = BytesIO(b'''# Some string in the menu @@ -256,17 +255,16 @@ def test_with_context(self): msgstr "Bahr" ''') catalog = pofile.read_po(buf, ignore_obsolete=True) - self.assertEqual(2, len(catalog)) + assert len(catalog) == 2 message = catalog.get('foo', context='Menu') - self.assertEqual('Menu', message.context) + assert message.context == 'Menu' message = catalog.get('bar', context='Menu') - self.assertEqual('Menu', message.context) + assert message.context == 'Menu' # And verify it pass through write_po out_buf = BytesIO() pofile.write_po(out_buf, catalog, omit_header=True) - assert out_buf.getvalue().strip() == buf.getvalue().strip(), \ - out_buf.getvalue() + assert out_buf.getvalue().strip() == buf.getvalue().strip() def test_obsolete_message_with_context(self): buf = StringIO(''' @@ -285,11 +283,11 @@ def test_obsolete_message_with_context(self): msgstr "Bahr" ''') catalog = pofile.read_po(buf) - self.assertEqual(2, len(catalog)) - self.assertEqual(1, len(catalog.obsolete)) + assert len(catalog) == 2 + assert len(catalog.obsolete) == 1 message = catalog.obsolete[u"foo"] - self.assertEqual(message.context, "other") - self.assertEqual(message.string, "Voh") + assert message.context == 'other' + assert message.string == 'Voh' def test_multiline_context(self): buf = StringIO(''' @@ -300,10 +298,10 @@ def test_multiline_context(self): msgstr "mst" ''') catalog = pofile.read_po(buf) - self.assertEqual(1, len(catalog)) + assert len(catalog) == 1 message = catalog.get('mid', context="a really long message context why?") assert message is not None - self.assertEqual("a really long message context why?", message.context) + assert message.context == 'a really long message context why?' def test_with_context_two(self): buf = BytesIO(b'''msgctxt "Menu" @@ -315,11 +313,11 @@ def test_with_context_two(self): msgstr "Bahr" ''') catalog = pofile.read_po(buf, ignore_obsolete=True) - self.assertEqual(2, len(catalog)) + assert len(catalog) == 2 message = catalog.get('foo', context='Menu') - self.assertEqual('Menu', message.context) + assert message.context == 'Menu' message = catalog.get('bar', context='Mannu') - self.assertEqual('Mannu', message.context) + assert message.context == 'Mannu' # And verify it pass through write_po out_buf = BytesIO() @@ -331,10 +329,10 @@ def test_single_plural_form(self): msgid_plural "foos" msgstr[0] "Voh"''') catalog = pofile.read_po(buf, locale='ja_JP') - self.assertEqual(1, len(catalog)) - self.assertEqual(1, catalog.num_plurals) + assert len(catalog) == 1 + assert catalog.num_plurals == 1 message = catalog['foo'] - self.assertEqual(1, len(message.string)) + assert len(message.string) == 1 def test_singular_plural_form(self): buf = StringIO(r'''msgid "foo" @@ -342,10 +340,10 @@ def test_singular_plural_form(self): msgstr[0] "Voh" msgstr[1] "Vohs"''') catalog = pofile.read_po(buf, locale='nl_NL') - self.assertEqual(1, len(catalog)) - self.assertEqual(2, catalog.num_plurals) + assert len(catalog) == 1 + assert catalog.num_plurals == 2 message = catalog['foo'] - self.assertEqual(2, len(message.string)) + assert len(message.string) == 2 def test_more_than_two_plural_forms(self): buf = StringIO(r'''msgid "foo" @@ -354,11 +352,11 @@ def test_more_than_two_plural_forms(self): msgstr[1] "Vohs" msgstr[2] "Vohss"''') catalog = pofile.read_po(buf, locale='lv_LV') - self.assertEqual(1, len(catalog)) - self.assertEqual(3, catalog.num_plurals) + assert len(catalog) == 1 + assert catalog.num_plurals == 3 message = catalog['foo'] - self.assertEqual(3, len(message.string)) - self.assertEqual(u'Vohss', message.string[2]) + assert len(message.string) == 3 + assert message.string[2] == 'Vohss' def test_plural_with_square_brackets(self): buf = StringIO(r'''msgid "foo" @@ -366,10 +364,10 @@ def test_plural_with_square_brackets(self): msgstr[0] "Voh [text]" msgstr[1] "Vohs [text]"''') catalog = pofile.read_po(buf, locale='nb_NO') - self.assertEqual(1, len(catalog)) - self.assertEqual(2, catalog.num_plurals) + assert len(catalog) == 1 + assert catalog.num_plurals == 2 message = catalog['foo'] - self.assertEqual(2, len(message.string)) + assert len(message.string) == 2 def test_obsolete_plural_with_square_brackets(self): buf = StringIO('''\ @@ -379,13 +377,13 @@ def test_obsolete_plural_with_square_brackets(self): #~ msgstr[1] "Vohs [text]" ''') catalog = pofile.read_po(buf, locale='nb_NO') - self.assertEqual(0, len(catalog)) - self.assertEqual(1, len(catalog.obsolete)) - self.assertEqual(2, catalog.num_plurals) + assert len(catalog) == 0 + assert len(catalog.obsolete) == 1 + assert catalog.num_plurals == 2 message = catalog.obsolete[('foo', 'foos')] - self.assertEqual(2, len(message.string)) - self.assertEqual("Voh [text]", message.string[0]) - self.assertEqual("Vohs [text]", message.string[1]) + assert len(message.string) == 2 + assert message.string[0] == 'Voh [text]' + assert message.string[1] == 'Vohs [text]' def test_missing_plural(self): buf = StringIO('''\ @@ -399,13 +397,13 @@ def test_missing_plural(self): msgstr[1] "Vohs [text]" ''') catalog = pofile.read_po(buf, locale='nb_NO') - self.assertEqual(1, len(catalog)) - self.assertEqual(3, catalog.num_plurals) + assert len(catalog) == 1 + assert catalog.num_plurals == 3 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]) + assert len(message.string) == 3 + assert message.string[0] == 'Voh [text]' + assert message.string[1] == 'Vohs [text]' + assert message.string[2] == '' def test_missing_plural_in_the_middle(self): buf = StringIO('''\ @@ -419,13 +417,13 @@ def test_missing_plural_in_the_middle(self): msgstr[2] "Vohs [text]" ''') catalog = pofile.read_po(buf, locale='nb_NO') - self.assertEqual(1, len(catalog)) - self.assertEqual(3, catalog.num_plurals) + assert len(catalog) == 1 + assert catalog.num_plurals == 3 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]) + assert len(message.string) == 3 + assert message.string[0] == 'Voh [text]' + assert message.string[1] == '' + assert message.string[2] == 'Vohs [text]' def test_abort_invalid_po_file(self): invalid_po = ''' @@ -459,10 +457,8 @@ def test_abort_invalid_po_file(self): # Catalog not created, throws PoFileError buf = StringIO(invalid_po_2) - output = None - with self.assertRaises(pofile.PoFileError) as e: - output = pofile.read_po(buf, locale='fr', abort_invalid=True) - assert not output + with pytest.raises(pofile.PoFileError): + pofile.read_po(buf, locale='fr', abort_invalid=True) # Catalog is created with warning, no abort buf = StringIO(invalid_po_2) @@ -471,17 +467,15 @@ def test_abort_invalid_po_file(self): # Catalog not created, aborted with PoFileError buf = StringIO(invalid_po_2) - output = None - with self.assertRaises(pofile.PoFileError) as e: - output = pofile.read_po(buf, locale='fr', abort_invalid=True) - assert not output + with pytest.raises(pofile.PoFileError): + pofile.read_po(buf, locale='fr', abort_invalid=True) def test_invalid_pofile_with_abort_flag(self): parser = pofile.PoFileParser(None, abort_invalid=True) lineno = 10 line = u'Algo esta mal' msg = 'invalid file' - with self.assertRaises(pofile.PoFileError) as e: + with pytest.raises(pofile.PoFileError): parser._invalid_pofile(line, lineno, msg) @@ -493,9 +487,9 @@ def test_join_locations(self): catalog.add(u'foo', locations=[('utils.py', 3)]) buf = BytesIO() pofile.write_po(buf, catalog, omit_header=True) - self.assertEqual(b'''#: main.py:1 utils.py:3 + assert buf.getvalue().strip() == b'''#: main.py:1 utils.py:3 msgid "foo" -msgstr ""''', buf.getvalue().strip()) +msgstr ""''' def test_write_po_file_with_specified_charset(self): catalog = Catalog(charset='iso-8859-1') @@ -512,9 +506,9 @@ def test_duplicate_comments(self): catalog.add(u'foo', auto_comments=['A comment']) buf = BytesIO() pofile.write_po(buf, catalog, omit_header=True) - self.assertEqual(b'''#. A comment + assert buf.getvalue().strip() == b'''#. A comment msgid "foo" -msgstr ""''', buf.getvalue().strip()) +msgstr ""''' def test_wrap_long_lines(self): text = """Here's some text where @@ -528,14 +522,14 @@ def test_wrap_long_lines(self): buf = BytesIO() pofile.write_po(buf, catalog, no_location=True, omit_header=True, width=42) - self.assertEqual(b'''msgid "" + assert buf.getvalue().strip() == b'''msgid "" "Here's some text where\\n" "white space and line breaks matter, and" " should\\n" "\\n" "not be removed\\n" "\\n" -msgstr ""''', buf.getvalue().strip()) +msgstr ""''' def test_wrap_long_lines_with_long_word(self): text = """Here's some text that @@ -546,12 +540,12 @@ def test_wrap_long_lines_with_long_word(self): buf = BytesIO() pofile.write_po(buf, catalog, no_location=True, omit_header=True, width=32) - self.assertEqual(b'''msgid "" + assert buf.getvalue().strip() == b'''msgid "" "Here's some text that\\n" "includesareallylongwordthatmightbutshouldnt" " throw us into an infinite " "loop\\n" -msgstr ""''', buf.getvalue().strip()) +msgstr ""''' def test_wrap_long_lines_in_header(self): """ @@ -561,14 +555,14 @@ def test_wrap_long_lines_in_header(self): revision_date=datetime(2007, 4, 1)) buf = BytesIO() pofile.write_po(buf, catalog) - self.assertEqual(b'''\ + assert b'\n'.join(buf.getvalue().splitlines()[:7]) == b'''\ # Translations template for AReallyReallyLongNameForAProject. # Copyright (C) 2007 ORGANIZATION # This file is distributed under the same license as the # AReallyReallyLongNameForAProject project. # FIRST AUTHOR , 2007. # -#, fuzzy''', b'\n'.join(buf.getvalue().splitlines()[:7])) +#, fuzzy''' def test_wrap_locations_with_hyphens(self): catalog = Catalog() @@ -580,10 +574,10 @@ def test_wrap_locations_with_hyphens(self): ]) buf = BytesIO() pofile.write_po(buf, catalog, omit_header=True) - self.assertEqual(b'''#: doupy/templates/base/navmenu.inc.html.py:60 + assert buf.getvalue().strip() == b'''#: doupy/templates/base/navmenu.inc.html.py:60 #: doupy/templates/job-offers/helpers.html:22 msgid "foo" -msgstr ""''', buf.getvalue().strip()) +msgstr ""''' def test_no_wrap_and_width_behaviour_on_comments(self): catalog = Catalog() @@ -592,7 +586,7 @@ def test_no_wrap_and_width_behaviour_on_comments(self): locations=[("fake.py", n) for n in range(1, 30)]) buf = BytesIO() pofile.write_po(buf, catalog, width=None, omit_header=True) - self.assertEqual(b"""\ + assert buf.getvalue().lower() == b"""\ #: fake.py:1 fake.py:2 fake.py:3 fake.py:4 fake.py:5 fake.py:6 fake.py:7 #: fake.py:8 fake.py:9 fake.py:10 fake.py:11 fake.py:12 fake.py:13 fake.py:14 #: fake.py:15 fake.py:16 fake.py:17 fake.py:18 fake.py:19 fake.py:20 fake.py:21 @@ -601,10 +595,10 @@ def test_no_wrap_and_width_behaviour_on_comments(self): msgid "pretty dam long message id, which must really be big to test this wrap behaviour, if not it won't work." msgstr "" -""", buf.getvalue().lower()) +""" buf = BytesIO() pofile.write_po(buf, catalog, width=100, omit_header=True) - self.assertEqual(b"""\ + assert buf.getvalue().lower() == b"""\ #: fake.py:1 fake.py:2 fake.py:3 fake.py:4 fake.py:5 fake.py:6 fake.py:7 fake.py:8 fake.py:9 fake.py:10 #: fake.py:11 fake.py:12 fake.py:13 fake.py:14 fake.py:15 fake.py:16 fake.py:17 fake.py:18 fake.py:19 #: fake.py:20 fake.py:21 fake.py:22 fake.py:23 fake.py:24 fake.py:25 fake.py:26 fake.py:27 fake.py:28 @@ -614,7 +608,7 @@ def test_no_wrap_and_width_behaviour_on_comments(self): " work." msgstr "" -""", buf.getvalue().lower()) +""" def test_pot_with_translator_comments(self): catalog = Catalog() @@ -625,7 +619,7 @@ def test_pot_with_translator_comments(self): 'multiple lines.']) buf = BytesIO() pofile.write_po(buf, catalog, omit_header=True) - self.assertEqual(b'''#. Comment About `foo` + assert buf.getvalue().strip() == b'''#. Comment About `foo` #: main.py:1 msgid "foo" msgstr "" @@ -634,7 +628,7 @@ def test_pot_with_translator_comments(self): # multiple lines. #: utils.py:3 msgid "bar" -msgstr ""''', buf.getvalue().strip()) +msgstr ""''' def test_po_with_obsolete_message(self): catalog = Catalog() @@ -644,13 +638,13 @@ def test_po_with_obsolete_message(self): user_comments=['User comment']) buf = BytesIO() pofile.write_po(buf, catalog, omit_header=True) - self.assertEqual(b'''#: main.py:1 + assert buf.getvalue().strip() == b'''#: main.py:1 msgid "foo" msgstr "Voh" # User comment #~ msgid "bar" -#~ msgstr "Bahr"''', buf.getvalue().strip()) +#~ msgstr "Bahr"''' def test_po_with_multiline_obsolete_message(self): catalog = Catalog() @@ -667,7 +661,7 @@ def test_po_with_multiline_obsolete_message(self): locations=[('utils.py', 3)]) buf = BytesIO() pofile.write_po(buf, catalog, omit_header=True) - self.assertEqual(b'''#: main.py:1 + assert buf.getvalue().strip() == b'''#: main.py:1 msgid "foo" msgstr "Voh" @@ -678,7 +672,7 @@ def test_po_with_multiline_obsolete_message(self): #~ msgstr "" #~ "Here's a message that covers\\n" #~ "multiple lines, and should still be handled\\n" -#~ "correctly.\\n"''', buf.getvalue().strip()) +#~ "correctly.\\n"''' def test_po_with_obsolete_message_ignored(self): catalog = Catalog() @@ -688,9 +682,9 @@ def test_po_with_obsolete_message_ignored(self): user_comments=['User comment']) buf = BytesIO() pofile.write_po(buf, catalog, omit_header=True, ignore_obsolete=True) - self.assertEqual(b'''#: main.py:1 + assert buf.getvalue().strip() == b'''#: main.py:1 msgid "foo" -msgstr "Voh"''', buf.getvalue().strip()) +msgstr "Voh"''' def test_po_with_previous_msgid(self): catalog = Catalog() @@ -698,10 +692,10 @@ def test_po_with_previous_msgid(self): previous_id=u'fo') buf = BytesIO() pofile.write_po(buf, catalog, omit_header=True, include_previous=True) - self.assertEqual(b'''#: main.py:1 + assert buf.getvalue().strip() == b'''#: main.py:1 #| msgid "fo" msgid "foo" -msgstr "Voh"''', buf.getvalue().strip()) +msgstr "Voh"''' def test_po_with_previous_msgid_plural(self): catalog = Catalog() @@ -709,13 +703,13 @@ def test_po_with_previous_msgid_plural(self): locations=[('main.py', 1)], previous_id=(u'fo', u'fos')) buf = BytesIO() pofile.write_po(buf, catalog, omit_header=True, include_previous=True) - self.assertEqual(b'''#: main.py:1 + assert buf.getvalue().strip() == b'''#: main.py:1 #| msgid "fo" #| msgid_plural "fos" msgid "foo" msgid_plural "foos" msgstr[0] "Voh" -msgstr[1] "Voeh"''', buf.getvalue().strip()) +msgstr[1] "Voeh"''' def test_sorted_po(self): catalog = Catalog() @@ -810,8 +804,8 @@ def test_silent_location_fallback(self): msgid "broken line number" msgstr ""''') catalog = pofile.read_po(buf) - self.assertEqual(catalog['missing line number'].locations, [(u'broken_file.py', None)]) - self.assertEqual(catalog['broken line number'].locations, []) + assert catalog['missing line number'].locations == [('broken_file.py', None)] + assert catalog['broken line number'].locations == [] def test_include_lineno(self): catalog = Catalog() @@ -819,9 +813,9 @@ def test_include_lineno(self): catalog.add(u'foo', locations=[('utils.py', 3)]) buf = BytesIO() pofile.write_po(buf, catalog, omit_header=True, include_lineno=True) - self.assertEqual(b'''#: main.py:1 utils.py:3 + assert buf.getvalue().strip() == b'''#: main.py:1 utils.py:3 msgid "foo" -msgstr ""''', buf.getvalue().strip()) +msgstr ""''' def test_no_include_lineno(self): catalog = Catalog() @@ -830,9 +824,9 @@ def test_no_include_lineno(self): catalog.add(u'foo', locations=[('utils.py', 3)]) buf = BytesIO() pofile.write_po(buf, catalog, omit_header=True, include_lineno=False) - self.assertEqual(b'''#: main.py utils.py + assert buf.getvalue().strip() == b'''#: main.py utils.py msgid "foo" -msgstr ""''', buf.getvalue().strip()) +msgstr ""''' class PofileFunctionsTestCase(unittest.TestCase): @@ -840,12 +834,12 @@ class PofileFunctionsTestCase(unittest.TestCase): def test_unescape(self): escaped = u'"Say:\\n \\"hello, world!\\"\\n"' unescaped = u'Say:\n "hello, world!"\n' - self.assertNotEqual(unescaped, escaped) - self.assertEqual(unescaped, pofile.unescape(escaped)) + assert unescaped != escaped + assert unescaped == pofile.unescape(escaped) def test_unescape_of_quoted_newline(self): # regression test for #198 - self.assertEqual(r'\n', pofile.unescape(r'"\\n"')) + assert pofile.unescape(r'"\\n"') == '\\n' def test_denormalize_on_msgstr_without_empty_first_line(self): # handle irregular multi-line msgstr (no "" as first line) @@ -853,9 +847,8 @@ def test_denormalize_on_msgstr_without_empty_first_line(self): msgstr = '"multi-line\\n"\n" translation"' expected_denormalized = u'multi-line\n translation' - self.assertEqual(expected_denormalized, pofile.denormalize(msgstr)) - self.assertEqual(expected_denormalized, - pofile.denormalize('""\n' + msgstr)) + assert expected_denormalized == pofile.denormalize(msgstr) + assert expected_denormalized == pofile.denormalize('""\n' + msgstr) def test_unknown_language_roundtrip(): diff --git a/tests/test_dates.py b/tests/test_dates.py index a84fac9b3..227813b23 100644 --- a/tests/test_dates.py +++ b/tests/test_dates.py @@ -46,253 +46,207 @@ class DateTimeFormatTestCase(unittest.TestCase): def test_quarter_format(self): d = date(2006, 6, 8) fmt = dates.DateTimeFormat(d, locale='en_US') - self.assertEqual('2', fmt['Q']) - self.assertEqual('2nd quarter', fmt['QQQQ']) - self.assertEqual('2', fmt['q']) - self.assertEqual('2nd quarter', fmt['qqqq']) + assert fmt['Q'] == '2' + assert fmt['QQQQ'] == '2nd quarter' + assert fmt['q'] == '2' + assert fmt['qqqq'] == '2nd quarter' d = date(2006, 12, 31) fmt = dates.DateTimeFormat(d, locale='en_US') - self.assertEqual('Q4', fmt['qqq']) - self.assertEqual('4', fmt['qqqqq']) - self.assertEqual('Q4', fmt['QQQ']) - self.assertEqual('4', fmt['QQQQQ']) + assert fmt['qqq'] == 'Q4' + assert fmt['qqqqq'] == '4' + assert fmt['QQQ'] == 'Q4' + assert fmt['QQQQQ'] == '4' 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 - fmt = dates.DateTimeFormat(d, locale='mt_MT') - self.assertEqual(u'Fr', fmt['LLLLL']) # narrow standalone + assert dates.DateTimeFormat(d, locale='mt_MT')['MMMMM'] == 'F' # narrow format + assert dates.DateTimeFormat(d, locale='mt_MT')['LLLLL'] == 'Fr' # narrow standalone def test_abbreviated_month_alias(self): d = date(2006, 3, 8) - fmt = dates.DateTimeFormat(d, locale='de_DE') - self.assertEqual(u'Mär', fmt['LLL']) + assert dates.DateTimeFormat(d, locale='de_DE')['LLL'] == 'Mär' def test_week_of_year_first(self): d = date(2006, 1, 8) - fmt = dates.DateTimeFormat(d, locale='de_DE') - self.assertEqual('1', fmt['w']) - fmt = dates.DateTimeFormat(d, locale='en_US') - self.assertEqual('02', fmt['ww']) + assert dates.DateTimeFormat(d, locale='de_DE')['w'] == '1' + assert dates.DateTimeFormat(d, locale='en_US')['ww'] == '02' def test_week_of_year_first_with_year(self): d = date(2006, 1, 1) fmt = dates.DateTimeFormat(d, locale='de_DE') - self.assertEqual('52', fmt['w']) - self.assertEqual('2005', fmt['YYYY']) + assert fmt['w'] == '52' + assert fmt['YYYY'] == '2005' def test_week_of_year_last(self): d = date(2006, 12, 26) - fmt = dates.DateTimeFormat(d, locale='de_DE') - self.assertEqual('52', fmt['w']) - fmt = dates.DateTimeFormat(d, locale='en_US') - self.assertEqual('52', fmt['w']) + assert dates.DateTimeFormat(d, locale='de_DE')['w'] == '52' + assert dates.DateTimeFormat(d, locale='en_US')['w'] == '52' def test_week_of_year_last_us_extra_week(self): d = date(2005, 12, 26) - fmt = dates.DateTimeFormat(d, locale='de_DE') - self.assertEqual('52', fmt['w']) - fmt = dates.DateTimeFormat(d, locale='en_US') - self.assertEqual('53', fmt['w']) + assert dates.DateTimeFormat(d, locale='de_DE')['w'] == '52' + assert dates.DateTimeFormat(d, locale='en_US')['w'] == '53' def test_week_of_year_de_first_us_last_with_year(self): d = date(2018,12,31) fmt = dates.DateTimeFormat(d, locale='de_DE') - self.assertEqual('1', fmt['w']) - self.assertEqual('2019', fmt['YYYY']) + assert fmt['w'] == '1' + assert fmt['YYYY'] == '2019' fmt = dates.DateTimeFormat(d, locale='en_US') - self.assertEqual('53', fmt['w']) - self.assertEqual('2018',fmt['yyyy']) + assert fmt['w'] == '53' + assert fmt['yyyy'] == '2018' def test_week_of_month_first(self): d = date(2006, 1, 8) - fmt = dates.DateTimeFormat(d, locale='de_DE') - self.assertEqual('1', fmt['W']) - fmt = dates.DateTimeFormat(d, locale='en_US') - self.assertEqual('2', fmt['W']) + assert dates.DateTimeFormat(d, locale='de_DE')['W'] == '1' + assert dates.DateTimeFormat(d, locale='en_US')['W'] == '2' def test_week_of_month_last(self): d = date(2006, 1, 29) - fmt = dates.DateTimeFormat(d, locale='de_DE') - self.assertEqual('4', fmt['W']) - fmt = dates.DateTimeFormat(d, locale='en_US') - self.assertEqual('5', fmt['W']) + assert dates.DateTimeFormat(d, locale='de_DE')['W'] == '4' + assert dates.DateTimeFormat(d, locale='en_US')['W'] == '5' def test_day_of_year(self): d = date(2007, 4, 1) - fmt = dates.DateTimeFormat(d, locale='en_US') - self.assertEqual('91', fmt['D']) + assert dates.DateTimeFormat(d, locale='en_US')['D'] == '91' def test_day_of_year_works_with_datetime(self): d = datetime(2007, 4, 1) - fmt = dates.DateTimeFormat(d, locale='en_US') - self.assertEqual('91', fmt['D']) + assert dates.DateTimeFormat(d, locale='en_US')['D'] == '91' def test_day_of_year_first(self): d = date(2007, 1, 1) - fmt = dates.DateTimeFormat(d, locale='en_US') - self.assertEqual('001', fmt['DDD']) + assert dates.DateTimeFormat(d, locale='en_US')['DDD'] == '001' def test_day_of_year_last(self): d = date(2007, 12, 31) - fmt = dates.DateTimeFormat(d, locale='en_US') - self.assertEqual('365', fmt['DDD']) + assert dates.DateTimeFormat(d, locale='en_US')['DDD'] == '365' def test_day_of_week_in_month(self): d = date(2007, 4, 15) - fmt = dates.DateTimeFormat(d, locale='en_US') - self.assertEqual('3', fmt['F']) + assert dates.DateTimeFormat(d, locale='en_US')['F'] == '3' def test_day_of_week_in_month_first(self): d = date(2007, 4, 1) - fmt = dates.DateTimeFormat(d, locale='en_US') - self.assertEqual('1', fmt['F']) + assert dates.DateTimeFormat(d, locale='en_US')['F'] == '1' def test_day_of_week_in_month_last(self): d = date(2007, 4, 29) - fmt = dates.DateTimeFormat(d, locale='en_US') - self.assertEqual('5', fmt['F']) + assert dates.DateTimeFormat(d, locale='en_US')['F'] == '5' def test_local_day_of_week(self): 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 - fmt = dates.DateTimeFormat(d, locale='en_US') - self.assertEqual('01', fmt['ee']) # sunday is first day of week - fmt = dates.DateTimeFormat(d, locale='ar_BH') - self.assertEqual('02', fmt['ee']) # saturday is first day of week + assert dates.DateTimeFormat(d, locale='de_DE')['e'] == '7' # monday is first day of week + assert dates.DateTimeFormat(d, locale='en_US')['ee'] == '01' # sunday is first day of week + assert dates.DateTimeFormat(d, locale='ar_BH')['ee'] == '02' # saturday is first day of week 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 - fmt = dates.DateTimeFormat(d, locale='en_US') - self.assertEqual('02', fmt['ee']) # sunday is first day of week - fmt = dates.DateTimeFormat(d, locale='ar_BH') - self.assertEqual('03', fmt['ee']) # saturday is first day of week + assert dates.DateTimeFormat(d, locale='de_DE')['e'] == '1' # monday is first day of week + assert dates.DateTimeFormat(d, locale='en_US')['ee'] == '02' # sunday is first day of week + assert dates.DateTimeFormat(d, locale='ar_BH')['ee'] == '03' # saturday is first day of week def test_local_day_of_week_standalone(self): 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 - fmt = dates.DateTimeFormat(d, locale='en_US') - self.assertEqual('1', fmt['c']) # sunday is first day of week - fmt = dates.DateTimeFormat(d, locale='ar_BH') - self.assertEqual('2', fmt['c']) # saturday is first day of week + assert dates.DateTimeFormat(d, locale='de_DE')['c'] == '7' # monday is first day of week + assert dates.DateTimeFormat(d, locale='en_US')['c'] == '1' # sunday is first day of week + assert dates.DateTimeFormat(d, locale='ar_BH')['c'] == '2' # saturday is first day of week 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 - fmt = dates.DateTimeFormat(d, locale='en_US') - self.assertEqual('2', fmt['c']) # sunday is first day of week - fmt = dates.DateTimeFormat(d, locale='ar_BH') - self.assertEqual('3', fmt['c']) # saturday is first day of week + assert dates.DateTimeFormat(d, locale='de_DE')['c'] == '1' # monday is first day of week + assert dates.DateTimeFormat(d, locale='en_US')['c'] == '2' # sunday is first day of week + assert dates.DateTimeFormat(d, locale='ar_BH')['c'] == '3' # saturday is first day of week def test_pattern_day_of_week(self): dt = datetime(2016, 2, 6) fmt = dates.DateTimeFormat(dt, locale='en_US') - self.assertEqual('7', fmt['c']) - self.assertEqual('Sat', fmt['ccc']) - self.assertEqual('Saturday', fmt['cccc']) - self.assertEqual('S', fmt['ccccc']) - self.assertEqual('Sa', fmt['cccccc']) - self.assertEqual('7', fmt['e']) - self.assertEqual('07', fmt['ee']) - self.assertEqual('Sat', fmt['eee']) - self.assertEqual('Saturday', fmt['eeee']) - self.assertEqual('S', fmt['eeeee']) - self.assertEqual('Sa', fmt['eeeeee']) - self.assertEqual('Sat', fmt['E']) - self.assertEqual('Sat', fmt['EE']) - self.assertEqual('Sat', fmt['EEE']) - self.assertEqual('Saturday', fmt['EEEE']) - self.assertEqual('S', fmt['EEEEE']) - self.assertEqual('Sa', fmt['EEEEEE']) + assert fmt['c'] == '7' + assert fmt['ccc'] == 'Sat' + assert fmt['cccc'] == 'Saturday' + assert fmt['ccccc'] == 'S' + assert fmt['cccccc'] == 'Sa' + assert fmt['e'] == '7' + assert fmt['ee'] == '07' + assert fmt['eee'] == 'Sat' + assert fmt['eeee'] == 'Saturday' + assert fmt['eeeee'] == 'S' + assert fmt['eeeeee'] == 'Sa' + assert fmt['E'] == 'Sat' + assert fmt['EE'] == 'Sat' + assert fmt['EEE'] == 'Sat' + assert fmt['EEEE'] == 'Saturday' + assert fmt['EEEEE'] == 'S' + assert fmt['EEEEEE'] == 'Sa' fmt = dates.DateTimeFormat(dt, locale='uk') - self.assertEqual('6', fmt['c']) - self.assertEqual('6', fmt['e']) - self.assertEqual('06', fmt['ee']) + assert fmt['c'] == '6' + assert fmt['e'] == '6' + assert fmt['ee'] == '06' def test_fractional_seconds(self): t = time(8, 3, 9, 799) - fmt = dates.DateTimeFormat(t, locale='en_US') - self.assertEqual('0', fmt['S']) + assert dates.DateTimeFormat(t, locale='en_US')['S'] == '0' t = time(8, 3, 1, 799) - fmt = dates.DateTimeFormat(t, locale='en_US') - self.assertEqual('0008', fmt['SSSS']) + assert dates.DateTimeFormat(t, locale='en_US')['SSSS'] == '0008' t = time(8, 3, 1, 34567) - fmt = dates.DateTimeFormat(t, locale='en_US') - self.assertEqual('0346', fmt['SSSS']) + assert dates.DateTimeFormat(t, locale='en_US')['SSSS'] == '0346' t = time(8, 3, 1, 345678) - fmt = dates.DateTimeFormat(t, locale='en_US') - self.assertEqual('345678', fmt['SSSSSS']) + assert dates.DateTimeFormat(t, locale='en_US')['SSSSSS'] == '345678' t = time(8, 3, 1, 799) - fmt = dates.DateTimeFormat(t, locale='en_US') - self.assertEqual('00080', fmt['SSSSS']) + assert dates.DateTimeFormat(t, locale='en_US')['SSSSS'] == '00080' def test_fractional_seconds_zero(self): t = time(15, 30, 0) - fmt = dates.DateTimeFormat(t, locale='en_US') - self.assertEqual('0000', fmt['SSSS']) + assert dates.DateTimeFormat(t, locale='en_US')['SSSS'] == '0000' def test_milliseconds_in_day(self): t = time(15, 30, 12, 345000) - fmt = dates.DateTimeFormat(t, locale='en_US') - self.assertEqual('55812345', fmt['AAAA']) + assert dates.DateTimeFormat(t, locale='en_US')['AAAA'] == '55812345' def test_milliseconds_in_day_zero(self): d = time(0, 0, 0) - fmt = dates.DateTimeFormat(d, locale='en_US') - self.assertEqual('0000', fmt['AAAA']) + assert dates.DateTimeFormat(d, locale='en_US')['AAAA'] == '0000' def test_timezone_rfc822(self): tz = timezone('Europe/Berlin') t = tz.localize(datetime(2015, 1, 1, 15, 30)) - fmt = dates.DateTimeFormat(t, locale='de_DE') - self.assertEqual('+0100', fmt['Z']) + assert dates.DateTimeFormat(t, locale='de_DE')['Z'] == '+0100' def test_timezone_gmt(self): tz = timezone('Europe/Berlin') t = tz.localize(datetime(2015, 1, 1, 15, 30)) - fmt = dates.DateTimeFormat(t, locale='de_DE') - self.assertEqual('GMT+01:00', fmt['ZZZZ']) + assert dates.DateTimeFormat(t, locale='de_DE')['ZZZZ'] == 'GMT+01:00' def test_timezone_name(self): tz = timezone('Europe/Paris') dt = tz.localize(datetime(2007, 4, 1, 15, 30)) - fmt = dates.DateTimeFormat(dt, locale='fr_FR') - self.assertEqual('heure : France', fmt['v']) + assert dates.DateTimeFormat(dt, locale='fr_FR')['v'] == 'heure : France' def test_timezone_location_format(self): tz = timezone('Europe/Paris') dt = datetime(2007, 4, 1, 15, 30, tzinfo=tz) - fmt = dates.DateTimeFormat(dt, locale='fr_FR') - self.assertEqual('heure : France', fmt['VVVV']) + assert dates.DateTimeFormat(dt, locale='fr_FR')['VVVV'] == 'heure : France' def test_timezone_walltime_short(self): tz = timezone('Europe/Paris') t = time(15, 30, tzinfo=tz) - fmt = dates.DateTimeFormat(t, locale='fr_FR') - self.assertEqual('heure : France', fmt['v']) + assert dates.DateTimeFormat(t, locale='fr_FR')['v'] == 'heure : France' def test_timezone_walltime_long(self): tz = timezone('Europe/Paris') t = time(15, 30, tzinfo=tz) - fmt = dates.DateTimeFormat(t, locale='fr_FR') - self.assertEqual(u'heure d\u2019Europe centrale', fmt['vvvv']) + assert dates.DateTimeFormat(t, locale='fr_FR')['vvvv'] == u'heure d’Europe centrale' def test_hour_formatting(self): l = 'en_US' t = time(0, 0, 0) - self.assertEqual(dates.format_time(t, 'h a', locale=l), '12 AM') - self.assertEqual(dates.format_time(t, 'H', locale=l), '0') - self.assertEqual(dates.format_time(t, 'k', locale=l), '24') - self.assertEqual(dates.format_time(t, 'K a', locale=l), '0 AM') + assert dates.format_time(t, 'h a', locale=l) == '12 AM' + assert dates.format_time(t, 'H', locale=l) == '0' + assert dates.format_time(t, 'k', locale=l) == '24' + assert dates.format_time(t, 'K a', locale=l) == '0 AM' t = time(12, 0, 0) - self.assertEqual(dates.format_time(t, 'h a', locale=l), '12 PM') - self.assertEqual(dates.format_time(t, 'H', locale=l), '12') - self.assertEqual(dates.format_time(t, 'k', locale=l), '12') - self.assertEqual(dates.format_time(t, 'K a', locale=l), '0 PM') + assert dates.format_time(t, 'h a', locale=l) == '12 PM' + assert dates.format_time(t, 'H', locale=l) == '12' + assert dates.format_time(t, 'k', locale=l) == '12' + assert dates.format_time(t, 'K a', locale=l) == '0 PM' class FormatDateTestCase(unittest.TestCase): @@ -309,7 +263,7 @@ def test_with_time_fields_in_pattern_and_datetime_param(self): 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, 4, 1) - self.assertEqual('14', dates.format_date(d, 'w', locale='en_US')) + assert dates.format_date(d, 'w', locale='en_US') == '14' class FormatDatetimeTestCase(unittest.TestCase): @@ -318,145 +272,94 @@ def test_with_float(self): d = datetime(2012, 4, 1, 15, 30, 29, tzinfo=timezone('UTC')) epoch = float(calendar.timegm(d.timetuple())) formatted_string = dates.format_datetime(epoch, format='long', locale='en_US') - self.assertEqual(u'April 1, 2012 at 3:30:29 PM UTC', formatted_string) + assert formatted_string == u'April 1, 2012 at 3:30:29 PM UTC' - def test_timezone_formats(self): + def test_timezone_formats_los_angeles(self): dt = datetime(2016, 1, 13, 7, 8, 35) tz = dates.get_timezone('America/Los_Angeles') dt = tz.localize(dt) - formatted_string = dates.format_datetime(dt, 'z', locale='en') - self.assertEqual(u'PST', formatted_string) - formatted_string = dates.format_datetime(dt, 'zz', locale='en') - self.assertEqual(u'PST', formatted_string) - formatted_string = dates.format_datetime(dt, 'zzz', locale='en') - self.assertEqual(u'PST', formatted_string) - formatted_string = dates.format_datetime(dt, 'zzzz', locale='en') - self.assertEqual(u'Pacific Standard Time', formatted_string) - formatted_string = dates.format_datetime(dt, 'Z', locale='en') - self.assertEqual(u'-0800', formatted_string) - formatted_string = dates.format_datetime(dt, 'ZZ', locale='en') - self.assertEqual(u'-0800', formatted_string) - formatted_string = dates.format_datetime(dt, 'ZZZ', locale='en') - self.assertEqual(u'-0800', formatted_string) - formatted_string = dates.format_datetime(dt, 'ZZZZ', locale='en') - self.assertEqual(u'GMT-08:00', formatted_string) - formatted_string = dates.format_datetime(dt, 'ZZZZZ', locale='en') - self.assertEqual(u'-08:00', formatted_string) - formatted_string = dates.format_datetime(dt, 'OOOO', locale='en') - self.assertEqual(u'GMT-08:00', formatted_string) - formatted_string = dates.format_datetime(dt, 'VV', locale='en') - self.assertEqual(u'America/Los_Angeles', formatted_string) - formatted_string = dates.format_datetime(dt, 'VVV', locale='en') - self.assertEqual(u'Los Angeles', formatted_string) - formatted_string = dates.format_datetime(dt, 'X', locale='en') - self.assertEqual(u'-08', formatted_string) - formatted_string = dates.format_datetime(dt, 'XX', locale='en') - self.assertEqual(u'-0800', formatted_string) - formatted_string = dates.format_datetime(dt, 'XXX', locale='en') - self.assertEqual(u'-08:00', formatted_string) - formatted_string = dates.format_datetime(dt, 'XXXX', locale='en') - self.assertEqual(u'-0800', formatted_string) - formatted_string = dates.format_datetime(dt, 'XXXXX', locale='en') - self.assertEqual(u'-08:00', formatted_string) - formatted_string = dates.format_datetime(dt, 'x', locale='en') - self.assertEqual(u'-08', formatted_string) - formatted_string = dates.format_datetime(dt, 'xx', locale='en') - self.assertEqual(u'-0800', formatted_string) - formatted_string = dates.format_datetime(dt, 'xxx', locale='en') - self.assertEqual(u'-08:00', formatted_string) - formatted_string = dates.format_datetime(dt, 'xxxx', locale='en') - self.assertEqual(u'-0800', formatted_string) - formatted_string = dates.format_datetime(dt, 'xxxxx', locale='en') - self.assertEqual(u'-08:00', formatted_string) + assert dates.format_datetime(dt, 'z', locale='en') == u'PST' + assert dates.format_datetime(dt, 'zz', locale='en') == u'PST' + assert dates.format_datetime(dt, 'zzz', locale='en') == u'PST' + assert dates.format_datetime(dt, 'zzzz', locale='en') == u'Pacific Standard Time' + assert dates.format_datetime(dt, 'Z', locale='en') == u'-0800' + assert dates.format_datetime(dt, 'ZZ', locale='en') == u'-0800' + assert dates.format_datetime(dt, 'ZZZ', locale='en') == u'-0800' + assert dates.format_datetime(dt, 'ZZZZ', locale='en') == u'GMT-08:00' + assert dates.format_datetime(dt, 'ZZZZZ', locale='en') == u'-08:00' + assert dates.format_datetime(dt, 'OOOO', locale='en') == u'GMT-08:00' + assert dates.format_datetime(dt, 'VV', locale='en') == u'America/Los_Angeles' + assert dates.format_datetime(dt, 'VVV', locale='en') == u'Los Angeles' + assert dates.format_datetime(dt, 'X', locale='en') == u'-08' + assert dates.format_datetime(dt, 'XX', locale='en') == u'-0800' + assert dates.format_datetime(dt, 'XXX', locale='en') == u'-08:00' + assert dates.format_datetime(dt, 'XXXX', locale='en') == u'-0800' + assert dates.format_datetime(dt, 'XXXXX', locale='en') == u'-08:00' + assert dates.format_datetime(dt, 'x', locale='en') == u'-08' + assert dates.format_datetime(dt, 'xx', locale='en') == u'-0800' + assert dates.format_datetime(dt, 'xxx', locale='en') == u'-08:00' + assert dates.format_datetime(dt, 'xxxx', locale='en') == u'-0800' + assert dates.format_datetime(dt, 'xxxxx', locale='en') == u'-08:00' + + def test_timezone_formats_utc(self): dt = datetime(2016, 1, 13, 7, 8, 35) tz = dates.get_timezone('UTC') dt = tz.localize(dt) - formatted_string = dates.format_datetime(dt, 'Z', locale='en') - self.assertEqual(u'+0000', formatted_string) - formatted_string = dates.format_datetime(dt, 'ZZ', locale='en') - self.assertEqual(u'+0000', formatted_string) - formatted_string = dates.format_datetime(dt, 'ZZZ', locale='en') - self.assertEqual(u'+0000', formatted_string) - formatted_string = dates.format_datetime(dt, 'ZZZZ', locale='en') - self.assertEqual(u'GMT+00:00', formatted_string) - formatted_string = dates.format_datetime(dt, 'ZZZZZ', locale='en') - self.assertEqual(u'Z', formatted_string) - formatted_string = dates.format_datetime(dt, 'OOOO', locale='en') - self.assertEqual(u'GMT+00:00', formatted_string) - formatted_string = dates.format_datetime(dt, 'VV', locale='en') - self.assertEqual(u'Etc/UTC', formatted_string) - formatted_string = dates.format_datetime(dt, 'VVV', locale='en') - self.assertEqual(u'UTC', formatted_string) - formatted_string = dates.format_datetime(dt, 'X', locale='en') - self.assertEqual(u'Z', formatted_string) - formatted_string = dates.format_datetime(dt, 'XX', locale='en') - self.assertEqual(u'Z', formatted_string) - formatted_string = dates.format_datetime(dt, 'XXX', locale='en') - self.assertEqual(u'Z', formatted_string) - formatted_string = dates.format_datetime(dt, 'XXXX', locale='en') - self.assertEqual(u'Z', formatted_string) - formatted_string = dates.format_datetime(dt, 'XXXXX', locale='en') - self.assertEqual(u'Z', formatted_string) - formatted_string = dates.format_datetime(dt, 'x', locale='en') - self.assertEqual(u'+00', formatted_string) - formatted_string = dates.format_datetime(dt, 'xx', locale='en') - self.assertEqual(u'+0000', formatted_string) - formatted_string = dates.format_datetime(dt, 'xxx', locale='en') - self.assertEqual(u'+00:00', formatted_string) - formatted_string = dates.format_datetime(dt, 'xxxx', locale='en') - self.assertEqual(u'+0000', formatted_string) - formatted_string = dates.format_datetime(dt, 'xxxxx', locale='en') - self.assertEqual(u'+00:00', formatted_string) + assert dates.format_datetime(dt, 'Z', locale='en') == u'+0000' + assert dates.format_datetime(dt, 'ZZ', locale='en') == u'+0000' + assert dates.format_datetime(dt, 'ZZZ', locale='en') == u'+0000' + assert dates.format_datetime(dt, 'ZZZZ', locale='en') == u'GMT+00:00' + assert dates.format_datetime(dt, 'ZZZZZ', locale='en') == u'Z' + assert dates.format_datetime(dt, 'OOOO', locale='en') == u'GMT+00:00' + assert dates.format_datetime(dt, 'VV', locale='en') == u'Etc/UTC' + assert dates.format_datetime(dt, 'VVV', locale='en') == u'UTC' + assert dates.format_datetime(dt, 'X', locale='en') == u'Z' + assert dates.format_datetime(dt, 'XX', locale='en') == u'Z' + assert dates.format_datetime(dt, 'XXX', locale='en') == u'Z' + assert dates.format_datetime(dt, 'XXXX', locale='en') == u'Z' + assert dates.format_datetime(dt, 'XXXXX', locale='en') == u'Z' + assert dates.format_datetime(dt, 'x', locale='en') == u'+00' + assert dates.format_datetime(dt, 'xx', locale='en') == u'+0000' + assert dates.format_datetime(dt, 'xxx', locale='en') == u'+00:00' + assert dates.format_datetime(dt, 'xxxx', locale='en') == u'+0000' + assert dates.format_datetime(dt, 'xxxxx', locale='en') == u'+00:00' + + def test_timezone_formats_kolkata(self): dt = datetime(2016, 1, 13, 7, 8, 35) tz = dates.get_timezone('Asia/Kolkata') dt = tz.localize(dt) - formatted_string = dates.format_datetime(dt, 'zzzz', locale='en') - self.assertEqual(u'India Standard Time', formatted_string) - formatted_string = dates.format_datetime(dt, 'ZZZZ', locale='en') - self.assertEqual(u'GMT+05:30', formatted_string) - formatted_string = dates.format_datetime(dt, 'ZZZZZ', locale='en') - self.assertEqual(u'+05:30', formatted_string) - formatted_string = dates.format_datetime(dt, 'OOOO', locale='en') - self.assertEqual(u'GMT+05:30', formatted_string) - formatted_string = dates.format_datetime(dt, 'VV', locale='en') - self.assertEqual(u'Asia/Calcutta', formatted_string) - formatted_string = dates.format_datetime(dt, 'VVV', locale='en') - self.assertEqual(u'Kolkata', formatted_string) - formatted_string = dates.format_datetime(dt, 'X', locale='en') - self.assertEqual(u'+0530', formatted_string) - formatted_string = dates.format_datetime(dt, 'XX', locale='en') - self.assertEqual(u'+0530', formatted_string) - formatted_string = dates.format_datetime(dt, 'XXX', locale='en') - self.assertEqual(u'+05:30', formatted_string) - formatted_string = dates.format_datetime(dt, 'XXXX', locale='en') - self.assertEqual(u'+0530', formatted_string) - formatted_string = dates.format_datetime(dt, 'XXXXX', locale='en') - self.assertEqual(u'+05:30', formatted_string) - formatted_string = dates.format_datetime(dt, 'x', locale='en') - self.assertEqual(u'+0530', formatted_string) - formatted_string = dates.format_datetime(dt, 'xx', locale='en') - self.assertEqual(u'+0530', formatted_string) - formatted_string = dates.format_datetime(dt, 'xxx', locale='en') - self.assertEqual(u'+05:30', formatted_string) - formatted_string = dates.format_datetime(dt, 'xxxx', locale='en') - self.assertEqual(u'+0530', formatted_string) - formatted_string = dates.format_datetime(dt, 'xxxxx', locale='en') - self.assertEqual(u'+05:30', formatted_string) + assert dates.format_datetime(dt, 'zzzz', locale='en') == u'India Standard Time' + assert dates.format_datetime(dt, 'ZZZZ', locale='en') == u'GMT+05:30' + assert dates.format_datetime(dt, 'ZZZZZ', locale='en') == u'+05:30' + assert dates.format_datetime(dt, 'OOOO', locale='en') == u'GMT+05:30' + assert dates.format_datetime(dt, 'VV', locale='en') == u'Asia/Calcutta' + assert dates.format_datetime(dt, 'VVV', locale='en') == u'Kolkata' + assert dates.format_datetime(dt, 'X', locale='en') == u'+0530' + assert dates.format_datetime(dt, 'XX', locale='en') == u'+0530' + assert dates.format_datetime(dt, 'XXX', locale='en') == u'+05:30' + assert dates.format_datetime(dt, 'XXXX', locale='en') == u'+0530' + assert dates.format_datetime(dt, 'XXXXX', locale='en') == u'+05:30' + assert dates.format_datetime(dt, 'x', locale='en') == u'+0530' + assert dates.format_datetime(dt, 'xx', locale='en') == u'+0530' + assert dates.format_datetime(dt, 'xxx', locale='en') == u'+05:30' + assert dates.format_datetime(dt, 'xxxx', locale='en') == u'+0530' + assert dates.format_datetime(dt, 'xxxxx', locale='en') == u'+05:30' class FormatTimeTestCase(unittest.TestCase): def test_with_naive_datetime_and_tzinfo(self): - string = dates.format_time(datetime(2007, 4, 1, 15, 30), - 'long', tzinfo=timezone('US/Eastern'), - locale='en') - self.assertEqual('11:30:00 AM EDT', string) + assert dates.format_time( + datetime(2007, 4, 1, 15, 30), + 'long', + tzinfo=timezone('US/Eastern'), + locale='en', + ) == '11:30:00 AM EDT' def test_with_float(self): d = datetime(2012, 4, 1, 15, 30, 29, tzinfo=timezone('UTC')) epoch = float(calendar.timegm(d.timetuple())) - formatted_time = dates.format_time(epoch, format='long', locale='en_US') - self.assertEqual(u'3:30:29 PM UTC', formatted_time) + assert dates.format_time(epoch, format='long', locale='en_US') == u'3:30:29 PM UTC' def test_with_date_fields_in_pattern(self): self.assertRaises(AttributeError, dates.format_time, date(2007, 4, 1), @@ -471,45 +374,25 @@ def test_with_date_fields_in_pattern_and_datetime_param(self): class FormatTimedeltaTestCase(unittest.TestCase): def test_zero_seconds(self): - string = dates.format_timedelta(timedelta(seconds=0), locale='en') - self.assertEqual('0 seconds', string) - string = dates.format_timedelta(timedelta(seconds=0), locale='en', - format='short') - self.assertEqual('0 sec', string) - string = dates.format_timedelta(timedelta(seconds=0), - granularity='hour', locale='en') - self.assertEqual('0 hours', string) - string = dates.format_timedelta(timedelta(seconds=0), - granularity='hour', locale='en', - format='short') - self.assertEqual('0 hr', string) + td = timedelta(seconds=0) + assert dates.format_timedelta(td, locale='en') == '0 seconds' + assert dates.format_timedelta(td, locale='en', format='short') == '0 sec' + assert dates.format_timedelta(td, granularity='hour', locale='en') == '0 hours' + assert dates.format_timedelta(td, granularity='hour', locale='en', format='short') == '0 hr' def test_small_value_with_granularity(self): - string = dates.format_timedelta(timedelta(seconds=42), - granularity='hour', locale='en') - self.assertEqual('1 hour', string) - string = dates.format_timedelta(timedelta(seconds=42), - granularity='hour', locale='en', - format='short') - self.assertEqual('1 hr', string) + td = timedelta(seconds=42) + assert dates.format_timedelta(td, granularity='hour', locale='en') == '1 hour' + assert dates.format_timedelta(td, granularity='hour', locale='en', format='short') == '1 hr' def test_direction_adding(self): - string = dates.format_timedelta(timedelta(hours=1), - locale='en', - add_direction=True) - self.assertEqual('in 1 hour', string) - string = dates.format_timedelta(timedelta(hours=-1), - locale='en', - add_direction=True) - self.assertEqual('1 hour ago', string) + td = timedelta(hours=1) + assert dates.format_timedelta(td, locale='en', add_direction=True) == 'in 1 hour' + assert dates.format_timedelta(-td, locale='en', add_direction=True) == '1 hour ago' def test_format_narrow(self): - string = dates.format_timedelta(timedelta(hours=1), - locale='en', format='narrow') - self.assertEqual('1h', string) - string = dates.format_timedelta(timedelta(hours=-2), - locale='en', format='narrow') - self.assertEqual('2h', string) + assert dates.format_timedelta(timedelta(hours=1), locale='en', format='narrow') == '1h' + assert dates.format_timedelta(timedelta(hours=-2), locale='en', format='narrow') == '2h' def test_format_invalid(self): self.assertRaises(TypeError, dates.format_timedelta, @@ -529,7 +412,7 @@ def localize(self, dt, is_dst=False): raise NotImplementedError() UTC = EvilFixedOffsetTimezone(0, 'UTC') # This is important to trigger the actual bug (#257) - self.assertEqual(False, hasattr(UTC, 'normalize')) + assert hasattr(UTC, 'normalize') is False return UTC def test_can_format_time_with_non_pytz_timezone(self): @@ -537,7 +420,7 @@ def test_can_format_time_with_non_pytz_timezone(self): utc = self._utc() t = datetime(2007, 4, 1, 15, 30, tzinfo=utc) formatted_time = dates.format_time(t, 'long', tzinfo=utc, locale='en') - self.assertEqual('3:30:00 PM UTC', formatted_time) + assert formatted_time == '3:30:00 PM UTC' def test_get_period_names(): diff --git a/tests/test_localedata.py b/tests/test_localedata.py index 8c4e40ec8..7bfe9c6ba 100644 --- a/tests/test_localedata.py +++ b/tests/test_localedata.py @@ -28,24 +28,19 @@ class MergeResolveTestCase(unittest.TestCase): def test_merge_items(self): d = {1: 'foo', 3: 'baz'} localedata.merge(d, {1: 'Foo', 2: 'Bar'}) - self.assertEqual({1: 'Foo', 2: 'Bar', 3: 'baz'}, d) + assert d == {1: 'Foo', 2: 'Bar', 3: 'baz'} def test_merge_nested_dict(self): d1 = {'x': {'a': 1, 'b': 2, 'c': 3}} d2 = {'x': {'a': 1, 'b': 12, 'd': 14}} localedata.merge(d1, d2) - self.assertEqual({ - 'x': {'a': 1, 'b': 12, 'c': 3, 'd': 14} - }, d1) + assert d1 == {'x': {'a': 1, 'b': 12, 'c': 3, 'd': 14}} def test_merge_nested_dict_no_overlap(self): d1 = {'x': {'a': 1, 'b': 2}} d2 = {'y': {'a': 11, 'b': 12}} localedata.merge(d1, d2) - self.assertEqual({ - 'x': {'a': 1, 'b': 2}, - 'y': {'a': 11, 'b': 12} - }, d1) + assert d1 == {'x': {'a': 1, 'b': 2}, 'y': {'a': 11, 'b': 12}} def test_merge_with_alias_and_resolve(self): alias = localedata.Alias('x') @@ -58,15 +53,9 @@ def test_merge_with_alias_and_resolve(self): 'y': {'b': 22, 'e': 25} } localedata.merge(d1, d2) - self.assertEqual({ - 'x': {'a': 1, 'b': 12, 'c': 3, 'd': 14}, - 'y': (alias, {'b': 22, 'e': 25}) - }, d1) + assert d1 == {'x': {'a': 1, 'b': 12, 'c': 3, 'd': 14}, 'y': (alias, {'b': 22, 'e': 25})} d = localedata.LocaleDataDict(d1) - self.assertEqual({ - 'x': {'a': 1, 'b': 12, 'c': 3, 'd': 14}, - 'y': {'a': 1, 'b': 22, 'c': 3, 'd': 14, 'e': 25} - }, dict(d.items())) + assert dict(d.items()) == {'x': {'a': 1, 'b': 12, 'c': 3, 'd': 14}, 'y': {'a': 1, 'b': 22, 'c': 3, 'd': 14, 'e': 25}} def test_load(): diff --git a/tests/test_numbers.py b/tests/test_numbers.py index bac6c61c9..78f779758 100644 --- a/tests/test_numbers.py +++ b/tests/test_numbers.py @@ -25,25 +25,17 @@ class FormatDecimalTestCase(unittest.TestCase): def test_patterns(self): - self.assertEqual(numbers.format_decimal(12345, '##0', - 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, - '#.00', locale='en_US'), - '100000000000000000000.00') + assert numbers.format_decimal(12345, '##0', locale='en_US') == '12345' + assert numbers.format_decimal(6.5, '0.00', locale='sv') == '6,50' + assert numbers.format_decimal((10.0 ** 20), '#.00', locale='en_US') == '100000000000000000000.00' # regression test for #183, fraction digits were not correctly cutted # if the input was a float value and the value had more than 7 # significant digits - self.assertEqual(u'12,345,678.05', - numbers.format_decimal(12345678.051, '#,##0.00', - locale='en_US')) + assert numbers.format_decimal(12345678.051, '#,##0.00', locale='en_US') == u'12,345,678.05' def test_subpatterns(self): - self.assertEqual(numbers.format_decimal(-12345, '#,##0.##;-#', - locale='en_US'), '-12,345') - self.assertEqual(numbers.format_decimal(-12345, '#,##0.##;(#)', - locale='en_US'), '(12,345)') + assert numbers.format_decimal((- 12345), '#,##0.##;-#', locale='en_US') == '-12,345' + assert numbers.format_decimal((- 12345), '#,##0.##;(#)', locale='en_US') == '(12,345)' def test_default_rounding(self): """ @@ -51,169 +43,114 @@ def test_default_rounding(self): A '5' is rounded to the closest 'even' number """ - self.assertEqual(numbers.format_decimal(5.5, '0', locale='sv'), '6') - self.assertEqual(numbers.format_decimal(6.5, '0', locale='sv'), '6') - self.assertEqual(numbers.format_decimal(6.5, '0', locale='sv'), '6') - self.assertEqual(numbers.format_decimal(1.2325, locale='sv'), '1,232') - self.assertEqual(numbers.format_decimal(1.2335, locale='sv'), '1,234') + assert numbers.format_decimal(5.5, '0', locale='sv') == '6' + assert numbers.format_decimal(6.5, '0', locale='sv') == '6' + assert numbers.format_decimal(6.5, '0', locale='sv') == '6' + assert numbers.format_decimal(1.2325, locale='sv') == '1,232' + assert numbers.format_decimal(1.2335, locale='sv') == '1,234' def test_significant_digits(self): """Test significant digits patterns""" - 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'), - '1,1000') - self.assertEqual(numbers.format_decimal(0.0001, '@@@', locale='sv'), - '0,000100') - self.assertEqual(numbers.format_decimal(0.0001234, '@@@', locale='sv'), - '0,000123') - self.assertEqual(numbers.format_decimal(0.0001234, '@@@#', locale='sv'), - '0,0001234') - self.assertEqual(numbers.format_decimal(0.0001234, '@@@#', locale='sv'), - '0,0001234') - self.assertEqual(numbers.format_decimal(0.12345, '@@@', locale='sv'), - '0,123') - self.assertEqual(numbers.format_decimal(3.14159, '@@##', locale='sv'), - '3,142') - self.assertEqual(numbers.format_decimal(1.23004, '@@##', locale='sv'), - '1,23') - self.assertEqual(numbers.format_decimal(1230.04, '@@,@@', locale='en_US'), - '12,30') - self.assertEqual(numbers.format_decimal(123.41, '@@##', locale='en_US'), - '123.4') - self.assertEqual(numbers.format_decimal(1, '@@', locale='en_US'), - '1.0') - self.assertEqual(numbers.format_decimal(0, '@', locale='en_US'), - '0') - self.assertEqual(numbers.format_decimal(0.1, '@', locale='en_US'), - '0.1') - self.assertEqual(numbers.format_decimal(0.1, '@#', locale='en_US'), - '0.1') - self.assertEqual(numbers.format_decimal(0.1, '@@', locale='en_US'), - '0.10') + assert numbers.format_decimal(123004, '@@', locale='en_US') == '120000' + assert numbers.format_decimal(1.12, '@', locale='sv') == '1' + assert numbers.format_decimal(1.1, '@@', locale='sv') == '1,1' + assert numbers.format_decimal(1.1, '@@@@@##', locale='sv') == '1,1000' + assert numbers.format_decimal(0.0001, '@@@', locale='sv') == '0,000100' + assert numbers.format_decimal(0.0001234, '@@@', locale='sv') == '0,000123' + assert numbers.format_decimal(0.0001234, '@@@#', locale='sv') == '0,0001234' + assert numbers.format_decimal(0.0001234, '@@@#', locale='sv') == '0,0001234' + assert numbers.format_decimal(0.12345, '@@@', locale='sv') == '0,123' + assert numbers.format_decimal(3.14159, '@@##', locale='sv') == '3,142' + assert numbers.format_decimal(1.23004, '@@##', locale='sv') == '1,23' + assert numbers.format_decimal(1230.04, '@@,@@', locale='en_US') == '12,30' + assert numbers.format_decimal(123.41, '@@##', locale='en_US') == '123.4' + assert numbers.format_decimal(1, '@@', locale='en_US') == '1.0' + assert numbers.format_decimal(0, '@', locale='en_US') == '0' + assert numbers.format_decimal(0.1, '@', locale='en_US') == '0.1' + assert numbers.format_decimal(0.1, '@#', locale='en_US') == '0.1' + assert numbers.format_decimal(0.1, '@@', locale='en_US') == '0.10' def test_decimals(self): """Test significant digits patterns""" - self.assertEqual(numbers.format_decimal(decimal.Decimal('1.2345'), - '#.00', locale='en_US'), - '1.23') - self.assertEqual(numbers.format_decimal(decimal.Decimal('1.2345000'), - '#.00', locale='en_US'), - '1.23') - self.assertEqual(numbers.format_decimal(decimal.Decimal('1.2345000'), - '@@', locale='en_US'), - '1.2') - self.assertEqual(numbers.format_decimal(decimal.Decimal('12345678901234567890.12345'), - '#.00', locale='en_US'), - '12345678901234567890.12') + assert numbers.format_decimal(decimal.Decimal('1.2345'), '#.00', locale='en_US') == '1.23' + assert numbers.format_decimal(decimal.Decimal('1.2345000'), '#.00', locale='en_US') == '1.23' + assert numbers.format_decimal(decimal.Decimal('1.2345000'), '@@', locale='en_US') == '1.2' + assert numbers.format_decimal(decimal.Decimal('12345678901234567890.12345'), '#.00', locale='en_US') == '12345678901234567890.12' def test_scientific_notation(self): - fmt = numbers.format_scientific(0.1, '#E0', locale='en_US') - self.assertEqual(fmt, '1E-1') - fmt = numbers.format_scientific(0.01, '#E0', locale='en_US') - self.assertEqual(fmt, '1E-2') - fmt = numbers.format_scientific(10, '#E0', locale='en_US') - self.assertEqual(fmt, '1E1') - fmt = numbers.format_scientific(1234, '0.###E0', locale='en_US') - self.assertEqual(fmt, '1.234E3') - fmt = numbers.format_scientific(1234, '0.#E0', locale='en_US') - self.assertEqual(fmt, '1.2E3') + assert numbers.format_scientific(0.1, '#E0', locale='en_US') == '1E-1' + assert numbers.format_scientific(0.01, '#E0', locale='en_US') == '1E-2' + assert numbers.format_scientific(10, '#E0', locale='en_US') == '1E1' + assert numbers.format_scientific(1234, '0.###E0', locale='en_US') == '1.234E3' + assert numbers.format_scientific(1234, '0.#E0', locale='en_US') == '1.2E3' # Exponent grouping - fmt = numbers.format_scientific(12345, '##0.####E0', locale='en_US') - self.assertEqual(fmt, '1.2345E4') + assert numbers.format_scientific(12345, '##0.####E0', locale='en_US') == '1.2345E4' # Minimum number of int digits - fmt = numbers.format_scientific(12345, '00.###E0', locale='en_US') - self.assertEqual(fmt, '12.345E3') - fmt = numbers.format_scientific(-12345.6, '00.###E0', locale='en_US') - self.assertEqual(fmt, '-12.346E3') - fmt = numbers.format_scientific(-0.01234, '00.###E0', locale='en_US') - self.assertEqual(fmt, '-12.34E-3') - # Custom pattern suffic - fmt = numbers.format_scientific(123.45, '#.##E0 m/s', locale='en_US') - self.assertEqual(fmt, '1.23E2 m/s') + assert numbers.format_scientific(12345, '00.###E0', locale='en_US') == '12.345E3' + assert numbers.format_scientific(-12345.6, '00.###E0', locale='en_US') == '-12.346E3' + assert numbers.format_scientific(-0.01234, '00.###E0', locale='en_US') == '-12.34E-3' + # Custom pattern suffix + assert numbers.format_scientific(123.45, '#.##E0 m/s', locale='en_US') == '1.23E2 m/s' # Exponent patterns - fmt = numbers.format_scientific(123.45, '#.##E00 m/s', locale='en_US') - self.assertEqual(fmt, '1.23E02 m/s') - 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.Decimal('12345'), '#.##E+00 m/s', - locale='en_US') - self.assertEqual(fmt, '1.23E+04 m/s') + assert numbers.format_scientific(123.45, '#.##E00 m/s', locale='en_US') == '1.23E02 m/s' + assert numbers.format_scientific(0.012345, '#.##E00 m/s', locale='en_US') == '1.23E-02 m/s' + assert numbers.format_scientific(decimal.Decimal('12345'), '#.##E+00 m/s', locale='en_US') == '1.23E+04 m/s' # 0 (see ticket #99) - fmt = numbers.format_scientific(0, '#E0', locale='en_US') - self.assertEqual(fmt, '0E0') + assert numbers.format_scientific(0, '#E0', locale='en_US') == '0E0' def test_formatting_of_very_small_decimals(self): # previously formatting very small decimals could lead to a type error # because the Decimal->string conversion was too simple (see #214) number = decimal.Decimal("7E-7") - fmt = numbers.format_decimal(number, format="@@@", locale='en_US') - self.assertEqual('0.000000700', fmt) + assert numbers.format_decimal(number, format="@@@", locale='en_US') == '0.000000700' def test_group_separator(self): - self.assertEqual('29567.12', numbers.format_decimal(29567.12, - locale='en_US', group_separator=False)) - self.assertEqual('29567,12', numbers.format_decimal(29567.12, - locale='fr_CA', group_separator=False)) - self.assertEqual('29567,12', numbers.format_decimal(29567.12, - locale='pt_BR', group_separator=False)) - self.assertEqual(u'$1099.98', numbers.format_currency(1099.98, 'USD', - locale='en_US', group_separator=False)) - self.assertEqual(u'101299,98\xa0€', numbers.format_currency(101299.98, 'EUR', - locale='fr_CA', group_separator=False)) - self.assertEqual('101299.98 euros', numbers.format_currency(101299.98, 'EUR', - locale='en_US', group_separator=False, format_type='name')) - self.assertEqual(u'25123412\xa0%', numbers.format_percent(251234.1234, locale='sv_SE', group_separator=False)) - - self.assertEqual(u'29,567.12', numbers.format_decimal(29567.12, - locale='en_US', group_separator=True)) - self.assertEqual(u'29\xa0567,12', numbers.format_decimal(29567.12, - locale='fr_CA', group_separator=True)) - self.assertEqual(u'29.567,12', numbers.format_decimal(29567.12, - locale='pt_BR', group_separator=True)) - self.assertEqual(u'$1,099.98', numbers.format_currency(1099.98, 'USD', - locale='en_US', group_separator=True)) - self.assertEqual(u'101\xa0299,98\xa0\u20ac', numbers.format_currency(101299.98, 'EUR', - locale='fr_CA', group_separator=True)) - self.assertEqual(u'101,299.98 euros', numbers.format_currency(101299.98, 'EUR', - locale='en_US', group_separator=True, - format_type='name')) - self.assertEqual(u'25\xa0123\xa0412\xa0%', numbers.format_percent(251234.1234, locale='sv_SE', group_separator=True)) + assert numbers.format_decimal(29567.12, locale='en_US', group_separator=False) == '29567.12' + assert numbers.format_decimal(29567.12, locale='fr_CA', group_separator=False) == '29567,12' + assert numbers.format_decimal(29567.12, locale='pt_BR', group_separator=False) == '29567,12' + assert numbers.format_currency(1099.98, 'USD', locale='en_US', group_separator=False) == u'$1099.98' + assert numbers.format_currency(101299.98, 'EUR', locale='fr_CA', group_separator=False) == u'101299,98\xa0€' + assert numbers.format_currency(101299.98, 'EUR', locale='en_US', group_separator=False, format_type='name') == '101299.98 euros' + assert numbers.format_percent(251234.1234, locale='sv_SE', group_separator=False) == u'25123412\xa0%' + + assert numbers.format_decimal(29567.12, locale='en_US', group_separator=True) == u'29,567.12' + assert numbers.format_decimal(29567.12, locale='fr_CA', group_separator=True) == u'29\xa0567,12' + assert numbers.format_decimal(29567.12, locale='pt_BR', group_separator=True) == u'29.567,12' + assert numbers.format_currency(1099.98, 'USD', locale='en_US', group_separator=True) == u'$1,099.98' + assert numbers.format_currency(101299.98, 'EUR', locale='fr_CA', group_separator=True) == u'101\xa0299,98\xa0€' + assert numbers.format_currency(101299.98, 'EUR', locale='en_US', group_separator=True, format_type='name') == u'101,299.98 euros' + assert numbers.format_percent(251234.1234, locale='sv_SE', group_separator=True) == u'25\xa0123\xa0412\xa0%' class NumberParsingTestCase(unittest.TestCase): def test_can_parse_decimals(self): - self.assertEqual(decimal.Decimal('1099.98'), - numbers.parse_decimal('1,099.98', locale='en_US')) - self.assertEqual(decimal.Decimal('1099.98'), - numbers.parse_decimal('1.099,98', locale='de')) - self.assertRaises(numbers.NumberFormatError, - lambda: numbers.parse_decimal('2,109,998', locale='de')) + assert decimal.Decimal('1099.98') == numbers.parse_decimal('1,099.98', locale='en_US') + assert decimal.Decimal('1099.98') == numbers.parse_decimal('1.099,98', locale='de') + with pytest.raises(numbers.NumberFormatError): + numbers.parse_decimal('2,109,998', locale='de') def test_parse_decimal_strict_mode(self): # Numbers with a misplaced grouping symbol should be rejected - with self.assertRaises(numbers.NumberFormatError) as info: + with pytest.raises(numbers.NumberFormatError) as info: numbers.parse_decimal('11.11', locale='de', strict=True) - assert info.exception.suggestions == ['1.111', '11,11'] + assert info.value.suggestions == ['1.111', '11,11'] # Numbers with two misplaced grouping symbols should be rejected - with self.assertRaises(numbers.NumberFormatError) as info: + with pytest.raises(numbers.NumberFormatError) as info: numbers.parse_decimal('80.00.00', locale='de', strict=True) - assert info.exception.suggestions == ['800.000'] + assert info.value.suggestions == ['800.000'] # Partially grouped numbers should be rejected - with self.assertRaises(numbers.NumberFormatError) as info: + with pytest.raises(numbers.NumberFormatError) as info: numbers.parse_decimal('2000,000', locale='en_US', strict=True) - assert info.exception.suggestions == ['2,000,000', '2,000'] + assert info.value.suggestions == ['2,000,000', '2,000'] # Numbers with duplicate grouping symbols should be rejected - with self.assertRaises(numbers.NumberFormatError) as info: + with pytest.raises(numbers.NumberFormatError) as info: numbers.parse_decimal('0,,000', locale='en_US', strict=True) - assert info.exception.suggestions == ['0'] + assert info.value.suggestions == ['0'] # Return only suggestion for 0 on strict - with self.assertRaises(numbers.NumberFormatError) as info: + with pytest.raises(numbers.NumberFormatError) as info: numbers.parse_decimal('0.00', locale='de', strict=True) - assert info.exception.suggestions == ['0'] + assert info.value.suggestions == ['0'] # Properly formatted numbers should be accepted assert str(numbers.parse_decimal('1.001', locale='de', strict=True)) == '1001' # Trailing zeroes should be accepted diff --git a/tests/test_support.py b/tests/test_support.py index a4fa3267a..2d8e9332d 100644 --- a/tests/test_support.py +++ b/tests/test_support.py @@ -62,7 +62,7 @@ def setUp(self): self.translations = translations1.add(translations2, merge=False) def assertEqualTypeToo(self, expected, result): - self.assertEqual(expected, result) + assert expected == result assert type(expected) == type(result), "instance type's do not " + \ "match: %r!=%r" % (type(expected), type(result)) @@ -186,7 +186,7 @@ def test_load(self): write_mo(f, catalog) translations = support.Translations.load(tempdir, locales=('fr',), domain='messages') - self.assertEqual('bar', translations.gettext('foo')) + assert translations.gettext('foo') == 'bar' finally: shutil.rmtree(tempdir) @@ -216,10 +216,7 @@ def test_method_signature_compatibility(self): for name in self.method_names(): translations_method = getattr(self.translations, name) null_method = getattr(self.null_translations, name) - self.assertEqual( - inspect.getfullargspec(translations_method), - inspect.getfullargspec(null_method), - ) + assert inspect.getfullargspec(translations_method) == inspect.getfullargspec(null_method) def test_same_return_values(self): data = { @@ -233,7 +230,7 @@ def test_same_return_values(self): signature = inspect.getfullargspec(method) parameter_names = [name for name in signature.args if name != 'self'] values = [data[name] for name in parameter_names] - self.assertEqual(method(*values), null_method(*values)) + assert method(*values) == null_method(*values) class LazyProxyTestCase(unittest.TestCase): @@ -245,8 +242,8 @@ def add_one(): self.counter += 1 return self.counter proxy = support.LazyProxy(add_one) - self.assertEqual(1, proxy.value) - self.assertEqual(1, proxy.value) + assert proxy.value == 1 + assert proxy.value == 1 def test_can_disable_proxy_cache(self): self.counter = 0 @@ -255,8 +252,8 @@ def add_one(): self.counter += 1 return self.counter proxy = support.LazyProxy(add_one, enable_cache=False) - self.assertEqual(1, proxy.value) - self.assertEqual(2, proxy.value) + assert proxy.value == 1 + assert proxy.value == 2 def test_can_copy_proxy(self): from copy import copy @@ -270,8 +267,8 @@ def first(xs): proxy_copy = copy(proxy) numbers.pop(0) - self.assertEqual(2, proxy.value) - self.assertEqual(2, proxy_copy.value) + assert proxy.value == 2 + assert proxy_copy.value == 2 def test_can_deepcopy_proxy(self): from copy import deepcopy @@ -284,8 +281,8 @@ def first(xs): proxy_deepcopy = deepcopy(proxy) numbers.pop(0) - self.assertEqual(2, proxy.value) - self.assertEqual(1, proxy_deepcopy.value) + assert proxy.value == 2 + assert proxy_deepcopy.value == 1 def test_handle_attribute_error(self): @@ -296,7 +293,7 @@ def raise_attribute_error(): with pytest.raises(AttributeError) as exception: proxy.value - self.assertEqual('message', str(exception.value)) + assert str(exception.value) == 'message' def test_format_date(): diff --git a/tests/test_util.py b/tests/test_util.py index e6a19d51a..d78aee7bc 100644 --- a/tests/test_util.py +++ b/tests/test_util.py @@ -47,13 +47,13 @@ def test_pathmatch(): class FixedOffsetTimezoneTestCase(unittest.TestCase): def test_zone_negative_offset(self): - self.assertEqual('Etc/GMT-60', util.FixedOffsetTimezone(-60).zone) + assert util.FixedOffsetTimezone((-60)).zone == 'Etc/GMT-60' def test_zone_zero_offset(self): - self.assertEqual('Etc/GMT+0', util.FixedOffsetTimezone(0).zone) + assert util.FixedOffsetTimezone(0).zone == 'Etc/GMT+0' def test_zone_positive_offset(self): - self.assertEqual('Etc/GMT+330', util.FixedOffsetTimezone(330).zone) + assert util.FixedOffsetTimezone(330).zone == 'Etc/GMT+330' parse_encoding = lambda s: util.parse_encoding(BytesIO(s.encode('utf-8'))) From eeb01c78001020837daa7bca70e05d21897692e1 Mon Sep 17 00:00:00 2001 From: Aarni Koskela Date: Tue, 10 May 2022 13:36:00 +0300 Subject: [PATCH 2/2] tests: Use pytest.raises() decorator where applicable --- tests/messages/test_extract.py | 9 ++++++--- tests/test_dates.py | 27 +++++++++++---------------- 2 files changed, 17 insertions(+), 19 deletions(-) diff --git a/tests/messages/test_extract.py b/tests/messages/test_extract.py index e3d925e5d..47fe30603 100644 --- a/tests/messages/test_extract.py +++ b/tests/messages/test_extract.py @@ -15,6 +15,8 @@ import unittest from io import BytesIO, StringIO +import pytest + from babel.messages import extract @@ -380,8 +382,8 @@ def test_utf8_bom_with_latin_magic_comment_fails(self): # NOTE: hello msg = _('Bonjour à tous') """.encode('utf-8')) - self.assertRaises(SyntaxError, list, - extract.extract_python(buf, ('_',), ['NOTE:'], {})) + with pytest.raises(SyntaxError): + list(extract.extract_python(buf, ('_',), ['NOTE:'], {})) def test_utf8_raw_strings_match_unicode_strings(self): buf = BytesIO(codecs.BOM_UTF8 + u""" @@ -466,7 +468,8 @@ def test_invalid_filter(self): def test_invalid_extract_method(self): buf = BytesIO(b'') - self.assertRaises(ValueError, list, extract.extract('spam', buf)) + with pytest.raises(ValueError): + list(extract.extract('spam', buf)) def test_different_signatures(self): buf = BytesIO(b""" diff --git a/tests/test_dates.py b/tests/test_dates.py index 227813b23..b62f542cd 100644 --- a/tests/test_dates.py +++ b/tests/test_dates.py @@ -252,13 +252,12 @@ def test_hour_formatting(self): class FormatDateTestCase(unittest.TestCase): def test_with_time_fields_in_pattern(self): - self.assertRaises(AttributeError, dates.format_date, date(2007, 4, 1), - "yyyy-MM-dd HH:mm", locale='en_US') + with pytest.raises(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, 4, 1, 15, 30), - "yyyy-MM-dd HH:mm", locale='en_US') + with pytest.raises(AttributeError): + dates.format_date(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) @@ -362,13 +361,12 @@ def test_with_float(self): assert dates.format_time(epoch, format='long', locale='en_US') == u'3:30:29 PM UTC' def test_with_date_fields_in_pattern(self): - self.assertRaises(AttributeError, dates.format_time, date(2007, 4, 1), - "yyyy-MM-dd HH:mm", locale='en_US') + with pytest.raises(AttributeError): + dates.format_time(datetime(2007, 4, 1), 'yyyy-MM-dd HH:mm', locale='en') def test_with_date_fields_in_pattern_and_datetime_param(self): - self.assertRaises(AttributeError, dates.format_time, - datetime(2007, 4, 1, 15, 30), - "yyyy-MM-dd HH:mm", locale='en_US') + with pytest.raises(AttributeError): + dates.format_time(datetime(2007, 4, 1, 15, 30), "yyyy-MM-dd HH:mm", locale='en_US') class FormatTimedeltaTestCase(unittest.TestCase): @@ -395,12 +393,9 @@ def test_format_narrow(self): assert dates.format_timedelta(timedelta(hours=-2), locale='en', format='narrow') == '2h' def test_format_invalid(self): - self.assertRaises(TypeError, dates.format_timedelta, - timedelta(hours=1), format='') - self.assertRaises(TypeError, dates.format_timedelta, - timedelta(hours=1), format='bold italic') - self.assertRaises(TypeError, dates.format_timedelta, - timedelta(hours=1), format=None) + for format in (None, '', 'bold italic'): + with pytest.raises(TypeError): + dates.format_timedelta(timedelta(hours=1), format=format) class TimeZoneAdjustTestCase(unittest.TestCase):