]> khamidou — GitHub mirrors - imapclient.git/commitdiff
unicode work: All unit tests pass again under all supported Python versions
authorMenno Smits <menno@freshfoo.com>
Sun, 3 Aug 2014 13:01:26 +0000 (01:01 +1200)
committerMenno Smits <menno@freshfoo.com>
Sun, 3 Aug 2014 13:01:26 +0000 (01:01 +1200)
Still plenty of clean up and testing to do (see XXX and TODO).

imapclient/imap_utf7.py
imapclient/imapclient.py
imapclient/test/test_datetime_util.py
imapclient/test/test_imap_utf7.py
imapclient/test/test_imapclient.py
imapclient/test/test_search.py
imapclient/test/test_util_functions.py
imapclient/test/testable_imapclient.py

index 06423e0e8bbf6fcafb4cf4fecb6d148f7ecf6f2e..b3592adbf09220f1493c24e556645f259e3589f0 100644 (file)
 
 from __future__ import unicode_literals
 
-from .six import text_type, binary_type, iteritems
+from .six import binary_type, text_type, byte2int, iterbytes, unichr
+
 
 PRINTABLE = set(range(0x20, 0x26)) | set(range(0x27, 0x7f))
 
+# TODO: module needs refactoring (e.g. variable names suck)
+
 def encode(s):
     """Encode a folder name using IMAP modified UTF-7 encoding.
 
-    Despite the function's name, the output is still a unicode string.
+    Input is unicode; output is bytes (Python 3) or str (Python 2). If
+    non-unicode input is provided, the input is returned unchanged.
     """
     if not isinstance(s, text_type):
         return s
@@ -41,60 +45,61 @@ def encode(s):
 
     def extend_result_if_chars_buffered():
         if _in:
-            r.extend(['&', modified_utf7(''.join(_in)), '-'])
+            r.extend([b'&', modified_utf7(''.join(_in)), b'-'])
             del _in[:]
 
     for c in s:
         if ord(c) in PRINTABLE:
             extend_result_if_chars_buffered()
-            r.append(c)
+            r.append(c.encode('latin-1'))
         elif c == '&':
             extend_result_if_chars_buffered()
-            r.append('&-')
+            r.append(b'&-')
         else:
             _in.append(c)
 
     extend_result_if_chars_buffered()
 
-    return ''.join(r)
+    return b''.join(r)
+
+
+AMPERSAND_ORD = byte2int(b'&')
+DASH_ORD = byte2int(b'-')
 
 def decode(s):
     """Decode a folder name from IMAP modified UTF-7 encoding to unicode.
 
-    Despite the function's name, the input may still be a unicode
-    string. If the input is bytes, it's first decoded to unicode.
+    XXX expand
     """
-    if isinstance(s, binary_type):
-        s = s.decode('latin-1')
-    if not isinstance(s, text_type):
+
+    if not isinstance(s, binary_type):
         return s
 
     r = []
-    _in = []
-    for c in s:
-        if c == '&' and not _in:
-            _in.append('&')
-        elif c == '-' and _in:
+    _in = bytearray()
+    for c in iterbytes(s):
+        if c == AMPERSAND_ORD and not _in:
+            _in.append(c)
+        elif c == DASH_ORD and _in:
             if len(_in) == 1:
                 r.append('&')
             else:
-                r.append(modified_deutf7(''.join(_in[1:])))
-            _in = []
+                r.append(modified_deutf7(_in[1:]))
+            _in = bytearray()
         elif _in:
             _in.append(c)
         else:
-            r.append(c)
+            r.append(unichr(c))
     if _in:
-        r.append(modified_deutf7(''.join(_in[1:])))
-
+        r.append(modified_deutf7(_in[1:]))
     return ''.join(r)
 
+
 def modified_utf7(s):
-    # encode to utf-7: '\xff' => b'+AP8-', decode from latin-1 => '+AP8-'
-    s_utf7 = s.encode('utf-7').decode('latin-1')
-    return s_utf7[1:-1].replace('/', ',')
+    s_utf7 = s.encode('utf-7')
+    return s_utf7[1:-1].replace(b'/', b',')
+
 
 def modified_deutf7(s):
-    s_utf7 = '+' + s.replace(',', '/') + '-'
-    # encode to latin-1: '+AP8-' => b'+AP8-', decode from utf-7 => '\xff'
-    return s_utf7.encode('latin-1').decode('utf-7')
+    s_utf7 = b'+' + s.replace(b',', b'/') + b'-'
+    return s_utf7.decode('utf-7')
index 1000f83ce383027eaa73f0e7f3514ac9eb7d7b28..51dd63fd46b0b9ade8cc3ac725c4df1f05fdee2f 100644 (file)
@@ -23,7 +23,7 @@ except ImportError:
 
 from .imap_utf7 import encode as encode_utf7, decode as decode_utf7
 from .fixed_offset import FixedOffset
-from .six import moves, iteritems, text_type, integer_types, PY3, binary_type
+from .six import moves, iteritems, text_type, integer_types, PY3, binary_type, string_types
 xrange = moves.xrange
 
 if PY3:
@@ -195,10 +195,10 @@ class IMAPClient(object):
 
         # Just return capabilities that imaplib grabbed at connection
         # time (pre-auth)
-        return from_bytes(self._imap.capabilities)
+        return tuple(to_bytes(c) for c in self._imap.capabilities)
 
     def _save_capabilities(self, raw_response):
-        raw_response = from_bytes(raw_response)
+        raw_response = to_bytes(raw_response)
         self._cached_capabilities = tuple(raw_response.upper().split())
         return self._cached_capabilities
 
@@ -210,7 +210,7 @@ class IMAPClient(object):
         # capabilities may in the future be named SORT2 which is
         # still compatible with the current standard and will not
         # be detected by this method.
-        return capability.upper() in self.capabilities()
+        return to_bytes(capability).upper() in self.capabilities()
 
     def namespace(self):
         """Return the namespace for the account as a (personal, other,
@@ -226,7 +226,18 @@ class IMAPClient(object):
         See :rfc:`2342` for more details.
         """
         data = self._command_and_check('namespace')
