]> khamidou — GitHub mirrors - imapclient.git/commitdiff
Plugged in new response parser
authorMenno Smits <menno@freshfoo.com>
Sun, 24 Jan 2010 19:23:48 +0000 (19:23 +0000)
committerMenno Smits <menno@freshfoo.com>
Sun, 24 Jan 2010 19:23:48 +0000 (19:23 +0000)
Old FetchParser class and supporting code removed.
livetest.py works fully with Dovecot.

imapclient/imapclient.py
imapclient/test/test_FetchParser.py [deleted file]
livetest.py

index 9f8ab1e4be78b9d3be45bce920fbd04ad5c35d6a..8efb1d2edb3482fdc4e18d9e9afcfe4d5db47594 100644 (file)
@@ -5,7 +5,6 @@
 import re
 import imaplib
 import shlex
-import datetime
 #imaplib.Debug = 5
 
 import imap_utf7
@@ -430,22 +429,6 @@ class IMAPClient(object):
         msg_list = messages_to_str(messages)
         parts_list = seq_to_parenlist([p.upper() for p in parts])
 
-        if self.use_uid:
-            typ, data = self._imap.uid('FETCH', msg_list, parts_list)
-        else:
-            typ, data = self._imap.fetch(msg_list, parts_list)
-        self._checkok('fetch', typ, data)
-
-        parser = FetchParser()
-        return parser(data)
-
-    def altfetch(self, messages, parts):
-        if not messages:
-            return {}
-
-        msg_list = messages_to_str(messages)
-        parts_list = seq_to_parenlist([p.upper() for p in parts])
-
         if self.use_uid:
             tag = self._imap._command('UID', 'FETCH', msg_list, parts_list)
         else:
@@ -460,6 +443,7 @@ class IMAPClient(object):
 
         return parse_fetch_response(data)
 
