From 81991f4573247f373403b41982370e700de8e01e Mon Sep 17 00:00:00 2001 From: Menno Smits Date: Tue, 4 Aug 2015 17:16:03 +1200 Subject: [PATCH] Fixed charset handling for search, sort and thread Lots of awkward handling added to deal with imaplib unicode handling inconsistencies and variation in imaplib between Python versions. Fixes #93. --- NEWS.rst | 17 ++++ imapclient/imapclient.py | 134 ++++++++++++++++--------- imapclient/livetest.py | 55 ++++++++-- imapclient/test/test_imapclient.py | 21 +++- imapclient/test/test_search.py | 52 +++++----- imapclient/test/test_sort.py | 74 ++++++++++++++ imapclient/test/test_util_functions.py | 25 +++-- 7 files changed, 282 insertions(+), 96 deletions(-) create mode 100644 imapclient/test/test_sort.py diff --git a/NEWS.rst b/NEWS.rst index 3a1a576..0842868 100644 --- a/NEWS.rst +++ b/NEWS.rst @@ -23,6 +23,23 @@ XXX XXX Thank people who contributed (Chris?) +Fixed charset handling for search, sort and thread +-------------------------------------------------- +The handling of the *charset* argument for the search, sort and thread +methods has been fixed. + +Any unicode criteria given will now be encoded using the supplied +charset. The charset must refer to an encoding that is capable of +handling the criteria's characters or an error will occur. + +Any criteria given as bytes will not be changed by IMAPClient, but the +provided charset will still be passed to the IMAP server. The encoding +referred to by *charset* should match the actual encoding used for the +critera. + +The tests and documentation for search, sort and thread has updated to +account for these changes and have also been generally improved. + Performance optimsation for parsing message id lists ---------------------------------------------------- A short circuit is now used when parsing a list of message ids which diff --git a/imapclient/imapclient.py b/imapclient/imapclient.py index c329297..c20e097 100644 --- a/imapclient/imapclient.py +++ b/imapclient/imapclient.py @@ -646,8 +646,16 @@ class IMAPClient(object): 'UNSEEN' 'SINCE 1-Feb-2011' - *charset* specifies the character set of the strings in the - criteria. It defaults to US-ASCII. + *charset* specifies the character set of the criteria. It + defaults to US-ASCII as this is the only charset that a server + is required to support by the RFC. + + Any criteria specified using unicode will be encoded as per + *charset*. Specifying a unicode criteria that can not be + encoded using *charset* will result in an error. + + Any criteria specified using bytes will not be modified but + should use an encoding that matches *charset*. See :rfc:`3501#section-6.4.4` for more details. @@ -656,7 +664,8 @@ class IMAPClient(object): search response (i.e. if a MODSEQ criteria was included in the search). """ - return self._search(normalise_search_criteria(criteria), charset) + criteria = normalise_search_criteria(criteria, charset) + return self._search(criteria, charset) def gmail_search(self, query, charset=None): """Search using Gmail's X-GM-RAW attribute. @@ -665,56 +674,34 @@ class IMAPClient(object): example: ``has:attachment in:unread`` This method only works for IMAP servers that support X-GM-RAW, - which is only likely to be Gmail. + which is only like to be Gmail. See https://developers.google.com/gmail/imap_extensions#extension_of_the_search_command_x-gm-raw for more info. - *charset* specifies the character set used to encode the - search string. It defaults to US-ASCII. + *charset* specifies the encoding for the query string. The + documentation for *charset* for :py:meth:`.search` + also applies here. """ - # the the query is sent as a literal to allow for 7-bit query strings - if isinstance(query, string_types): - query = query.encode(charset or 'us-ascii') - self._imap.literal = query + # the the query is sent as a literal to allow for 8-bit query strings + self._imap.literal = to_bytes(query, charset or 'us-ascii') return self._search([b'X-GM-RAW'], charset) def _search(self, criteria, charset): + charset = to_bytes(charset) + if self.use_uid: args = [] if charset: args.extend([b'CHARSET', charset]) args.extend(criteria) - typ, data = self._imap.uid('SEARCH', *args) + typ, data = self._imap.uid('search' if PY3 else b'search', *args) else: typ, data = self._imap.search(charset, *criteria) - self._checkok('search', typ, data) + self._checkok(b'search', typ, data) return parse_message_list(data) - def thread(self, algorithm='REFERENCES', criteria='ALL', charset='UTF-8'): - """Return a list of messages threads matching *criteria*. - - Each thread is a list of messages ids. - - See :rfc:`5256` for more details. - """ - algorithm = to_bytes(algorithm) - if not self.has_capability(b'THREAD=' + algorithm): - raise ValueError('server does not support %s threading algorithm' - % algorithm) - - if not criteria: - raise ValueError('no criteria specified') - - args = [algorithm] - if charset: - args.append(to_bytes(charset)) - args.extend(normalise_search_criteria(criteria)) - - data = self._command_and_check('thread', *args, uid=True) - return parse_response(data) - def sort(self, sort_criteria, criteria='ALL', charset='UTF-8'): """Return a list of message ids sorted by *sort_criteria* and optionally filtered by *criteria*. @@ -725,26 +712,58 @@ class IMAPClient(object): REVERSE SIZE SUBJECT - The *criteria* argument is as per search(). + The *criteria* and *charset* arguments are as per + :py:meth:`.search`. See :rfc:`5256` for full details. Note that SORT is an extension to the IMAP4 standard so it may not be supported by all IMAP servers. """ - if not criteria: - raise ValueError('no criteria specified') - if not self.has_capability('SORT'): raise self.Error('The server does not support the SORT extension') - ids = self._command_and_check('sort', - seq_to_parenstr_upper(sort_criteria), - charset, - *normalise_search_criteria(criteria), - uid=True, unpack=True) + ids = self._command_and_check( + b'sort', + _normalise_sort_criteria(sort_criteria), + to_bytes(charset), + *normalise_search_criteria(criteria, charset), + uid=True, unpack=True) return [long(i) for i in ids.split()] + def thread(self, algorithm='REFERENCES', criteria='ALL', charset='UTF-8'): + """Return a list of messages threads matching *criteria*. + + Each returned thread is a list of messages ids. An example + return value containing three message threads:: + + ((1, 2), (3,), (4, 5, 6)) + + The optional *algorithm* argument specifies the threading + algorithm to use. + + The *criteria* and *charset* arguments are as per + :py:meth:`.search`. + + See :rfc:`5256` for more details. + + """ + algorithm = to_bytes(algorithm) + if not self.has_capability(b'THREAD=' + algorithm): + raise ValueError('server does not support %s threading algorithm' + % algorithm) + + if not criteria: + raise ValueError('no criteria specified') + + args = [algorithm] + if charset: + args.append(to_bytes(charset)) + args.extend(normalise_search_criteria(criteria, charset)) + + data = self._command_and_check(b'thread', *args, uid=True) + return parse_response(data) + def get_flags(self, messages): """Return the flags set for each message in *messages*. @@ -1013,9 +1032,11 @@ class IMAPClient(object): assert not kwargs, "unexpected keyword args: " + ', '.join(kwargs) if uid and self.use_uid: + if PY3: + command = to_unicode(command) # imaplib must die typ, data = self._imap.uid(command, *args) else: - meth = getattr(self._imap, command) + meth = getattr(self._imap, to_unicode(command)) typ, data = meth(*args) self._checkok(command, typ, data) if unpack: @@ -1096,17 +1117,30 @@ def seq_to_parenstr(items): def seq_to_parenstr_upper(items): return _join_and_paren(item.upper() for item in _normalise_text_list(items)) -def normalise_search_criteria(criteria): +def normalise_search_criteria(criteria, charset=None): if not criteria: raise ValueError('no criteria specified') - return ['(' + item + ')' for item in _normalise_text_list(criteria)] + if isinstance(criteria, (text_type, binary_type)): + criteria = (criteria,) + if not charset: + charset = 'us-ascii' + return [b'(' + to_bytes(item, charset) + b')' for item in criteria] + +def _normalise_sort_criteria(criteria, charset=None): + if isinstance(criteria, (text_type, binary_type)): + criteria = (criteria,) + # This is because imaplib's implementation varies between Python 2 and 3. + if PY3: + return '(' + ' '.join(to_unicode(item).upper() for item in criteria) + ')' + else: + return b'(' + b' '.join(to_bytes(item).upper() for item in criteria) + b')' def _join_and_paren(items): return '(' + ' '.join(items) + ')' def _normalise_text_list(items): if isinstance(items, (text_type, binary_type)): - items = (to_unicode(items),) + items = (items,) return (to_unicode(c) for c in items) def join_message_ids(messages): @@ -1155,7 +1189,7 @@ def to_unicode(s): return s.decode('ascii') return s -def to_bytes(s): +def to_bytes(s, charset='ascii'): if isinstance(s, text_type): - return s.encode('ascii') + return s.encode(charset) return s diff --git a/imapclient/livetest.py b/imapclient/livetest.py index e04e0f4..828582f 100644 --- a/imapclient/livetest.py +++ b/imapclient/livetest.py @@ -54,6 +54,18 @@ Here is the second part. --===============1534046211==-- """.replace('\n', '\r\n') + +SMILE = '\u263a' +FROWN = '\u2639' + +SMILE_MESSAGE = b"""\ +Subject: stuff +Content-Type: text/plain; charset="UTF-8" + +'\xe2\x98\xba' +""".replace(b'\n', b'\r\n') + + class _TestBase(unittest.TestCase): conf = None @@ -626,13 +638,20 @@ def createUidTestClass(conf, use_uid): self.assertEqual(len(ids), 1) self.assertGreater(ids.modseq, initial_modseq) + def test_search_with_unicode(self): + self.client.append(self.base_folder, SMILE_MESSAGE) + + self.assertEqual(len(self.client.search('TEXT "%s"' % SMILE, charset='UTF-8')), 1) + self.assertEqual(len(self.client.search(['TEXT "%s"' % SMILE], charset='UTF-8')), 1) + + self.assertEqual(len(self.client.search('TEXT "%s"' % FROWN, charset='UTF-8')), 0) + def test_gmail_search(self): self.skip_unless_capable('X-GM-EXT-1', 'Gmail search') random_string = ''.join(random.sample(string.ascii_letters*20, 64)) msg = 'Subject: something\r\n\r\nFoo\r\n%s\r\n' % random_string self.client.append(self.base_folder, msg) - self.client.noop() # For Gmail ids = self.client.gmail_search(random_string) self.assertEqual(len(ids), 1) @@ -641,8 +660,7 @@ def createUidTestClass(conf, use_uid): self.assertEqual(len(ids), 0) def test_sort(self): - if not self.client.has_capability('SORT'): - return self.skipTest("Server doesn't support SORT") + self.skip_unless_capable('SORT') # Add some test messages msg_tmpl = 'Subject: Test\r\n\r\nBody' @@ -658,14 +676,19 @@ def createUidTestClass(conf, use_uid): expected = [first_id, first_id - 1, first_id - 2] self.assertListEqual(messages, expected) + def test_sort_with_unicode(self): + self.skip_unless_capable('SORT') + + self.client.append(self.base_folder, SMILE_MESSAGE) + + messages = self.client.sort('ARRIVAL', ['TEXT "%s"' % SMILE]) + self.assertEqual(len(messages), 1) + + messages = self.client.sort('ARRIVAL', ['TEXT "%s"' % FROWN]) + self.assertEqual(len(messages), 0) + def test_thread(self): - thread_algo = None - for cap in self.client.capabilities(): - if cap.startswith(b'THREAD='): - thread_algo = cap.split(b'=')[-1] - break - if not thread_algo: - return self.skipTest("Server doesn't support THREAD") + self.skip_unless_capable('THREAD=REFERENCES') msg_tmpl = 'Subject: %s\r\n\r\nBody' subjects = ('a', 'b', 'c') @@ -681,6 +704,18 @@ def createUidTestClass(conf, use_uid): expected = ((first_id,), (first_id + 1,), (first_id + 2,)) self.assertTupleEqual(messages, expected) + def test_thread_with_unicode(self): + self.skip_unless_capable('THREAD=REFERENCES') + + self.client.append(self.base_folder, SMILE_MESSAGE) + + threads = self.client.thread(criteria=['TEXT "%s"' % SMILE]) + self.assertEqual(len(threads), 1) + self.assertEqual(len(threads[0]), 1) + + threads = self.client.thread(criteria=['TEXT "%s"' % FROWN]) + self.assertEqual(len(threads), 0) + def test_copy(self): self.append_msg(SIMPLE_MESSAGE) target_folder = self.add_prefix_to_folder('target') diff --git a/imapclient/test/test_imapclient.py b/imapclient/test/test_imapclient.py index 98642c0..cc9b88e 100644 --- a/imapclient/test/test_imapclient.py +++ b/imapclient/test/test_imapclient.py @@ -522,13 +522,30 @@ class TestThread(IMAPClientTest): self.client._cached_capabilities = (b'THREAD=FOO',) self.assertRaises(ValueError, self.client.thread) + def test_charset_with_uid(self): + self.client._cached_capabilities = (b'THREAD=REFERENCES',) + self.client._imap.uid.return_value = ('OK', []) + + self.client.thread(criteria='\u261e', charset='utf-8') + + self.client._imap.uid.assert_called_once_with('thread', b'REFERENCES', b'utf-8', b'(\xe2\x98\x9e)') + + def test_charset_without_uid(self): + self.client._cached_capabilities = (b'THREAD=REFERENCES',) + self.client.use_uid = False + self.client._imap.thread.return_value = ('OK', []) + + self.client.thread(criteria='\u261e', charset='utf-8') + + self.client._imap.thread.assert_called_once_with(b'REFERENCES', b'utf-8', b'(\xe2\x98\x9e)') + def test_all_args_with_uid(self): 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', b'FOO', b'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 @@ -537,7 +554,7 @@ class TestThread(IMAPClientTest): self.client.thread(algorithm='FOO', criteria='STUFF', charset='ASCII') - self.client._imap.thread.assert_called_once_with(b'FOO', b'ASCII', '(STUFF)') + self.client._imap.thread.assert_called_once_with(b'FOO', b'ASCII', b'(STUFF)') class TestId(IMAPClientTest): diff --git a/imapclient/test/test_search.py b/imapclient/test/test_search.py index fa4403f..fd3293f 100644 --- a/imapclient/test/test_search.py +++ b/imapclient/test/test_search.py @@ -4,10 +4,15 @@ from __future__ import unicode_literals +from six import PY3 + from .imapclient_test import IMAPClientTest from .testable_imapclient import TestableIMAPClient as IMAPClient +search_command = 'search' if PY3 else b'search' + + class TestSearch(IMAPClientTest): def test_with_uid(self): @@ -16,7 +21,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_command, b'(FOO)') self.assertEqual(result, [1, 2, 44]) self.assertEqual(result.modseq, None) @@ -26,7 +31,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_command, b'(FOO)') self.assertEqual(result, []) self.assertEqual(result.modseq, None) @@ -36,7 +41,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]) self.assertEqual(result.modseq, None) @@ -44,30 +49,27 @@ class TestSearch(IMAPClientTest): self.client.use_uid = True self.client._imap.uid.return_value = ('OK', [b'1 2 44']) - result = self.client.search('FOO', 'UTF9') + result = self.client.search(['UNDELETED', 'TEXT "\u2639"'], 'UTF-8') self.client._imap.uid.assert_called_once_with( - 'SEARCH', - b'CHARSET', 'UTF9', - '(FOO)') + search_command, + b'CHARSET', b'UTF-8', + b'(UNDELETED)', + b'(TEXT "\xe2\x98\xb9")', + ) self.assertEqual(result, [1, 2, 44]) def test_without_uid_with_charset(self): self.client.use_uid = False self.client._imap.search.return_value = ('OK', [b'1 2 44']) - result = self.client.search('FOO', 'UTF9') - - self.client._imap.search.assert_called_once_with('UTF9', '(FOO)') - self.assertEqual(result, [1, 2, 44]) - - def test_with_multiple_criteria_and_charset(self): - self.client.use_uid = False - self.client._imap.search.return_value = ('OK', [b'1 2 44']) - - result = self.client.search(['FOO', 'BAR'], 'UTF9') + result = self.client.search(['UNDELETED', 'TEXT "\u2639"'], 'UTF-8') - self.client._imap.search.assert_called_once_with('UTF9', '(FOO)', '(BAR)') + self.client._imap.search.assert_called_once_with( + b'UTF-8', + b'(UNDELETED)', + b'(TEXT "\xe2\x98\xb9")', + ) self.assertEqual(result, [1, 2, 44]) def test_modseq(self): @@ -75,7 +77,7 @@ class TestSearch(IMAPClientTest): result = self.client.search(['MODSEQ 40000']) - self.client._imap.uid.assert_called_once_with('SEARCH', '(MODSEQ 40000)') + self.client._imap.uid.assert_called_once_with(search_command, b'(MODSEQ 40000)') self.assertEqual(result, [1, 2]) self.assertEqual(result.modseq, 51101) @@ -95,7 +97,7 @@ class TestGmailSearch(IMAPClientTest): result = self.client.gmail_search('FOO') - self.client._imap.uid.assert_called_once_with('SEARCH', b'X-GM-RAW') + self.client._imap.uid.assert_called_once_with(search_command, b'X-GM-RAW') self.assertEqual(self.client._imap.literal, b'FOO') self.assertEqual(result, [1, 2, 44]) @@ -113,11 +115,11 @@ class TestGmailSearch(IMAPClientTest): self.client.use_uid = True self.client._imap.uid.return_value = ('OK', [b'1 2 44']) - result = self.client.gmail_search('\u2620', 'UTF8') + result = self.client.gmail_search('\u2620', 'UTF-8') self.client._imap.uid.assert_called_once_with( - 'SEARCH', - b'CHARSET', 'UTF8', + search_command, + b'CHARSET', b'UTF-8', b'X-GM-RAW') self.assertEqual(self.client._imap.literal, b'\xe2\x98\xa0') self.assertEqual(result, [1, 2, 44]) @@ -126,9 +128,9 @@ class TestGmailSearch(IMAPClientTest): self.client.use_uid = False self.client._imap.search.return_value = ('OK', [b'1 2 44']) - result = self.client.gmail_search('\u2620', 'UTF8') + result = self.client.gmail_search('\u2620', 'UTF-8') - self.client._imap.search.assert_called_once_with('UTF8', b'X-GM-RAW') + self.client._imap.search.assert_called_once_with(b'UTF-8', b'X-GM-RAW') self.assertEqual(self.client._imap.literal, b'\xe2\x98\xa0') self.assertEqual(result, [1, 2, 44]) diff --git a/imapclient/test/test_sort.py b/imapclient/test/test_sort.py new file mode 100644 index 0000000..aa51ceb --- /dev/null +++ b/imapclient/test/test_sort.py @@ -0,0 +1,74 @@ +# Copyright (c) 2015, Menno Smits +# Released subject to the New BSD License +# Please see http://en.wikipedia.org/wiki/BSD_licenses + +from __future__ import unicode_literals + +from six import PY3 + +from .imapclient_test import IMAPClientTest + + +sort_command = 'sort' if PY3 else b'sort' + + +class TestSort(IMAPClientTest): + + def setUp(self): + super(TestSort, self).setUp() + self.client._cached_capabilities = (b'SORT',) + + def test_no_support(self): + self.client._cached_capabilities = (b'BLAH',) + self.assertRaises(ValueError, self.client.thread) + + def test_without_uid(self): + self.client.use_uid = False + self.client._imap.sort.return_value = ('OK', [b'9 8 7']) + + ids = self.client.sort('arrival') + + self.client._imap.sort.assert_called_once_with( + '(ARRIVAL)', + b'UTF-8', + b'(ALL)', + ) + self.assertSequenceEqual(ids, [9, 8, 7]) + + def test_with_uid(self): + self.client.use_uid = True + self.client._imap.uid.return_value = ('OK', [b'9 8 7']) + + ids = self.client.sort(['foo', 'bar']) + + self.client._imap.uid.assert_called_once_with( + sort_command, + '(FOO BAR)', + b'UTF-8', + b'(ALL)', + ) + self.assertSequenceEqual(ids, [9, 8, 7]) + + def test_charset_without_uid(self): + self.client.use_uid = False + self.client._imap.sort.return_value = ('OK', ['']) + + self.client.sort('arrival', criteria=['\u261e', 'UNDELETED'], charset='utf-7') + + self.client._imap.sort.assert_called_once_with( + '(ARRIVAL)', + b'utf-7', + b'(+Jh4-)', b'(UNDELETED)', + ) + + def test_unicode_with_uid(self): + self.client._imap.uid.return_value = ('OK', ['']) + + self.client.sort('arrival', criteria=['\u261e', 'UNDELETED'], charset='utf-7') + + self.client._imap.uid.assert_called_once_with( + sort_command, + '(ARRIVAL)', + b'utf-7', + b'(+Jh4-)', b'(UNDELETED)', + ) diff --git a/imapclient/test/test_util_functions.py b/imapclient/test/test_util_functions.py index 0f9f07b..8ebafc5 100644 --- a/imapclient/test/test_util_functions.py +++ b/imapclient/test/test_util_functions.py @@ -112,28 +112,35 @@ class Test_join_message_ids(unittest.TestCase): def test_iter(self): self.check(iter([123, 99]), b'123,99') + class Test_normalise_search_criteria(unittest.TestCase): - def check(self, criteria, expected): - self.assertEqual(normalise_search_criteria(criteria), expected) + def check(self, criteria, charset, expected): + self.assertEqual(normalise_search_criteria(criteria, charset), expected) def test_unicode(self): - self.check('Foo', ['(Foo)']) + self.check('Foo', None, [b'(Foo)']) def test_binary(self): - self.check(b'FOO', ['(FOO)']) + self.check(b'FOO', None, [b'(FOO)']) + + def test_unicode_with_charset(self): + self.check('\u263a', 'UTF-8', [b'(\xe2\x98\xba)']) + + def test_binary_with_charset(self): + self.check(b'FOO', 'UTF-9', [b'(FOO)']) def test_tuple(self): - self.check(('FOO', 'BAR'), ['(FOO)', '(BAR)']) + self.check(('FOO', 'BAR'), None, [b'(FOO)', b'(BAR)']) def test_list(self): - self.check(['FOO', 'BAR'], ['(FOO)', '(BAR)']) + self.check(['FOO', 'BAR'], None, [b'(FOO)', b'(BAR)']) def test_mixed_list(self): - self.check(['FOO', b'BAR'], ['(FOO)', '(BAR)']) + self.check(['FOO', b'BAR'], None, [b'(FOO)', b'(BAR)']) def test_None(self): - self.assertRaises(ValueError, normalise_search_criteria, None) + self.assertRaises(ValueError, normalise_search_criteria, None, None) def test_empty(self): - self.assertRaises(ValueError, normalise_search_criteria, '') + self.assertRaises(ValueError, normalise_search_criteria, '', None) -- 2.43.0