-        return Namespace(*parse_response(data))
+        parts = []
+        for item in parse_response(data):
+            if item is None:
+                parts.append(item)
+            else:
+                converted = []
+                for prefix, separator in item:
+                    if self.folder_encode:
+                        prefix = decode_utf7(prefix)
+                    converted.append((prefix, to_unicode(separator)))
+                parts.append(tuple(converted))
+        return Namespace(*parts)
 
     def get_folder_delimiter(self):
         """Return the folder separator used by the IMAP server.
@@ -365,22 +376,22 @@ class IMAPClient(object):
 
         # imaplib doesn't parse these correctly (broken regex) so replace
         # with the raw values out of the OK section
-        for line in resp.get('OK', []):
-            match = re.match(r'\[(?P<key>[A-Z-]+)( \((?P<data>.*)\))?\]', line)
+        for line in resp.get(b'OK', []):
+            match = re.match(br'\[(?P<key>[A-Z-]+)( \((?P<data>.*)\))?\]', line)
             if match:
                 key = match.group('key')
-                if key == 'PERMANENTFLAGS':
+                if key == b'PERMANENTFLAGS':
                     out[key] = tuple(match.group('data').split())
 
         for key, value in iteritems(resp):
             key = key.upper()
-            if key in ('OK', 'PERMANENTFLAGS'):
+            if key in (b'OK', b'PERMANENTFLAGS'):
                 continue  # already handled above
-            elif key in ('EXISTS', 'RECENT', 'UIDNEXT', 'UIDVALIDITY', 'HIGHESTMODSEQ'):
+            elif key in (b'EXISTS', b'RECENT', b'UIDNEXT', b'UIDVALIDITY', b'HIGHESTMODSEQ'):
                 value = int(value[0])
-            elif key == 'READ-WRITE':
+            elif key == b'READ-WRITE':
                 value = True
-            elif key == 'FLAGS':
+            elif key == b'FLAGS':
                 value = tuple(value[0][1:-1].split())
             out[key] = value
         return out
@@ -583,14 +594,16 @@ class IMAPClient(object):
         search string. It defaults to US-ASCII.
         """
         # the the query is sent as a literal to allow for 7-bit query strings
-        self._imap.literal = query.encode(charset or 'us-ascii')
-        return self._search(['X-GM-RAW'], charset)
+        if isinstance(query, string_types):
+            query = query.encode(charset or 'us-ascii')
+        self._imap.literal = query
+        return self._search([b'X-GM-RAW'], charset)
 
     def _search(self, criteria, charset):
         if self.use_uid:
             args = []
             if charset:
-                args.extend(['CHARSET', charset])
+                args.extend([b'CHARSET', charset])
             args.extend(criteria)
             typ, data = self._imap.uid('SEARCH', *args)
         else:
@@ -611,7 +624,8 @@ class IMAPClient(object):
 
         See :rfc:`5256` for more details.
         """
-        if not self.has_capability('THREAD=' + algorithm):
+        algorithm = to_bytes(algorithm)
+        if not self.has_capability(b'THREAD=' + algorithm):
             raise ValueError('server does not support %s threading algorithm'
                              % algorithm)
 
@@ -620,7 +634,7 @@ class IMAPClient(object):
 
         args = [algorithm]
         if charset:
-            args.append(charset)
+            args.append(to_bytes(charset))
         args.extend(normalise_search_criteria(criteria))
 
         data = self._command_and_check('thread', *args, uid=True)
@@ -971,8 +985,18 @@ class IMAPClient(object):
             folder_name = folder_name.decode('ascii')
         if self.folder_encode:
             folder_name = encode_utf7(folder_name)
-        return self._imap._quote(folder_name)
-
+        return _quote(folder_name)
+
+#XXX revisit
+def _quote(arg):
+    if isinstance(arg, text_type):
+        arg = arg.replace('\\', '\\\\')
+        arg = arg.replace('"', '\\"')
+        return '"%s"' % arg
+    else:
+        arg = arg.replace(b'\\', b'\\\\')
+        arg = arg.replace(b'"', b'\\"')
+        return b'"' + arg + b'"'
 
 def normalise_text_list(items):
     return list(_normalise_text_list(items))
@@ -983,31 +1007,32 @@ def seq_to_parenstr(items):
 def seq_to_parenstr_upper(items):
     return _join_and_paren(item.upper() for item in _normalise_text_list(items))
 
+#XXX name?
 def messages_to_str(messages):
     """Convert a sequence of messages ids or a single integer message id
     into an id list string for use with IMAP commands
     """
     if isinstance(messages, (text_type, binary_type, integer_types)):
-        messages = (messages,)
-    return ','.join(_maybe_int_to_unicode(m) for m in messages)
+        messages = (to_bytes(messages),)
+    return b','.join(_maybe_int_to_bytes(m) for m in messages)
 
-def _maybe_int_to_unicode(val):
+def _maybe_int_to_bytes(val):
     if isinstance(val, integer_types):
-        return text_type(val)
-    return to_unicode(val)
+        return str(val).encode('us-ascii')
+    return to_bytes(val)
 
 def normalise_search_criteria(criteria):
     if not criteria:
         raise ValueError('no criteria specified')
-    return ['(%s)' % item for item in _normalise_text_list(criteria)]
+    return [b'(' + item + b')' for item in _normalise_text_list(criteria)]
 
 def _join_and_paren(items):
-    return '(%s)' % ' '.join(items)
+    return b'(' + b' '.join(items) + b')'
 
 def _normalise_text_list(items):
     if isinstance(items, (text_type, binary_type)):
-        items = (items,)
-    return (to_unicode(c) for c in items)
+        items = (to_bytes(items),)
+    return (to_bytes(c) for c in items)
 
 def datetime_to_imap(dt):
     """Convert a datetime instance to a IMAP datetime string.
@@ -1020,10 +1045,10 @@ def datetime_to_imap(dt):
     return dt.strftime("%d-%b-%Y %H:%M:%S %z")
 
 def _parse_untagged_response(text):
-    assert text.startswith('* ')
+    assert text.startswith(b'* ')
     text = text[2:]
-    if text.startswith(('OK ', 'NO ')):
-        return tuple(text.split(' ', 1))
+    if text.startswith((b'OK ', b'NO ')):
+        return tuple(text.split(b' ', 1))
     return parse_response([text])
 
 def pop_with_default(dct, key, default):