+
     def append(self, folder, msg, flags=(), msg_time=None):
         """Append a message to a folder
 
@@ -564,7 +548,7 @@ class IMAPClient(object):
             typ, data = self._imap.store(msg_list, cmd, flag_list)
         self._checkok('store', typ, data)
 
-        return self._flatten_dict(FetchParser()(data))
+        return self._flatten_dict(parse_fetch_response((data)))
 
 
     def _flatten_dict(self, fetch_dict):
@@ -585,209 +569,6 @@ class IMAPClient(object):
         return name
 
 
-class FetchParser(object):
-    """
-    Parse an IMAP FETCH response and convert the return values to useful Python
-    values.
-    """
-
-    def parse(self, response):
-        out = {}
-        for response_item in response:
-            msgid, data = self.parse_data(response_item)
-
-            if msgid != None:
-                # Response for a new message
-                current_msg_data = {}
-                out[msgid] = current_msg_data
-
-            current_msg_data.update(data)
-
-        return out
-
-    __call__ = parse
-
-    def parse_data(self, data):
-        out = {}
-
-        if isinstance(data, str):
-            if data == ')':
-                # End of response for current message
-                return None, {}
-
-        elif isinstance(data, tuple):
-            data, literal_data = data
-
-        else:
-            raise ValueError("don't know how to handle %r" % data)
-
-        data = data.lstrip()
-        msgid = None
-        if data[0].isdigit():
-            # Get message ID
-            msgid, data = data.split(None, 1)
-            msgid = long(msgid)
-
-            assert data.startswith('('), data
-            data = data[1:]
-
-        if data.endswith(')'):
-            data = data[:-1]
-
-        for name, item in FetchTokeniser().process_pairs(data):
-            name = name.upper()
-
-            if name == 'UID':
-                # Using UID's, override the message ID
-                msgid = long(item)
-
-            else:
-                if isinstance(item, Literal):
-                    #assert len(data) == item.length
-                    arg = literal_data
-                else:
-                    arg = item
-
-                # Call handler function based on the response type
-                methname = 'do_'+name.upper().replace('.', '_')
-                meth = getattr(self, methname, self.do_default)
-                out[name] = meth(arg)
-
-        return msgid, out
-
-    def do_INTERNALDATE(self, arg):
-        """Process an INTERNALDATE response
-
-        @param arg: A quoted IMAP INTERNALDATE string
-            (eg. " 9-Feb-2007 17:08:08 +0000")
-        @return: datetime.datetime instance for the given time (in UTC)
-        """
-        arg = 'INTERNALDATE "%s"' % arg
-        mo = imaplib.InternalDate.match(arg)
-        if not mo:
-            raise ValueError("couldn't parse date %r" % arg)
-
-        zoneh = int(mo.group('zoneh'))
-        zonem = (zoneh * 60) + int(mo.group('zonem'))
-        if mo.group('zonen') == '-':
-            zonem = -zonem
-        tz = FixedOffset(zonem)
-
-        year = int(mo.group('year'))
-        mon = imaplib.Mon2num[mo.group('mon')]
-        day = int(mo.group('day'))
-        hour = int(mo.group('hour'))
-        min = int(mo.group('min'))
-        sec = int(mo.group('sec'))
-
-        dt = datetime.datetime(year, mon, day, hour, min, sec, 0, tz)
-
-        # Normalise to host system's timezone
-        return dt.astimezone(FixedOffset.for_system()).replace(tzinfo=None)
-
-
-    def do_default(self, arg):
-        return arg
-
-
-class FetchTokeniser(object):
-    """
-    General response tokenizer and converter
-    """
-
-    QUOTED_STRING = '(?:".*?")'
-    PAREN_LIST = '(?:\(.*?\))'
-
-    PAIR_RE = re.compile((
-        '([\w\.]+(?:\[[^\]]+\]+)?)\s+' +    # name (matches "FOO", "FOO.BAR" & "BODY[SECTION STUFF]")
-        '((?:\d+)' +                        # bare integer
-        '|(?:{\d+?})' +                     # IMAP literal
-        '|' + QUOTED_STRING +
-        '|' + PAREN_LIST +
-        ')\s*'))
-
-    DATA_RE = re.compile((
-        '(' + QUOTED_STRING +
-        '|' + PAREN_LIST +
-        '|(?:\S+)' +            # word
-        ')\s*'))
-
-    def process_pairs(self, s):
-        """Break up and convert a string of FETCH response pairs
-
-        @param s: FETCH response string eg. "FOO 12 BAH (1 abc def "foo bar")"
-        @return: Tokenised and converted input return as (name, data) pairs.
-        """
-        out = []
-        for m in strict_finditer(self.PAIR_RE, s):
-            name, data = m.groups()
-            out.append((name, self.nativefy(data)))
-        return out
-
-    def process_list(self, s):
-        """Break up and convert a string of data items
-
-        @param s: FETCH response string eg. "(1 abc def "foo bar")"
-        @return: A list of converted items.
-        """
-        if s == '':
-            return []
-        out = []
-        for m in strict_finditer(self.DATA_RE, s):
-            out.append(self.nativefy(m.group(1)))
-        return out
-
-    def nativefy(self, s):
-        if s.startswith('"'):
-            return s[1:-1]      # Debracket
-        elif s.startswith('{'):
-            return Literal(long(s[1:-1]))
-        elif s.startswith('('):
-            return self.process_list(s[1:-1])
-        elif s.isdigit():
-            return long(s)
-        elif s.upper() == 'NIL':
-            return None
-        else:
-            return s
-
-
-class Literal(object):
-    """
-    Simple class to represent a literal token in the fetch response
-    (eg. "{21}")
-    """
-
-    def __init__(self, length):
-        self.length = length
-
-    def __eq__(self, other):
-        return self.length == other.length
-
-    def __str__(self):
-        return '{%d}' % self.length
-
-
-def strict_finditer(regex, s):
-    """Like re.finditer except the regex must match from exactly where the
-    previous match ended and all the entire input must be matched.
-    """
-    i = 0
-    matched = False
-    while 1:
-        match = regex.match(s[i:])
-        if match:
-            matched = True
-            i += match.end()
-            yield match
-        else:
-            if (len(s) > 0 and not matched) or i < len(s):
-                raise ValueError("failed to match all of input. "
-                        "%r remains" % s[i:])
-            else:
-                return
-
-
 def messages_to_str(messages):
     """Convert a sequence of messages ids or a single message id into an
     message ID list for use with IMAP commands.
