From ef8d10c0b00e7c1c7e93bdafaf928f800da5ba57 Mon Sep 17 00:00:00 2001 From: Menno Smits Date: Sun, 9 Dec 2012 01:46:43 +0000 Subject: [PATCH] Broken the back of the unicode related issues. The lexer code has become the bytes -> string conversion point. This seems to work well. Still lots of tests to update but the implementation changes might be largely done. --- imapclient/imap_utf7.py | 9 +- imapclient/pycompat.py | 20 ++++ imapclient/response_lexer.py | 43 ++++---- imapclient/response_parser.py | 9 +- imapclient/test/test_imapclient.py | 9 +- imapclient/test/test_response_parser.py | 136 ++++++++++++------------ 6 files changed, 117 insertions(+), 109 deletions(-) create mode 100644 imapclient/pycompat.py diff --git a/imapclient/imap_utf7.py b/imapclient/imap_utf7.py index e70b052..d7b2cdf 100644 --- a/imapclient/imap_utf7.py +++ b/imapclient/imap_utf7.py @@ -23,6 +23,7 @@ # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. from .six import b, u, text_type, PY3, int2byte +from .pycompat import iter_as_bytes class FolderNameError(ValueError): pass @@ -100,11 +101,3 @@ def modified_base64(s): def modified_unbase64(s): s_utf7 = b('+') + s.replace(b(','), b('/')) + b('-') return s_utf7.decode('utf-7') - -if PY3: - def iter_as_bytes(some_bytes): - for c in some_bytes[:]: - yield int2byte(c) -else: - def iter_as_bytes(a_str): - return iter(a_str) diff --git a/imapclient/pycompat.py b/imapclient/pycompat.py new file mode 100644 index 0000000..aacccce --- /dev/null +++ b/imapclient/pycompat.py @@ -0,0 +1,20 @@ +""" +Further Python 2/3 compatibility helpers that aren't provided by six. +""" + +from .six import PY3, int2byte + +if PY3: + def iter_as_bytes(some_bytes): + for c in some_bytes[:]: + yield int2byte(c) + + def to_native_str(some_bytes): + return some_bytes.decode('latin-1') + +else: + def iter_as_bytes(a_str): + return iter(a_str) + + def to_native_str(some_bytes): + return some_bytes diff --git a/imapclient/response_lexer.py b/imapclient/response_lexer.py index 07d4fce..e4c9437 100644 --- a/imapclient/response_lexer.py +++ b/imapclient/response_lexer.py @@ -16,8 +16,8 @@ use for external callers. __all__ = ["Lexer"] -from .six import advance_iterator - +from .six import advance_iterator, b +from .pycompat import iter_as_bytes, to_native_str class TokenSource(object): """ @@ -38,11 +38,11 @@ class TokenSource(object): def __iter__(self): return self.src -CTRL_CHARS = ''.join([chr(ch) for ch in range(32)]) -SPECIALS = r' ()%"[' + CTRL_CHARS -ALL_CHARS = [chr(ch) for ch in range(256)] +CTRL_CHARS = b''.join([b(chr(ch)) for ch in range(32)]) +SPECIALS = b' ()%"[' + CTRL_CHARS +ALL_CHARS = [b(chr(ch)) for ch in range(256)] NON_SPECIALS = frozenset([ch for ch in ALL_CHARS if ch not in SPECIALS]) -WHITESPACE = frozenset(' \t\r\n') +WHITESPACE = frozenset(iter_as_bytes(b(' \t\r\n'))) class Lexer(object): "A lexical analyzer class for IMAP" @@ -56,19 +56,19 @@ class Lexer(object): token = '' try: for nextchar in stream_i: - if escape and nextchar == "\\": + if escape and nextchar == b("\\"): escaper = nextchar nextchar = advance_iterator(stream_i) if nextchar != escaper and nextchar != end_char: - token += escaper + token += to_native_str(escaper.decode) elif nextchar == end_char: break - token += nextchar + token += to_native_str(nextchar) else: raise ValueError("No closing %r" % end_char) except StopIteration: raise ValueError("No closing %r" % end_char) - return token + end_char + return token + to_native_str(end_char) def read_token_stream(self, stream_i): whitespace = WHITESPACE @@ -86,20 +86,20 @@ class Lexer(object): token = '' for nextchar in stream_i: if nextchar in wordchars: - token += nextchar - elif nextchar == '[': - token += nextchar + read_until(stream_i, ']', escape=False) + token += to_native_str(nextchar) + elif nextchar == b('['): + token += to_native_str(nextchar) + read_until(stream_i, b(']'), escape=False) else: if nextchar in whitespace: yield token - elif nextchar == '"': + elif nextchar == b('"'): assert not token - yield nextchar + read_until(stream_i, nextchar) + yield to_native_str(nextchar) + read_until(stream_i, nextchar) else: # Other punctuation, eg. "(". This ends the current token. if token: yield token - yield nextchar + yield to_native_str(nextchar) break else: if token: @@ -131,16 +131,16 @@ class LiteralHandlingIter: if isinstance(resp_record, tuple): # A 'record' with a string which includes a literal marker, and # the literal itself. - src_text, self.literal = resp_record - assert src_text.endswith("}"), src_text - self.src_text = src_text + self.src_text = resp_record[0] + assert self.src_text.endswith(b("}")), self.src_text + self.literal = to_native_str(resp_record[1]) else: # just a line with no literals. self.src_text = resp_record self.literal = None def __iter__(self): - return PushableIterator(self.src_text) + return PushableIterator(iter_as_bytes(self.src_text)) class PushableIterator(object): @@ -164,6 +164,3 @@ class PushableIterator(object): def push(self, item): self.pushed.append(item) - - - diff --git a/imapclient/response_parser.py b/imapclient/response_parser.py index a258aa0..3cd3ea4 100644 --- a/imapclient/response_parser.py +++ b/imapclient/response_parser.py @@ -166,11 +166,11 @@ def _convert_INTERNALDATE(date_string, normalise_times=True): def atom(src, token): - if token == "(": + if token == '(': return parse_tuple(src) elif token == 'NIL': return None - elif token[0] == '{': + elif token[:1] == '{': literal_len = int(token[1:-1]) literal_text = src.current_literal if literal_text is None: @@ -179,14 +179,13 @@ def atom(src, token): raise ParseError('Expecting literal of size %d, got %d' % ( literal_len, len(literal_text))) return literal_text - elif len(token) >= 2 and (token[0] == token[-1] == '"'): + elif len(token) >= 2 and (token[:1] == token[-1:] == '"'): return token[1:-1] elif token.isdigit(): return int(token) else: return token - def parse_tuple(src): out = [] for token in src: @@ -196,7 +195,5 @@ def parse_tuple(src): # no terminator raise ParseError('Tuple incomplete before "(%s"' % _fmt_tuple(out)) - def _fmt_tuple(t): return ' '.join(str(item) for item in t) - diff --git a/imapclient/test/test_imapclient.py b/imapclient/test/test_imapclient.py index 59ff607..3258884 100644 --- a/imapclient/test/test_imapclient.py +++ b/imapclient/test/test_imapclient.py @@ -6,9 +6,8 @@ import itertools import socket import sys from datetime import datetime -from StringIO import StringIO -from imapclient.six import advance_iterator, u +from imapclient.six import advance_iterator, b, u, StringIO from imapclient.fixed_offset import FixedOffset from imapclient.imapclient import datetime_to_imap from imapclient.test.mock import patch, sentinel, Mock @@ -65,9 +64,9 @@ class TestListFolders(IMAPClientTest): 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'), diff --git a/imapclient/test/test_response_parser.py b/imapclient/test/test_response_parser.py index ed77fa0..11bbd7d 100644 --- a/imapclient/test/test_response_parser.py +++ b/imapclient/test/test_response_parser.py @@ -8,8 +8,10 @@ Unit tests for the FetchTokeniser and FetchParser classes from datetime import datetime from textwrap import dedent + from imapclient.fixed_offset import FixedOffset from imapclient.response_parser import parse_response, parse_fetch_response, ParseError +from imapclient.six import b from imapclient.test.util import unittest #TODO: tokenising tests @@ -21,51 +23,51 @@ CRLF = '\r\n' class TestParseResponse(unittest.TestCase): def test_unquoted(self): - self._test('FOO', 'FOO') - self._test('F.O:-O_0;', 'F.O:-O_0;') - self._test(r'\Seen', r'\Seen') + self._test(b('FOO'), 'FOO') + self._test(b('F.O:-O_0;'), 'F.O:-O_0;') + self._test(b(r'\Seen'), r'\Seen') def test_string(self): - self._test('"TEST"', 'TEST') + self._test(b('"TEST"'), 'TEST') def test_int(self): - self._test('45', 45) + self._test(b('45'), 45) def test_nil(self): - self._test('NIL', None) + self._test(b('NIL'), None) def test_empty_tuple(self): - self._test('()', ()) + self._test(b('()'), ()) def test_tuple(self): - self._test('(123 "foo" GeE)', (123, 'foo', 'GeE')) + self._test(b('(123 "foo" GeE)'), (123, 'foo', 'GeE')) def test_int_and_tuple(self): - self._test('1 (123 "foo")', (1, (123, 'foo')), wrap=False) + self._test(b('1 (123 "foo")'), (1, (123, 'foo')), wrap=False) def test_nested_tuple(self): - self._test('(123 "foo" ("more" NIL) 66)', + self._test(b('(123 "foo" ("more" NIL) 66)'), (123, "foo", ("more", None), 66)) def test_deeper_nest_tuple(self): - self._test('(123 "foo" ((0 1 2) "more" NIL) 66)', + self._test(b('(123 "foo" ((0 1 2) "more" NIL) 66)'), (123, "foo", ((0, 1, 2), "more", None), 66)) def test_complex_mixed(self): - self._test('((FOO "PLAIN" ("CHARSET" "US-ASCII") NIL NIL "7BIT" 1152 23) ' - '("TEXT" "PLAIN" ("CHARSET" "US-ASCII" "NAME" "cc.diff") ' - '"" "foo" "BASE64" 4554 73) "MIXED")', + self._test(b('((FOO "PLAIN" ("CHARSET" "US-ASCII") NIL NIL "7BIT" 1152 23) ' + '("TEXT" "PLAIN" ("CHARSET" "US-ASCII" "NAME" "cc.diff") ' + '"" "foo" "BASE64" 4554 73) "MIXED")'), (('FOO', 'PLAIN', ('CHARSET', 'US-ASCII'), None, None, '7BIT', 1152, 23), ('TEXT', 'PLAIN', ('CHARSET', 'US-ASCII', 'NAME', 'cc.diff'), '', 'foo', 'BASE64', 4554, 73), 'MIXED')) def test_envelopey(self): - self._test('(UID 5 ENVELOPE ("internal_date" "subject" ' - '(("name" NIL "address1" "domain1.com")) ' - '((NIL NIL "address2" "domain2.com")) ' - '(("name" NIL "address3" "domain3.com")) ' - '((NIL NIL "address4" "domain4.com")) ' - 'NIL NIL "" ""))', + self._test(b('(UID 5 ENVELOPE ("internal_date" "subject" ' + '(("name" NIL "address1" "domain1.com")) ' + '((NIL NIL "address2" "domain2.com")) ' + '(("name" NIL "address3" "domain3.com")) ' + '((NIL NIL "address4" "domain4.com")) ' + 'NIL NIL "" ""))'), ('UID', 5, 'ENVELOPE', @@ -81,12 +83,12 @@ class TestParseResponse(unittest.TestCase): ''))) def test_envelopey_quoted(self): - self._test('(UID 5 ENVELOPE ("internal_date" "subject with \\"quotes\\"" ' - '(("name" NIL "address1" "domain1.com")) ' - '((NIL NIL "address2" "domain2.com")) ' - '(("name" NIL "address3" "domain3.com")) ' - '((NIL NIL "address4" "domain4.com")) ' - 'NIL NIL "" ""))', + self._test(b('(UID 5 ENVELOPE ("internal_date" "subject with \\"quotes\\"" ' + '(("name" NIL "address1" "domain1.com")) ' + '((NIL NIL "address2" "domain2.com")) ' + '(("name" NIL "address3" "domain3.com")) ' + '((NIL NIL "address4" "domain4.com")) ' + 'NIL NIL "" ""))'), ('UID', 5, 'ENVELOPE', @@ -102,43 +104,43 @@ class TestParseResponse(unittest.TestCase): ''))) def test_literal(self): - literal_text = add_crlf(dedent("""\ + literal_text = add_crlf(dedent(b("""\ 012 abc def XYZ - """)) - self._test([('{18}', literal_text)], literal_text) + """))) + self._test([(b('{18}'), literal_text)], literal_text) def test_literal_with_more(self): - literal_text = add_crlf(dedent("""\ + literal_text = add_crlf(dedent(b("""\ 012 abc def XYZ - """)) - response = [('(12 "foo" {18}', literal_text), ")"] + """))) + response = [(b('(12 "foo" {18}'), literal_text), ")"] self._test(response, (12, 'foo', literal_text)) def test_quoted_specials(self): - self._test(r'"\"foo bar\""', '"foo bar"') - self._test(r'"foo \"bar\""', 'foo "bar"') - self._test(r'"foo\\bar"', r'foo\bar') + self._test(b(r'"\"foo bar\""'), '"foo bar"') + self._test(b(r'"foo \"bar\""'), 'foo "bar"') + self._test(b(r'"foo\\bar"'), r'foo\bar') def test_square_brackets(self): - self._test('foo[bar rrr]', 'foo[bar rrr]') - self._test('"foo[bar rrr]"', 'foo[bar rrr]') - self._test('[foo bar]def', '[foo bar]def') - self._test('(foo [bar rrr])', ('foo', '[bar rrr]')) - self._test('(foo foo[bar rrr])', ('foo', 'foo[bar rrr]')) + self._test(b('foo[bar rrr]'), 'foo[bar rrr]') + self._test(b('"foo[bar rrr]"'), 'foo[bar rrr]') + self._test(b('[foo bar]def'), '[foo bar]def') + self._test(b('(foo [bar rrr])'), ('foo', '[bar rrr]')) + self._test(b('(foo foo[bar rrr])'), ('foo', 'foo[bar rrr]')) def test_incomplete_tuple(self): - self._test_parse_error('abc (1 2', 'Tuple incomplete before "\(1 2"') + self._test_parse_error(b('abc (1 2'), 'Tuple incomplete before "\(1 2"') def test_bad_literal(self): - self._test_parse_error([('{99}', 'abc')], + self._test_parse_error([(b('{99}'), b('abc'))], 'Expecting literal of size 99, got 3') def test_bad_quoting(self): - self._test_parse_error('"abc next', """No closing '"'""") + self._test_parse_error(b('"abc next'), """No closing '"'""") def _test(self, to_parse, expected, wrap=True): if wrap: @@ -159,11 +161,11 @@ class TestParseResponse(unittest.TestCase): class TestParseFetchResponse(unittest.TestCase): def test_basic(self): - self.assertEquals(parse_fetch_response('4 ()'), {4: {'SEQ': 4}}) + self.assertEqual(parse_fetch_response('4 ()'), {4: {'SEQ': 4}}) def test_none_special_case(self): - self.assertEquals(parse_fetch_response([None]), {}) + self.assertEqual(parse_fetch_response([None]), {}) def test_bad_msgid(self): @@ -179,7 +181,7 @@ class TestParseFetchResponse(unittest.TestCase): def test_simple_pairs(self): - self.assertEquals(parse_fetch_response(['23 (ABC 123 StUfF "hello")']), + self.assertEqual(parse_fetch_response(['23 (ABC 123 StUfF "hello")']), {23: {'ABC': 123, 'STUFF': 'hello', 'SEQ': 23}}) @@ -191,14 +193,14 @@ class TestParseFetchResponse(unittest.TestCase): def test_UID(self): - self.assertEquals(parse_fetch_response(['23 (UID 76)']), - {76: {'SEQ': 23}}) - self.assertEquals(parse_fetch_response(['23 (uiD 76)']), - {76: {'SEQ': 23}}) + self.assertEqual(parse_fetch_response([b('23 (UID 76)')]), + {76: {'SEQ': 23}}) + self.assertEqual(parse_fetch_response([b('23 (uiD 76)')]), + {76: {'SEQ': 23}}) def test_not_uid_is_key(self): - self.assertEquals(parse_fetch_response(['23 (UID 76)'], uid_is_key=False), + self.assertEqual(parse_fetch_response(['23 (UID 76)'], uid_is_key=False), {23: {'UID': 76, 'SEQ': 23}}) @@ -208,12 +210,12 @@ class TestParseFetchResponse(unittest.TestCase): def test_FLAGS(self): - self.assertEquals(parse_fetch_response(['23 (FLAGS (\Seen Stuff))']), + self.assertEqual(parse_fetch_response([b('23 (FLAGS (\Seen Stuff))')]), {23: {'SEQ': 23, 'FLAGS': (r'\Seen', 'Stuff')}}) def test_multiple_messages(self): - self.assertEquals(parse_fetch_response( + self.assertEqual(parse_fetch_response( ["2 (FLAGS (Foo Bar)) ", "7 (FLAGS (Baz Sneeve))"]), { @@ -223,7 +225,7 @@ class TestParseFetchResponse(unittest.TestCase): def test_literals(self): - self.assertEquals(parse_fetch_response([('1 (RFC822.TEXT {4}', 'body'), + self.assertEqual(parse_fetch_response([('1 (RFC822.TEXT {4}', 'body'), (' RFC822 {21}', 'Subject: test\r\n\r\nbody'), ')']), {1: {'RFC822.TEXT': 'body', @@ -232,15 +234,15 @@ class TestParseFetchResponse(unittest.TestCase): def test_literals_and_keys_with_square_brackets(self): - self.assertEquals(parse_fetch_response([('1 (BODY[TEXT] {11}', 'Hi there.\r\n'), ')']), + self.assertEqual(parse_fetch_response([('1 (BODY[TEXT] {11}', 'Hi there.\r\n'), ')']), { 1: {'BODY[TEXT]': 'Hi there.\r\n', 'SEQ': 1}}) def test_BODY_HEADER_FIELDS(self): header_text = 'Subject: A subject\r\nFrom: Some one \r\n\r\n' - self.assertEquals(parse_fetch_response( - [('123 (UID 31710 BODY[HEADER.FIELDS (from subject)] {57}', header_text), ')']), + self.assertEqual(parse_fetch_response( + [(b('123 (UID 31710 BODY[HEADER.FIELDS (from subject)] {57}'), b(header_text)), b(')')]), { 31710: {'BODY[HEADER.FIELDS (FROM SUBJECT)]': header_text, 'SEQ': 123}}) @@ -253,19 +255,19 @@ class TestParseFetchResponse(unittest.TestCase): self.check_BODYish_multipart('BODYSTRUCTURE') def check_BODYish_single_part(self, respType): - text = '123 (UID 317 %s ("TEXT" "PLAIN" ("CHARSET" "us-ascii") NIL NIL "7BIT" 16 1))' % respType + text = b('123 (UID 317 %s ("TEXT" "PLAIN" ("CHARSET" "us-ascii") NIL NIL "7BIT" 16 1))' % respType) parsed = parse_fetch_response([text]) - self.assertEquals(parsed, {317: {respType: ('TEXT', 'PLAIN', ('CHARSET', 'us-ascii'), None, None, '7BIT', 16, 1), + self.assertEqual(parsed, {317: {respType: ('TEXT', 'PLAIN', ('CHARSET', 'us-ascii'), None, None, '7BIT', 16, 1), 'SEQ': 123 } }) self.assertFalse(parsed[317][respType].is_multipart) def check_BODYish_multipart(self, respType): - text = '123 (UID 269 %s (("TEXT" "HTML" ("CHARSET" "us-ascii") NIL NIL "QUOTED-PRINTABLE" 55 3)' \ - '("TEXT" "PLAIN" ("CHARSET" "us-ascii") NIL NIL "7BIT" 26 1) "MIXED"))' \ - % respType + text = b('123 (UID 269 %s (("TEXT" "HTML" ("CHARSET" "us-ascii") NIL NIL "QUOTED-PRINTABLE" 55 3)' \ + '("TEXT" "PLAIN" ("CHARSET" "us-ascii") NIL NIL "7BIT" 26 1) "MIXED"))' \ + % respType) parsed = parse_fetch_response([text]) - self.assertEquals(parsed, {269: {respType: ([('TEXT', 'HTML', ('CHARSET', 'us-ascii'), None, None, 'QUOTED-PRINTABLE', 55, 3), + self.assertEqual(parsed, {269: {respType: ([('TEXT', 'HTML', ('CHARSET', 'us-ascii'), None, None, 'QUOTED-PRINTABLE', 55, 3), ('TEXT', 'PLAIN', ('CHARSET', 'us-ascii'), None, None, '7BIT', 26, 1)], 'MIXED'), 'SEQ': 123} @@ -274,7 +276,7 @@ class TestParseFetchResponse(unittest.TestCase): def test_partial_fetch(self): body = '01234567890123456789' - self.assertEquals(parse_fetch_response( + self.assertEqual(parse_fetch_response( [('123 (UID 367 BODY[]<0> {20}', body), ')']), { 367: {'BODY[]<0>': body, 'SEQ': 123}}) @@ -286,7 +288,7 @@ class TestParseFetchResponse(unittest.TestCase): actual_dt = output[3]['INTERNALDATE'] self.assert_(actual_dt.tzinfo is None) # Returned date should be in local timezone expected_dt = datetime_to_native(expected_dt) - self.assertEquals(actual_dt, expected_dt) + self.assertEqual(actual_dt, expected_dt) check(' 9-Feb-2007 17:08:08 -0430', datetime(2007, 2, 9, 17, 8, 8, 0, FixedOffset(-4*60 - 30))) @@ -301,7 +303,7 @@ class TestParseFetchResponse(unittest.TestCase): def check(date_str, expected_dt): output = parse_fetch_response(['3 (INTERNALDATE "%s")' % date_str], normalise_times=False) actual_dt = output[3]['INTERNALDATE'] - self.assertEquals(actual_dt, expected_dt) + self.assertEqual(actual_dt, expected_dt) check(' 9-Feb-2007 17:08:08 -0430', datetime(2007, 2, 9, 17, 8, 8, 0, FixedOffset(-4*60 - 30))) @@ -313,7 +315,7 @@ class TestParseFetchResponse(unittest.TestCase): datetime(2007, 12, 9, 17, 8, 8, 0, FixedOffset(0))) def test_mixed_types(self): - self.assertEquals(parse_fetch_response([('1 (INTERNALDATE " 9-Feb-2007 17:08:08 +0100" RFC822 {21}', + self.assertEqual(parse_fetch_response([('1 (INTERNALDATE " 9-Feb-2007 17:08:08 +0100" RFC822 {21}', 'Subject: test\r\n\r\nbody'), ')']), {1: {'INTERNALDATE': datetime_to_native(datetime(2007, 2, 9, -- 2.43.0