@@ -1041,11 +1066,13 @@ def as_pairs(items):
             last_item = item
         i += 1
 
+#XXX
 def to_unicode(s):
     if isinstance(s, binary_type):
         return s.decode('ascii')
     return s
 
+#XXX
 def to_bytes(s):
     if isinstance(s, text_type):
         return s.encode('ascii')
@@ -1054,6 +1081,8 @@ def to_bytes(s):
 def from_bytes(data):
     """Convert bytes to string in lists, tuples and dicts.
     """
+    #XXX
+    return data
     if isinstance(data, dict):
         decoded = {}
         for key, value in iteritems(data):
index ea48db568acb09ced66ef8a9f90f0e11e1d03857..fb6deba2a848a7f9aa85e3abb99c8c846269bbff 100644 (file)
@@ -25,15 +25,15 @@ class TestParsing(unittest.TestCase):
 
     def test_rfc822_style(self):
         self.check_normalised_and_not(
-            'Sun, 24 Mar 2013 22:06:10 +0200',
+            b'Sun, 24 Mar 2013 22:06:10 +0200',
             datetime(2013, 3, 24, 22, 6, 10, 0, FixedOffset(120))
         )
 
     def test_internaldate_style(self):
         self.check_normalised_and_not(
-            ' 9-Feb-2007 17:08:08 -0430',
+            b' 9-Feb-2007 17:08:08 -0430',
             datetime(2007, 2, 9, 17, 8, 8, 0, FixedOffset(-4*60 - 30))
         )
 
     def test_invalid(self):
-        self.assertRaises(ValueError, parse_to_datetime, 'ABC')
+        self.assertRaises(ValueError, parse_to_datetime, b'ABC')
index d63bd7ddfa717fbffebf9f6dc05ddfe3074800be..2db59142a5233a2a46b7410c3cdc0c5346696a3f 100644 (file)
@@ -4,31 +4,29 @@
 
 from __future__ import unicode_literals
 
-from imapclient.six import text_type, PY3
+from imapclient.six import text_type, binary_type, int2byte, unichr
 from imapclient.imap_utf7 import decode, encode
 from imapclient.test.util import unittest
 
-if PY3:
-    unichr = chr  # unichr doesn't exist in py3 where every string is unicode
 
 class IMAP4UTF7TestCase(unittest.TestCase):
     tests = [
-        ['Foo', 'Foo'],
-        ['Foo Bar', 'Foo Bar'],
-        ['Stuff & Things', 'Stuff &- Things'],
-        ['Hello world', 'Hello world'],
-        ['Hello & world', 'Hello &- world'],
-        ['Hello\xffworld', 'Hello&AP8-world'],
-        ['\xff\xfe\xfd\xfc', '&AP8A,gD9APw-'],
+        ['Foo', b'Foo'],
+        ['Foo Bar', b'Foo Bar'],
+        ['Stuff & Things', b'Stuff &- Things'],
+        ['Hello world', b'Hello world'],
+        ['Hello & world', b'Hello &- world'],
+        ['Hello\xffworld', b'Hello&AP8-world'],
+        ['\xff\xfe\xfd\xfc', b'&AP8A,gD9APw-'],
         ['~peter/mail/\u65e5\u672c\u8a9e/\u53f0\u5317',
-         '~peter/mail/&ZeVnLIqe-/&U,BTFw-'], # example from RFC 2060
-        ['\x00foo', '&AAA-foo'],
+         b'~peter/mail/&ZeVnLIqe-/&U,BTFw-'], # example from RFC 2060
+        ['\x00foo', b'&AAA-foo'],
     ]
 
     def test_encode(self):
         for (input, output) in self.tests:
             encoded = encode(input)
-            self.assertIsInstance(encoded, text_type)
+            self.assertIsInstance(encoded, binary_type)
             self.assertEqual(encoded, output)
 
 
@@ -38,18 +36,15 @@ class IMAP4UTF7TestCase(unittest.TestCase):
             self.assertIsInstance(decoded, text_type)
             self.assertEqual(input, decoded)
 
-    def test_printableSingletons(self):
+    def test_printable_singletons(self):
         """
         The IMAP4 modified UTF-7 implementation encodes all printable
         characters which are in ASCII using the corresponding ASCII byte.
         """
         # All printables represent themselves
         for o in list(range(0x20, 0x26)) + list(range(0x27, 0x7f)):
-            self.assertEqual(unichr(o), encode(chr(o)))
-            self.assertEqual(unichr(o), decode(unichr(o)))
-        self.assertEqual(encode('&'), '&-')
-        self.assertEqual(encode('&'), '&-')
+            self.assertEqual(int2byte(o), encode(unichr(o)))
+            self.assertEqual(unichr(o), decode(int2byte(o)))
+        self.assertEqual(encode('&'), b'&-')
+        self.assertEqual(encode('&'), b'&-')
         self.assertEqual(decode(b'&-'), '&')
-
-if __name__ == '__main__':
-    unittest.main()
index 67b5afec35b826a46c9791474a7d8590023d2bc2..48a83fbfd66ad9f89fdafdd919ad051dad3e87c5 100644 (file)
@@ -25,7 +25,7 @@ class TestListFolders(IMAPClientTest):
         folders = self.client.list_folders('foo', 'bar')
 
         self.client._imap._simple_command.assert_called_once_with(
-            'LIST', '"foo"', '"bar"')
+            'LIST', b'"foo"', b'"bar"')
         self.assertEqual(self.client._proc_folder_list.call_args, ((sentinel.folder_data,), {}))
         self.assertTrue(folders is sentinel.folder_list)
 
@@ -37,7 +37,7 @@ class TestListFolders(IMAPClientTest):
         folders = self.client.list_sub_folders('foo', 'bar')
 
         self.client._imap._simple_command.assert_called_once_with(
-            'LSUB', '"foo"', '"bar"')
+            'LSUB', b'"foo"', b'"bar"')
         self.assertEqual(self.client._proc_folder_list.call_args, ((sentinel.folder_data,), {}))
         self.assertTrue(folders is sentinel.folder_list)
 
@@ -61,9 +61,9 @@ class TestListFolders(IMAPClientTest):
 
         folders = self.client.list_folders('foo', 'bar')
 
