]> git.ipfire.org Git - thirdparty/babel.git/commitdiff
Add comparison operators to _NormalizedString
authorAarni Koskela <akx@iki.fi>
Mon, 27 May 2019 08:19:08 +0000 (11:19 +0300)
committerAarni Koskela <akx@iki.fi>
Mon, 27 May 2019 08:37:12 +0000 (11:37 +0300)
Based on @hoangduytranuk's original implementation.

Fixes #612

babel/messages/pofile.py
tests/messages/test_normalized_string.py [new file with mode: 0644]

index fe376318adf625fa197a4c184cb7ca443f771821..2943fa2ece6fe134e3019f2c3c16c5a7220c66e5 100644 (file)
@@ -16,8 +16,7 @@ import re
 
 from babel.messages.catalog import Catalog, Message
 from babel.util import wraptext
-from babel._compat import text_type
-
+from babel._compat import text_type, cmp
 
 
 def unescape(string):
@@ -99,6 +98,36 @@ class _NormalizedString(object):
     def __nonzero__(self):
         return bool(self._strs)
 
+    __bool__ = __nonzero__
+
+    def __repr__(self):
+        return os.linesep.join(self._strs)
+
+    def __cmp__(self, other):
+        if not other:
+            return 1
+
+        return cmp(text_type(self), text_type(other))
+
+    def __gt__(self, other):
+        return self.__cmp__(other) > 0
+
+    def __lt__(self, other):
+        return self.__cmp__(other) < 0
+
+    def __ge__(self, other):
+        return self.__cmp__(other) >= 0
+
+    def __le__(self, other):
+        return self.__cmp__(other) <= 0
+
+    def __eq__(self, other):
+        return self.__cmp__(other) == 0
+
+    def __ne__(self, other):
+        return self.__cmp__(other) != 0
+
+
 
 class PoFileParser(object):
     """Support class to  read messages from a ``gettext`` PO (portable object) file
diff --git a/tests/messages/test_normalized_string.py b/tests/messages/test_normalized_string.py
new file mode 100644 (file)
index 0000000..9c95672
--- /dev/null
@@ -0,0 +1,17 @@
+from babel.messages.pofile import _NormalizedString
+
+
+def test_normalized_string():
+    ab1 = _NormalizedString('a', 'b ')
+    ab2 = _NormalizedString('a', ' b')
+    ac1 = _NormalizedString('a', 'c')
+    ac2 = _NormalizedString('  a', 'c  ')
+    z = _NormalizedString()
+    assert ab1 == ab2 and ac1 == ac2  # __eq__
+    assert ab1 < ac1  # __lt__
+    assert ac1 > ab2  # __gt__
+    assert ac1 >= ac2  # __ge__
+    assert ab1 <= ab2  # __le__
+    assert ab1 != ac1  # __ne__
+    assert not z  # __nonzero__ / __bool__
+    assert sorted([ab1, ab2, ac1])  # the sort order is not stable so we can't really check it, just that we can sort