"""
import shlex
+from cStringIO import StringIO
#XXX higher level response type response type processing
#XXX plug-in this version
def parse_response(text):
- #XXX
+ #XXX doc
src = ResponseTokeniser(text)
try:
- return tuple([atom(src, token) for token in src])
+ return tuple(atom(src, token) for token in src)
except ParseError:
raise
except ValueError, err:
def parse_fetch_response(text):
- #XXX
- response = parse_response(text)
-
- msgid = response[0]
-
- # Second item should be FETCH
- if response[1] != 'FETCH':
- raise ParseError('not a FETCH response')
+ response = iter(parse_response(text))
+ def expect(expected_value):
+ next_value = response.next()
+ if next_value != expected_value:
+ raise ParseError('expected %r, got %r' % (expected_value, next_value))
+ msg_data = {}
+ while True:
+ try:
+ expect('*')
+ except StopIteration:
+ break
+ msgid = int(response.next())
+ expect('FETCH')
+ msg_data[msgid] = response.next()
+ return msg_data
EOF = object()
def datetime_to_native(dt):
return dt.astimezone(system_offset).replace(tzinfo=None)
-class TestPatchFetchResponse(object):
+class TestParseFetchResponse(unittest.TestCase):
def test_basic(self):
- parse_fetch_response('4 FETCH ()', {'4': {}})
+ self.assertEquals(parse_fetch_response('* 4 FETCH ()'), {4: {}})
+
+
+ def test_simple_pair(self):
+ self.assertEquals(parse_fetch_response('* 23 FETCH (ABC 123 STUFF "hello")'),
+ {'23': {'ABC': 123,
+ 'STUFF': 'hello'}})
+
def test_non_fetch(self):
- self.assertRaises(ParseError, parse_fetch_response, '4 OTHER ()')
+ self.assertRaises(ParseError, parse_fetch_response, '* 4 OTHER ()')
+
+
+ def test_bad_msgid(self):
+ self.assertRaises(ParseError, parse_fetch_response, '* abc FETCH ()')
+
def test_UID(self):
- self.fail()
-# '''Test UID handling. The UID is returned instead of the given message
-# ID if present.
-# '''
-# self._parse_test(
-# ['1 (UID 8)'],
-# {8: {}}
-# )
+ self.assertEquals(parse_fetch_response('* 23 FETCH (UID 76)'),
+ {'76': {}})
def test_FLAGS(self):
def test_multiple_fields(self):
self.fail()
+ def test_multiple_messages(self):
+ self.fail()
+
def test_case_handling(self):
self.fail()
# self._parse_test(
from pprint import pprint
from imapclient import IMAPClient
+from imapclient.response_parser import parse_response
def main():
i = IMAPClient('localhost')
i.select_folder('INBOX')
msgs = i.search()
i._imap.debug = 5
- lines = i.altfetch(msgs[0], ['RFC822'])
+ lines = i.altfetch(msgs, ['ENVELOPE', 'BODYSTRUCTURE'])
- print lines[0]
- body = '\r\n'.join(lines[1:-1])
- body += '\r\n'
- print body
- print len(body)
+ body = '\r\n'.join(lines)
+ #body += '\r\n'
+ for x in parse_response(body):
+ print x
if __name__ == '__main__':
main()