diff --git a/imapclient/test/test_FetchParser.py b/imapclient/test/test_FetchParser.py
deleted file mode 100644 (file)
index 5dbc4aa..0000000
+++ /dev/null
@@ -1,236 +0,0 @@
-# Copyright (c) 2009, Menno Smits
-# Released subject to the New BSD License
-# Please see http://en.wikipedia.org/wiki/BSD_licenses
-
-"""
-Unit tests for the FetchTokeniser and FetchParser classes
-"""
-
-import unittest
-import datetime
-from imapclient.imapclient import FetchParser, FetchTokeniser, Literal
-from imapclient.fixed_offset import FixedOffset
-from pprint import pformat
-
-#TODO: test invalid dates and times
-#TODO: more response types  
-
-system_offset = FixedOffset.for_system()
-def datetime_to_native(dt):
-    return dt.astimezone(system_offset).replace(tzinfo=None)
-
-class TestFetchTokeniser(unittest.TestCase):
-    def setUp(self):
-        self.t = FetchTokeniser()
-
-    def testEmptyList(self):
-        self._test_list('', [])
-
-    def testOneItemList(self):
-        self._test_list('123', [123])
-
-    def testWordsInList(self):
-        self._test_list('test stuff', ['test', 'stuff'])
-
-    def testQuotedStringInList(self):
-        self._test_list('"test stuff" and more', ['test stuff', 'and', 'more'])
-
-    def testNILInList(self):
-        self._test_list('test NIL stuff', ['test', None, 'stuff'])
-
-    def testEmptyListPair(self):
-        self._test_pairs('FOO ()', [('FOO', [])])
-
-    def testIntPair(self):
-        self._test_pairs('FOO 123', [('FOO', 123)])
-
-    def testQuotedStringPair(self):
-        self._test_pairs('FOO "abc def"', [('FOO', "abc def")])
-
-    def testComplexListPair(self):
-        self._test_pairs('FOO (123 "a b c" \\XYZ)', [('FOO', [123, "a b c", '\\XYZ'])])
-
-    def testMultiplePairs(self):
-        self._test_pairs('FOO 123 bar (def "XYZ") MORE "stuff"', [
-            ('FOO', 123),
-            ('bar', ['def', 'XYZ']),
-            ('MORE', 'stuff'),
-            ])
-
-    def testNoPairs(self):
-        self._test_pairs('', [])
-
-    def testGarbage(self):
-        self.assertRaises(ValueError,
-                self.t.process_pairs, 'FOO 123 BAH "abc" WHAT?')
-        self.assertRaises(ValueError,
-                self.t.process_pairs, 'HMMM FOO 123 BAH "abc"')
-        self.assertRaises(ValueError,
-                self.t.process_pairs, 'FOO 123 BAD BAH "abc"')
-
-    def testLiteral(self):
-        self._test_pairs('FOO {21}', [('FOO', Literal(21))])
-
-    def _test_pairs(self, input_, expected):
-        output = self.t.process_pairs(input_)
-        self.assert_(
-                output == expected,
-                format_error(input_, output, expected),
-            )
-        return output
-
-    def _test_list(self, input_, expected):
-        output = self.t.process_list(input_)
-        self.assert_(
-                output == expected,
-                format_error(input_, output, expected),
-            )
-        return output
-
-class TestFetchParser(unittest.TestCase):
-
-    def setUp(self):
-        self.p = FetchParser()
-
-    def testCharacterCase(self):
-        """Test handling of varied case in the response type name
-        """
-        self._parse_test(
-            [r'2 (flaGS (\Deleted Foo \Seen))'],
-            {2: {'FLAGS': [r'\Deleted', 'Foo', r'\Seen']}}
-            )
-
-    def testGarbage(self):
-        self.assertRaises(ValueError, self.p, [r'2 (FLAGS (\Deleted) MORE)'])
-
-
-    def test_INTERNALDATE(self):
-
-        def check(date_str, expected_dt):
-            output = self.p(['3 (INTERNALDATE "%s")' % date_str])
-            assert output.keys() == [3]
-            assert output[3].keys() == ['INTERNALDATE']
-            actual_dt = output[3]['INTERNALDATE']
-
-            # Returned date should be in local timezone
-            self.assert_(actual_dt.tzinfo is None)
-
-            expected_dt = datetime_to_native(expected_dt)
-            self.assert_(actual_dt == expected_dt,
-                         '%s != %s' % (actual_dt, expected_dt))
-
-        dt = check(' 9-Feb-2007 17:08:08 -0430',
-                   datetime.datetime(2007, 2, 9, 17, 8, 8, 0, FixedOffset(-4*60 - 30)))
- 
-        dt = check('12-Feb-2007 17:08:08 +0200',
-                   datetime.datetime(2007, 2, 12, 17, 8, 8, 0, FixedOffset(2*60)))
- 
-        dt = check(' 9-Dec-2007 17:08:08 +0000',
-                   datetime.datetime(2007, 12, 9, 17, 8, 8, 0, FixedOffset(0)))
-
-
-    def testMultipleTypes(self):
-        """Test multiple response types"""
-        self._parse_test(
-            [r'2 (FLAGS (\Deleted Foo \Seen) INTERNALDATE " 9-Feb-2007 17:08:08 +0000")'],
-            {2: {
-                    'FLAGS': [r'\Deleted', 'Foo', r'\Seen'],
-                    'INTERNALDATE': datetime_to_native(datetime.datetime(2007, 2, 9,
-                                                                         17, 8, 8, 0,
-                                                                         FixedOffset(0)))
-                    }
-                }
-            )
-
-    def testMultipleMessages(self):
-        """Test with multple messages in the response
-        """
-        self._parse_test(
-            [
-                r'2 (FLAGS (Foo Bar))',
-                r'7 (FLAGS (Baz Sneeve))',
-                ],
-            {
-                2: {'FLAGS': ['Foo', 'Bar']},
-                7: {'FLAGS': ['Baz', 'Sneeve']},
-                }
-            )
-
-    def testLiteral(self):
-        """Test literal handling
-        """
-        self._parse_test(
-            [('1 (RFC822 {21}', 'Subject: test\r\n\r\nbody'), ')'],
-            { 1: {'RFC822': 'Subject: test\r\n\r\nbody'} }
-            )
-
-    def testMultipleLiterals(self):
-        self._parse_test(
-            [
-                ('1 (RFC822.TEXT {4}', 'body'),
-                (' RFC822 {21}', 'Subject: test\r\n\r\nbody'),
-                ')'
-                ],
-            { 1: {
-                    'RFC822.TEXT': 'body',
-                    'RFC822': 'Subject: test\r\n\r\nbody',
-                    }
-                }
-            )
-
-    def testMultiTypesWithLiteral(self):
-        expected = {1: {'INTERNALDATE': datetime_to_native(datetime.datetime(2007, 2, 9,
-                                                                             17, 8, 8, 0,
-                                                                             FixedOffset(60))),
-                        'RFC822': 'Subject: test\r\n\r\nbody'}
-                    }
-        self._parse_test([('1 (INTERNALDATE " 9-Feb-2007 17:08:08 +0100" RFC822 {21}',
-                           'Subject: test\r\n\r\nbody'), ')'],
-                         expected)
-
-        # Also test where there literal comes back first
-        self._parse_test([('1 (RFC822 {21}', 'Subject: test\r\n\r\nbody'),
-                           'INTERNALDATE " 9-Feb-2007 17:08:08 +0100")'],
-                           expected)
-
-    def testLiteralsWithSections(self):
-        self._parse_test(
-            [('1 (BODY[TEXT] {11}', 'Hi there.\r\n'), ')'],
-            { 1: {'BODY[TEXT]': 'Hi there.\r\n',} }
-            )
-
-    def testLiteralsWithSectionsAndOtherParts(self):
-        self._parse_test(
-            [('1 (FLAGS (\\Seen) UID 2 BODY[HEADER.FIELDS (FROM)] {21}',
-              'From: foo@foo.com\r\n'), ')'],
-            {2: { 'BODY[HEADER.FIELDS (FROM)]': 'From: foo@foo.com\r\n',
-                  'FLAGS': ['\\Seen'],
-                   }
-                }
-            )
-
-    def testUID(self):
-        """Test UID handling. The UID is returned instead of the given message
-        ID if present.
-        """
-        self._parse_test(
-            ['1 (UID 8)'],
-            {8: {}}
-            )
-
-    def _parse_test(self, to_parse, expected):
-        output = self.p(to_parse)
-        self.assert_(
-                output == expected,
-                format_error(to_parse, output, expected),
-            )
-
-def format_error(input_, output, expected):
-    return 'failed for:\n%s\ngot:\n%s\nexpected:\n%s' % (
-                pformat(input_),
-                pformat(output),
-                pformat(expected),
-            )
-
-if __name__ == '__main__':
-    unittest.main()
index 0d0275fc19d7a4fee7b7e5d703e59532fa3a86ab..a8ba26aba05980a749609972ea79cb5f75ac850e 100755 (executable)
@@ -174,7 +174,7 @@ def test_flags(client):
         answer = func(msgid, *args)
 
         assert answer.has_key(msgid)
-        answer_flags = answer[msgid]
+        answer_flags = list(answer[msgid])
 
         # This is required because the order of the returned flags isn't
         # guaranteed