-        self.client._imap._simple_command.assert_called_once_with('LIST', '"foo"', '"bar"')
-        self.assertEqual(folders, [(('\\HasNoChildren',), '/', 'A'),
-                                   (('\\HasNoChildren',), '/', 'Hello\xffworld')])
+        self.client._imap._simple_command.assert_called_once_with('LIST', b'"foo"', b'"bar"')
+        self.assertEqual(folders, [((b'\\HasNoChildren',), b'/', 'A'),
+                                   ((b'\\HasNoChildren',), b'/', 'Hello\xffworld')])
 
     def test_folder_encode_off(self):
         self.client.folder_encode = False
@@ -77,61 +77,61 @@ class TestListFolders(IMAPClientTest):
         folders = self.client.list_folders('foo', 'bar')
 
         self.client._imap._simple_command.assert_called_once_with('LIST', '"foo"', '"bar"')
-        self.assertEqual(folders, [(('\\HasNoChildren',), '/', 'A'),
-                                   (('\\HasNoChildren',), '/', 'Hello&AP8-world')])
+        self.assertEqual(folders, [((b'\\HasNoChildren',), b'/', b'A'),
+                                   ((b'\\HasNoChildren',), b'/', b'Hello&AP8-world')])
 
     def test_simple(self):
-        folders = self.client._proc_folder_list(['(\\HasNoChildren) "/" "A"',
-                                                 '(\\HasNoChildren) "/" "Foo Bar"',
+        folders = self.client._proc_folder_list([b'(\\HasNoChildren) "/" "A"',
+                                                 b'(\\HasNoChildren) "/" "Foo Bar"',
                                                  ])
-        self.assertEqual(folders, [(('\\HasNoChildren',), '/', 'A',),
-                                   (('\\HasNoChildren',), '/', 'Foo Bar')])
+        self.assertEqual(folders, [((b'\\HasNoChildren',), b'/', 'A',),
+                                   ((b'\\HasNoChildren',), b'/', 'Foo Bar')])
 
 
     def test_without_quotes(self):
-        folders = self.client._proc_folder_list(['(\\HasNoChildren) "/" A',
-                                                 '(\\HasNoChildren) "/" B',
-                                                 '(\\HasNoChildren) "/" C',
+        folders = self.client._proc_folder_list([b'(\\HasNoChildren) "/" A',
+                                                 b'(\\HasNoChildren) "/" B',
+                                                 b'(\\HasNoChildren) "/" C',
                                                  ])
-        self.assertEqual(folders, [(('\\HasNoChildren',), '/', 'A'),
-                                   (('\\HasNoChildren',), '/', 'B'),
-                                   (('\\HasNoChildren',), '/', 'C')])
+        self.assertEqual(folders, [((b'\\HasNoChildren',), b'/', 'A'),
+                                   ((b'\\HasNoChildren',), b'/', 'B'),
+                                   ((b'\\HasNoChildren',), b'/', 'C')])
 
     def test_unquoted_numeric_folder_name(self):
         # Some IMAP implementations do this
-        folders = self.client._proc_folder_list(['(\\HasNoChildren) "/" 123'])
-        self.assertEqual(folders, [(('\\HasNoChildren',), '/', '123')])
+        folders = self.client._proc_folder_list([b'(\\HasNoChildren) "/" 123'])
+        self.assertEqual(folders, [((b'\\HasNoChildren',), b'/', '123')])
 
     def test_mixed(self):
-        folders = self.client._proc_folder_list(['(\\HasNoChildren) "/" Alpha',
-                                                 '(\\HasNoChildren) "/" "Foo Bar"',
-                                                 '(\\HasNoChildren) "/" C',
+        folders = self.client._proc_folder_list([b'(\\HasNoChildren) "/" Alpha',
+                                                 b'(\\HasNoChildren) "/" "Foo Bar"',
+                                                 b'(\\HasNoChildren) "/" C',
                                                  ])
-        self.assertEqual(folders, [(('\\HasNoChildren',), '/', 'Alpha'),
-                                   (('\\HasNoChildren',), '/', 'Foo Bar'),
-                                   (('\\HasNoChildren',), '/', 'C')])
+        self.assertEqual(folders, [((b'\\HasNoChildren',), b'/', 'Alpha'),
+                                   ((b'\\HasNoChildren',), b'/', 'Foo Bar'),
+                                   ((b'\\HasNoChildren',), b'/', 'C')])
 
 
     def test_funky_characters(self):
-        folders = self.client._proc_folder_list([('(\\NoInferiors \\UnMarked) "/" {5}', 'bang\xff'),
-                                                 '',
-                                                 '(\\HasNoChildren \\UnMarked) "/" "INBOX"'])
-        self.assertEqual(folders, [(('\\NoInferiors', '\\UnMarked'), "/", 'bang\xff'),
-                                   (('\\HasNoChildren', '\\UnMarked'), "/", 'INBOX')])
+        folders = self.client._proc_folder_list([(b'(\\NoInferiors \\UnMarked) "/" {5}', 'bang\xff'),
+                                                 b'',
+                                                 b'(\\HasNoChildren \\UnMarked) "/" "INBOX"'])
+        self.assertEqual(folders, [((b'\\NoInferiors', b'\\UnMarked'), b"/", 'bang\xff'),
+                                   ((b'\\HasNoChildren', b'\\UnMarked'), b"/", 'INBOX')])
 
 
     def test_quoted_specials(self):
-        folders = self.client._proc_folder_list([r'(\HasNoChildren) "/" "Test \"Folder\""',
-                                                 r'(\HasNoChildren) "/" "Left\"Right"',
-                                                 r'(\HasNoChildren) "/" "Left\\Right"',
-                                                 r'(\HasNoChildren) "/" "\"Left Right\""',
-                                                 r'(\HasNoChildren) "/" "\"Left\\Right\""',
+        folders = self.client._proc_folder_list([br'(\HasNoChildren) "/" "Test \"Folder\""',
+                                                 br'(\HasNoChildren) "/" "Left\"Right"',
+                                                 br'(\HasNoChildren) "/" "Left\\Right"',
+                                                 br'(\HasNoChildren) "/" "\"Left Right\""',
+                                                 br'(\HasNoChildren) "/" "\"Left\\Right\""',
                                                  ])
-        self.assertEqual(folders, [(('\\HasNoChildren',), '/', 'Test "Folder"'),
-                                   (('\\HasNoChildren',), '/', 'Left\"Right'),
-                                   (('\\HasNoChildren',), '/', r'Left\Right'),
-                                   (('\\HasNoChildren',), '/', r'"Left Right"'),
-                                   (('\\HasNoChildren',), '/', r'"Left\Right"'),
+        self.assertEqual(folders, [((b'\\HasNoChildren',), b'/', 'Test "Folder"'),
+                                   ((b'\\HasNoChildren',), b'/', 'Left\"Right'),
+                                   ((b'\\HasNoChildren',), b'/', r'Left\Right'),
+                                   ((b'\\HasNoChildren',), b'/', r'"Left Right"'),
+                                   ((b'\\HasNoChildren',), b'/', r'"Left\Right"'),
                                    ])
 
     def test_empty_response(self):
@@ -139,8 +139,8 @@ class TestListFolders(IMAPClientTest):
 
 
     def test_blanks(self):
-        folders = self.client._proc_folder_list(['', None, r'(\HasNoChildren) "/" "last"'])
-        self.assertEqual(folders, [((r'\HasNoChildren',), '/', 'last')])
+        folders = self.client._proc_folder_list(['', None, br'(\HasNoChildren) "/" "last"'])
+        self.assertEqual(folders, [((br'\HasNoChildren',), b'/', 'last')])
 
 
 class TestSelectFolder(IMAPClientTest):
@@ -166,19 +166,19 @@ class TestSelectFolder(IMAPClientTest):
         result = self.client.select_folder(b'folder_name', sentinel.readonly)
 
         self.client._command_and_check.assert_called_once_with('select',
-                                                               '"folder_name"',
+                                                               b'"folder_name"',
                                                                sentinel.readonly)
         self.maxDiff = 99999
         self.assertEqual(result, {
-            'EXISTS': 3,
-            'RECENT': 0,
-            'UIDNEXT': 1281,
-            'UIDVALIDITY': 631062293,
-            'HIGHESTMODSEQ': 127110,
-            'FLAGS': (r'\Flagged', r'\Deleted', 'abc', '[foo]/bar', 'def'),
-            'PERMANENTFLAGS': (r'\Flagged', r'\Deleted', 'abc', '[foo]/bar', 'def', r'\*'),
-            'READ-WRITE': True,
-            'OTHER': ['blah']
+            b'EXISTS': 3,
+            b'RECENT': 0,
+            b'UIDNEXT': 1281,
+            b'UIDVALIDITY': 631062293,
+            b'HIGHESTMODSEQ': 127110,
+            b'FLAGS': (br'\Flagged', br'\Deleted', b'abc', b'[foo]/bar', b'def'),
+            b'PERMANENTFLAGS': (br'\Flagged', br'\Deleted', b'abc', b'[foo]/bar', b'def', br'\*'),
+            b'READ-WRITE': True,
+            b'OTHER': [b'blah']
         })
 
 
@@ -191,7 +191,7 @@ class TestAppend(IMAPClientTest):
         self.client.append('foobar', msg, ['FLAG', 'WAVE'], None)
 
         self.client._imap.append.assert_called_with(
-            '"foobar"', '(FLAG WAVE)', None, b'hi')
+            b'"foobar"', b'(FLAG WAVE)', None, b'hi')
 
     @patch('imapclient.imapclient.datetime_to_imap')
     def test_with_msg_time(self, datetime_to_imap):
@@ -204,7 +204,7 @@ class TestAppend(IMAPClientTest):
 
         self.assertTrue(datetime_to_imap.called)
         self.client._imap.append.assert_called_with(
-            '"foobar"', '(FLAG WAVE)', '"somedate"', msg)
+            b'"foobar"', b'(FLAG WAVE)', '"somedate"', msg)
 
 
 class TestAclMethods(IMAPClientTest):
@@ -212,17 +212,17 @@ class TestAclMethods(IMAPClientTest):
     def test_getacl(self):
         self.client._imap.getacl.return_value = ('OK', [b'INBOX Fred rwipslda Sally rwip'])
         acl = self.client.getacl('INBOX')
-        self.assertSequenceEqual(acl, [('Fred', 'rwipslda'), ('Sally', 'rwip')])
+        self.assertSequenceEqual(acl, [(b'Fred', b'rwipslda'), (b'Sally', b'rwip')])
 
     def test_setacl(self):
         self.client._imap.setacl.return_value = ('OK', [b"SETACL done"])
 
         response = self.client.setacl('folder', sentinel.who, sentinel.what)
 
-        self.client._imap.setacl.assert_called_with('"folder"',
+        self.client._imap.setacl.assert_called_with(b'"folder"',
                                                     sentinel.who,
                                                     sentinel.what)
-        self.assertEqual(response, "SETACL done")
+        self.assertEqual(response, b"SETACL done")
 
 
 class TestIdleAndNoop(IMAPClientTest):
@@ -245,9 +245,9 @@ class TestIdleAndNoop(IMAPClientTest):
         def fake_get_line():
             count = six.next(counter)
             if count == 0:
-                return '* 1 EXISTS'
+                return b'* 1 EXISTS'
             elif count == 1:
-                return '* 0 EXPUNGE'
+                return b'* 0 EXPUNGE'
             else:
                 raise socket.timeout
         self.client._imap._get_line = fake_get_line
@@ -258,7 +258,7 @@ class TestIdleAndNoop(IMAPClientTest):
         self.assertListEqual(mock_sock.method_calls,
                              [('setblocking', (0,), {}),
                               ('setblocking', (1,), {})])
-        self.assertListEqual([(1, 'EXISTS'), (0, 'EXPUNGE')], responses)
+        self.assertListEqual([(1, b'EXISTS'), (0, b'EXPUNGE')], responses)
 
     @patch('imapclient.imapclient.select.select')
     def test_idle_check_timeout(self, mock_select):
@@ -294,7 +294,7 @@ class TestIdleAndNoop(IMAPClientTest):
         self.assertListEqual(mock_sock.method_calls,
                              [('setblocking', (0,), {}),
                               ('setblocking', (1,), {})])
-        self.assertListEqual([(99, 'EXISTS')], responses)
+        self.assertListEqual([(99, b'EXISTS')], responses)
 
     def test_idle_done(self):
         self.client._idle_tag = sentinel.tag
@@ -330,18 +330,16 @@ class TestIdleAndNoop(IMAPClientTest):
         def fake_get_response():
             count = six.next(counter)
             if count == 0:
-                return '* 99 EXISTS'
-            client._imap.tagged_commands[sentinel.tag] = ('OK', ['Idle done'])
+                return b'* 99 EXISTS'
+            client._imap.tagged_commands[sentinel.tag] = ('OK', [b'Idle done'])
         client._imap._get_response = fake_get_response
-            
-        text, responses = client._consume_until_tagged_response(sentinel.tag,
-                                                                'IDLE')
+
+        text, responses = client._consume_until_tagged_response(sentinel.tag, b'IDLE')
         self.assertEqual(client._imap.tagged_commands, {})
-        self.assertEqual(text, 'Idle done')
-        self.assertListEqual([(99, 'EXISTS')], responses)
+        self.assertEqual(text, b'Idle done')
+        self.assertListEqual([(99, b'EXISTS')], responses)
 
 
-                         
 class TestDebugLogging(IMAPClientTest):
 
     def test_default_is_stderr(self):
@@ -421,6 +419,10 @@ class TestNamespace(IMAPClientTest):
         self.set_return(b'(("FOO." "/")) NIL NIL')
         self.assertEqual(self.client.namespace(), ((('FOO.', '/'),), None, None))
 
+    def test_folder_decoding(self):
+        self.set_return(b'(("&AP8-." "/")) NIL NIL')
+        self.assertEqual(self.client.namespace(), ((('\xff.', '/'),), None, None))
+
     def test_other_only(self):
         self.set_return(b'NIL NIL (("" "."))')
         self.assertEqual(self.client.namespace(), (None, None, (("", "."),)))
@@ -441,22 +443,22 @@ class TestCapabilities(IMAPClientTest):
         self.client._imap.capabilities = ('FOO', 'BAR')
         self.client._imap.untagged_responses = {}
 
-        self.assertEqual(self.client.capabilities(), ('FOO', 'BAR'))
+        self.assertEqual(self.client.capabilities(), (b'FOO', b'BAR'))
 
     def test_server_returned_capability_after_auth(self):
-        self.client._imap.capabilities = ('FOO',)
-        self.client._imap.untagged_responses = {'CAPABILITY': ['FOO MORE']}
+        self.client._imap.capabilities = (b'FOO',)
+        self.client._imap.untagged_responses = {'CAPABILITY': [b'FOO MORE']}
 
         self.assertEqual(self.client._cached_capabilities, None)
-        self.assertEqual(self.client.capabilities(), ('FOO', 'MORE'))
-        self.assertEqual(self.client._cached_capabilities, ('FOO', 'MORE'))
+        self.assertEqual(self.client.capabilities(), (b'FOO', b'MORE'))
+        self.assertEqual(self.client._cached_capabilities, (b'FOO', b'MORE'))
 
     def test_caching(self):
         self.client._imap.capabilities = ('FOO',)
         self.client._imap.untagged_responses = {}
-        self.client._cached_capabilities = ('FOO', 'MORE')
+        self.client._cached_capabilities = (b'FOO', b'MORE')
 
-        self.assertEqual(self.client.capabilities(), ('FOO', 'MORE'))
+        self.assertEqual(self.client.capabilities(), (b'FOO', b'MORE'))
 
     def test_post_auth_request(self):
         self.client._imap.capabilities = ('FOO',)
@@ -464,14 +466,24 @@ class TestCapabilities(IMAPClientTest):
         self.client._imap.state = 'SELECTED'
         self.client._imap.capability.return_value = ('OK', [b'FOO BAR'])
 
-        self.assertEqual(self.client.capabilities(), ('FOO', 'BAR'))
-        self.assertEqual(self.client._cached_capabilities, ('FOO', 'BAR'))
+        self.assertEqual(self.client.capabilities(), (b'FOO', b'BAR'))
+        self.assertEqual(self.client._cached_capabilities, (b'FOO', b'BAR'))
+
+    def test_has_capability(self):
+        self.client._cached_capabilities = (b'FOO', b'MORE')
+
+        self.assertTrue(self.client.has_capability(b'FOO'))
+        self.assertTrue(self.client.has_capability(b'foo'))
+        self.assertFalse(self.client.has_capability(b'BAR'))
 
+        self.assertTrue(self.client.has_capability('FOO'))
+        self.assertTrue(self.client.has_capability('foo'))
+        self.assertFalse(self.client.has_capability('BAR'))
 
 class TestThread(IMAPClientTest):
 
     def test_thread_without_uid(self):
-        self.client._cached_capabilities = ('THREAD=REFERENCES',)
+        self.client._cached_capabilities = (b'THREAD=REFERENCES',)
         self.client.use_uid = False
         self.client._imap.thread.return_value = ('OK', [b'(1 2)(3)(4 5 6)'])
 
@@ -480,7 +492,7 @@ class TestThread(IMAPClientTest):
         self.assertSequenceEqual(threads, ((1, 2), (3,), (4, 5, 6)))
 
     def test_thread_with_uid(self):
-        self.client._cached_capabilities = ('THREAD=REFERENCES',)
+        self.client._cached_capabilities = (b'THREAD=REFERENCES',)
         self.client.use_uid = True
         self.client._imap.uid.return_value = ('OK', [b'(1 2)(3)(4 5 6)'])
 
@@ -489,26 +501,26 @@ class TestThread(IMAPClientTest):
         self.assertSequenceEqual(threads, ((1, 2), (3,), (4, 5, 6)))
 
     def test_no_support(self):
-        self.client._cached_capabilities = ('NOT-THREAD',)
+        self.client._cached_capabilities = (b'NOT-THREAD',)
         self.assertRaises(ValueError, self.client.thread)
 
     def test_no_support2(self):
-        self.client._cached_capabilities = ('THREAD=FOO',)
+        self.client._cached_capabilities = (b'THREAD=FOO',)
         self.assertRaises(ValueError, self.client.thread)
 
     def test_all_args_with_uid(self):
-        self.client._cached_capabilities = ('THREAD=FOO',)
+        self.client._cached_capabilities = (b'THREAD=FOO',)
         self.client._imap.uid.return_value = ('OK', [])
 
         self.client.thread(algorithm='FOO', criteria='STUFF', charset='ASCII')
 
-        self.client._imap.uid.assert_called_once_with('thread', 'FOO', 'ASCII', '(STUFF)')
+        self.client._imap.uid.assert_called_once_with('thread', b'FOO', b'ASCII', b'(STUFF)')
 
     def test_all_args_without_uid(self):
         self.client.use_uid = False
-        self.client._cached_capabilities = ('THREAD=FOO',)
+        self.client._cached_capabilities = (b'THREAD=FOO',)
         self.client._imap.thread.return_value = ('OK', [])
 
         self.client.thread(algorithm='FOO', criteria='STUFF', charset='ASCII')
 
-        self.client._imap.thread.assert_called_once_with('FOO', 'ASCII','(STUFF)')
+        self.client._imap.thread.assert_called_once_with(b'FOO', b'ASCII', b'(STUFF)')
index 2440a6b9e89af1b6cffd42972ed7abd26a6080cb..dcd454dbd8b80ecea09bc58fc9d7abfb3f7d0183 100644 (file)
@@ -12,7 +12,7 @@ class TestSearch(IMAPClientTest):
 
         result = self.client.search('FOO')
 
-        self.client._imap.uid.assert_called_once_with('SEARCH', '(FOO)')
+        self.client._imap.uid.assert_called_once_with('SEARCH', b'(FOO)')
         self.assertEqual(result, [1, 2, 44])
 
     def test_without_uid(self):
@@ -21,7 +21,7 @@ class TestSearch(IMAPClientTest):
 
         result = self.client.search('FOO')
 
-        self.client._imap.search.assert_called_once_with(None, '(FOO)')
+        self.client._imap.search.assert_called_once_with(None, b'(FOO)')
         self.assertEqual(result, [1, 2, 44])
 
     def test_with_uid_with_charset(self):
@@ -32,8 +32,8 @@ class TestSearch(IMAPClientTest):
 
         self.client._imap.uid.assert_called_once_with(
             'SEARCH',
-            'CHARSET', 'UTF9',
-            '(FOO)')
+            b'CHARSET', 'UTF9',
+            b'(FOO)')
         self.assertEqual(result, [1, 2, 44])
 
     def test_without_uid_with_charset(self):
@@ -42,7 +42,7 @@ class TestSearch(IMAPClientTest):
 
         result = self.client.search('FOO', 'UTF9')
 
-        self.client._imap.search.assert_called_once_with('UTF9', '(FOO)')
+        self.client._imap.search.assert_called_once_with('UTF9', b'(FOO)')
         self.assertEqual(result, [1, 2, 44])
 
     def test_with_multiple_criteria_and_charset(self):
@@ -51,7 +51,7 @@ class TestSearch(IMAPClientTest):
 
         result = self.client.search(['FOO', 'BAR'], 'UTF9')
 
-        self.client._imap.search.assert_called_once_with('UTF9', '(FOO)', '(BAR)')
+        self.client._imap.search.assert_called_once_with('UTF9', b'(FOO)', b'(BAR)')
         self.assertEqual(result, [1, 2, 44])
 
     def test_error_from_server(self):
@@ -59,7 +59,7 @@ class TestSearch(IMAPClientTest):
 
         self.assertRaisesRegex(IMAPClient.Error,
                                'bad karma',
-                               self.client.search, 'FOO')
+                               self.client.search, b'FOO')
 
 
 class TestGmailSearch(IMAPClientTest):
@@ -70,7 +70,7 @@ class TestGmailSearch(IMAPClientTest):
 
         result = self.client.gmail_search('FOO')
 
-        self.client._imap.uid.assert_called_once_with('SEARCH', 'X-GM-RAW')
+        self.client._imap.uid.assert_called_once_with('SEARCH', b'X-GM-RAW')
         self.assertEqual(self.client._imap.literal, b'FOO')
         self.assertEqual(result, [1, 2, 44])
 
@@ -80,7 +80,7 @@ class TestGmailSearch(IMAPClientTest):
 
         result = self.client.gmail_search('FOO')
 
-        self.client._imap.search.assert_called_once_with(None, 'X-GM-RAW')
+        self.client._imap.search.assert_called_once_with(None, b'X-GM-RAW')
         self.assertEqual(self.client._imap.literal, b'FOO')
         self.assertEqual(result, [1, 2, 44])
 
@@ -92,8 +92,8 @@ class TestGmailSearch(IMAPClientTest):
 
         self.client._imap.uid.assert_called_once_with(
             'SEARCH',
-            'CHARSET', 'UTF8',
-            'X-GM-RAW')
+            b'CHARSET', 'UTF8',
+            b'X-GM-RAW')
         self.assertEqual(self.client._imap.literal, b'\xe2\x98\xa0')
         self.assertEqual(result, [1, 2, 44])
 
@@ -103,7 +103,7 @@ class TestGmailSearch(IMAPClientTest):
 
         result = self.client.gmail_search('\u2620', 'UTF8')
 
-        self.client._imap.search.assert_called_once_with('UTF8', 'X-GM-RAW')
+        self.client._imap.search.assert_called_once_with('UTF8', b'X-GM-RAW')
         self.assertEqual(self.client._imap.literal, b'\xe2\x98\xa0')
         self.assertEqual(result, [1, 2, 44])
 
@@ -112,4 +112,4 @@ class TestGmailSearch(IMAPClientTest):
 
         self.assertRaisesRegex(IMAPClient.Error,
                                'bad karma',
-                               self.client.gmail_search, 'FOO')
+                               self.client.gmail_search, b'FOO')
index 8d789d0845c8fda7af698c102d58c0fd38413a9a..13cbaa7f411c519801664b980058af92722b515f 100644 (file)
@@ -26,22 +26,22 @@ class Test_normalise_text_list(unittest.TestCase):
         self.assertEqual(normalise_text_list(items), expected)
 
     def test_unicode(self):
-        self.check('Foo', ['Foo'])
+        self.check('Foo', [b'Foo'])
 
     def test_binary(self):
-        self.check(b'FOO', ['FOO'])
+        self.check(b'FOO', [b'FOO'])
 
     def test_tuple(self):
-        self.check(('FOO', 'BAR'), ['FOO', 'BAR'])
+        self.check(('FOO', 'BAR'), [b'FOO', b'BAR'])
 
     def test_list(self):
-        self.check(['FOO', 'BAR'], ['FOO', 'BAR'])
+        self.check(['FOO', 'BAR'], [b'FOO', b'BAR'])
 
     def test_iter(self):
-        self.check(iter(['FOO', 'BAR']), ['FOO', 'BAR'])
+        self.check(iter(['FOO', 'BAR']), [b'FOO', b'BAR'])
 
     def test_mixed_list(self):
-        self.check(['FOO', b'Bar'], ['FOO', 'Bar'])
+        self.check(['FOO', b'Bar'], [b'FOO', b'Bar'])
 
 class Test_seq_to_parenstr(unittest.TestCase):
 
@@ -49,22 +49,22 @@ class Test_seq_to_parenstr(unittest.TestCase):
         self.assertEqual(seq_to_parenstr(items), expected)
 
     def test_unicode(self):
-        self.check('foO', '(foO)')
+        self.check('foO', b'(foO)')
 
     def test_binary(self):
-        self.check(b'Foo', '(Foo)')
+        self.check(b'Foo', b'(Foo)')
 
     def test_tuple(self):
-        self.check(('FOO', 'BAR'), '(FOO BAR)')
+        self.check(('FOO', 'BAR'), b'(FOO BAR)')
 
     def test_list(self):
-        self.check(['FOO', 'BAR'], '(FOO BAR)')
+        self.check(['FOO', 'BAR'], b'(FOO BAR)')
 
     def test_iter(self):
-        self.check(iter(['FOO', 'BAR']), '(FOO BAR)')
+        self.check(iter(['FOO', 'BAR']), b'(FOO BAR)')
 
     def test_mixed_list(self):
-        self.check(['foo', b'BAR'], '(foo BAR)')
+        self.check(['foo', b'BAR'], b'(foo BAR)')
 
 class Test_seq_to_parenstr_upper(unittest.TestCase):
 
@@ -72,22 +72,22 @@ class Test_seq_to_parenstr_upper(unittest.TestCase):
         self.assertEqual(seq_to_parenstr_upper(items), expected)
 
     def test_unicode(self):
-        self.check('foO', '(FOO)')
+        self.check('foO', b'(FOO)')
 
     def test_binary(self):
-        self.check(b'Foo', '(FOO)')
+        self.check(b'Foo', b'(FOO)')
 
     def test_tuple(self):
-        self.check(('foo', 'BAR'), '(FOO BAR)')
+        self.check(('foo', 'BAR'), b'(FOO BAR)')
 
     def test_list(self):
-        self.check(['FOO', 'bar'], '(FOO BAR)')
+        self.check(['FOO', 'bar'], b'(FOO BAR)')
 
     def test_iter(self):
-        self.check(iter(['FOO', 'BaR']), '(FOO BAR)')
+        self.check(iter(['FOO', 'BaR']), b'(FOO BAR)')
 
     def test_mixed_list(self):
-        self.check(['foo', b'BAR'], '(FOO BAR)')
+        self.check(['foo', b'BAR'], b'(FOO BAR)')
 
 class Test_messages_to_str(unittest.TestCase):
 
@@ -95,28 +95,28 @@ class Test_messages_to_str(unittest.TestCase):
         self.assertEqual(messages_to_str(items), expected)
 
     def test_int(self):
-        self.check(123, '123')
+        self.check(123, b'123')
 
     def test_unicode(self):
-        self.check('123', '123')
+        self.check('123', b'123')
 
     def test_unicode_non_numeric(self):
-        self.check('2:*', '2:*')
+        self.check('2:*', b'2:*')
 
     def test_binary(self):
-        self.check(b'123', '123')
+        self.check(b'123', b'123')
 
     def test_binary_non_numeric(self):
-        self.check(b'2:*', '2:*')
+        self.check(b'2:*', b'2:*')
 
     def test_tuple(self):
-        self.check((123, 99), '123,99')
+        self.check((123, 99), b'123,99')
 
     def test_mixed_list(self):
-        self.check(['2:3', 123, b'44'], '2:3,123,44')
+        self.check(['2:3', 123, b'44'], b'2:3,123,44')
 
     def test_iter(self):
-        self.check(iter([123, 99]), '123,99')
+        self.check(iter([123, 99]), b'123,99')
 
 class Test_normalise_search_criteria(unittest.TestCase):
 
@@ -124,19 +124,19 @@ class Test_normalise_search_criteria(unittest.TestCase):
         self.assertEqual(normalise_search_criteria(criteria), expected)
 
     def test_unicode(self):
-        self.check('Foo', ['(Foo)'])
+        self.check('Foo', [b'(Foo)'])
 
     def test_binary(self):
-        self.check(b'FOO', ['(FOO)'])
+        self.check(b'FOO', [b'(FOO)'])
 
     def test_tuple(self):
-        self.check(('FOO', 'BAR'), ['(FOO)', '(BAR)'])
+        self.check(('FOO', 'BAR'), [b'(FOO)', b'(BAR)'])
 
     def test_list(self):
-        self.check(['FOO', 'BAR'], ['(FOO)', '(BAR)'])
+        self.check(['FOO', 'BAR'], [b'(FOO)', b'(BAR)'])
 
     def test_mixed_list(self):
-        self.check(['FOO', b'BAR'], ['(FOO)', '(BAR)'])
+        self.check(['FOO', b'BAR'], [b'(FOO)', b'(BAR)'])
 
     def test_None(self):
         self.assertRaises(ValueError, normalise_search_criteria, None)
index 27f8a0726384e086285a5c24cd47b3d0c5579e4d..660f0e8a22e2143ac8bb777bf44a70a6566a613e 100644 (file)
@@ -14,12 +14,4 @@ class TestableIMAPClient(IMAPClient):
         super(TestableIMAPClient, self).__init__('somehost')
 
     def _create_IMAP4(self):
-        mock_IMAP4 = Mock()
-        mock_IMAP4._quote = self._quote
-        return mock_IMAP4
-
-    def _quote(self, arg):
-        """The real code from IMAP4._quote."""
-        arg = arg.replace('\\', '\\\\')
-        arg = arg.replace('"', '\\"')
-        return '"%s"' % arg
+        return Mock()