Still plenty of clean up and testing to do (see XXX and TODO).
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
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')
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:
# 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
# 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,
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.
# 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
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:
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)
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)
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))
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.
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):
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')
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):
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')
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)
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()
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)
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)
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
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):
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):
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']
})
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):
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):
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):
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
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):
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
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):
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, (("", "."),)))
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',)
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)'])
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)'])
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)')
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):
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):
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):
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):
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):
self.assertRaisesRegex(IMAPClient.Error,
'bad karma',
- self.client.search, 'FOO')
+ self.client.search, b'FOO')
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])
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])
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])
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])
self.assertRaisesRegex(IMAPClient.Error,
'bad karma',
- self.client.gmail_search, 'FOO')
+ self.client.gmail_search, b'FOO')
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):
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):
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):
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):
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)
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()