From: Menno Smits Date: Mon, 31 Aug 2015 22:07:57 +0000 (+1200) Subject: Bring IMAPClient in line with PEP8. X-Git-Tag: 1.0.0~1^2~34 X-Git-Url: http://git.khamidou.com/?a=commitdiff_plain;h=e32ead4e212bc722aa7e14147fd205aa837388d8;p=imapclient.git Bring IMAPClient in line with PEP8. Added pep8 tool config to tox.ini. Closes #141. --- diff --git a/imapclient/config.py b/imapclient/config.py index 5735890..76c5ccd 100644 --- a/imapclient/config.py +++ b/imapclient/config.py @@ -48,7 +48,7 @@ def parse_config_file(filename): oauth2_client_secret=None, oauth2_refresh_token=None, expect_failure=None, - )) + )) with open(filename, 'r') as fh: parser.readfp(fh) @@ -62,9 +62,11 @@ def parse_config_file(filename): return conf + def _read_config_section(parser, section): get = lambda name: parser.get(section, name) getboolean = lambda name: parser.getboolean(section, name) + def getint(name): try: return parser.getint(section, name) @@ -102,6 +104,7 @@ def _read_config_section(parser, section): expect_failure=get('expect_failure') ) + def refresh_oauth2_token(client_id, client_secret, refresh_token): if not json: raise RuntimeError("livetest OAUTH2 functionality relies on 'json' module") @@ -115,6 +118,8 @@ def refresh_oauth2_token(client_id, client_secret, refresh_token): # Tokens are expensive to refresh so use the same one for the duration of the process. _oauth2_cache = {} + + def get_oauth2_token(client_id, client_secret, refresh_token): cache_key = (client_id, client_secret, refresh_token) token = _oauth2_cache.get(cache_key) @@ -124,6 +129,7 @@ def get_oauth2_token(client_id, client_secret, refresh_token): _oauth2_cache[cache_key] = token return token + def create_client_from_config(conf): ssl_context = None if conf.ssl: @@ -144,8 +150,8 @@ def create_client_from_config(conf): if conf.oauth: client.oauth_login(conf.oauth_url, - conf.oauth_token, - conf.oauth_token_secret) + conf.oauth_token, + conf.oauth_token_secret) elif conf.oauth2: access_token = get_oauth2_token(conf.oauth2_client_id, conf.oauth2_client_secret, @@ -159,6 +165,7 @@ def create_client_from_config(conf): client.shutdown() raise + class Bunch(dict): def __getattr__(self, k): diff --git a/imapclient/datetime_util.py b/imapclient/datetime_util.py index 530a56d..a874fb5 100644 --- a/imapclient/datetime_util.py +++ b/imapclient/datetime_util.py @@ -21,7 +21,7 @@ def parse_to_datetime(timestamp, normalise=True): unadjusted but will contain timezone information as per the input. """ time_tuple = parsedate_tz(_munge(timestamp)) - if time_tuple == None: + if time_tuple is None: raise ValueError("couldn't parse datetime %r" % timestamp) tz_offset_seconds = time_tuple[-1] @@ -31,13 +31,15 @@ def parse_to_datetime(timestamp, normalise=True): dt = datetime(*time_tuple[:6], tzinfo=tz) if normalise and tz: - dt = datetime_to_native(dt) + dt = datetime_to_native(dt) return dt + def datetime_to_native(dt): return dt.astimezone(FixedOffset.for_system()).replace(tzinfo=None) + def datetime_to_INTERNALDATE(dt): """Convert a datetime instance to a IMAP INTERNALDATE string. @@ -53,6 +55,7 @@ def datetime_to_INTERNALDATE(dt): # issue #154). For example: 'Sat, 8 May 2010 16.03.09 +0200' _rfc822_dotted_time = re.compile("\w+, ?\d{1,2} \w+ \d\d(\d\d)? \d\d?\.\d\d?\.\d\d?.*") + def _munge(s): s = s.decode('latin-1') # parsedate_tz only works with strings if _rfc822_dotted_time.match(s): diff --git a/imapclient/examples/oauth_example.py b/imapclient/examples/oauth_example.py index e078be2..11564aa 100644 --- a/imapclient/examples/oauth_example.py +++ b/imapclient/examples/oauth_example.py @@ -1,24 +1,24 @@ -from __future__ import unicode_literals - -from imapclient import IMAPClient - -# Populate these with actual values -CONSUMER_KEY = '...' -CONSUMER_SECRET = '...' -OAUTH_TOKEN = '...' -OAUTH_TOKEN_SECRET = '...' - -HOST = 'imap.host.com' -URL = "https://somedomain.com/someuser/imap/" -ssl = True - -server = IMAPClient(HOST, use_uid=True, ssl=ssl) - -resp = server.oauth_login(URL, OAUTH_TOKEN, OAUTH_TOKEN_SECRET, - CONSUMER_KEY, CONSUMER_SECRET) -print(resp) - -select_info = server.select_folder('INBOX') -print(select_info) - -server.logout() +from __future__ import unicode_literals + +from imapclient import IMAPClient + +# Populate these with actual values +CONSUMER_KEY = '...' +CONSUMER_SECRET = '...' +OAUTH_TOKEN = '...' +OAUTH_TOKEN_SECRET = '...' + +HOST = 'imap.host.com' +URL = "https://somedomain.com/someuser/imap/" +ssl = True + +server = IMAPClient(HOST, use_uid=True, ssl=ssl) + +resp = server.oauth_login(URL, OAUTH_TOKEN, OAUTH_TOKEN_SECRET, + CONSUMER_KEY, CONSUMER_SECRET) +print(resp) + +select_info = server.select_folder('INBOX') +print(select_info) + +server.logout() diff --git a/imapclient/fixed_offset.py b/imapclient/fixed_offset.py index 3636d40..ec9b070 100644 --- a/imapclient/fixed_offset.py +++ b/imapclient/fixed_offset.py @@ -9,10 +9,11 @@ from datetime import tzinfo, timedelta ZERO = timedelta(0) + class FixedOffset(tzinfo): """ - This class describes fixed timezone offsets in hours and minutes - east from UTC + This class describes fixed timezone offsets in hours and minutes + east from UTC """ def __init__(self, minutes): diff --git a/imapclient/imap_utf7.py b/imapclient/imap_utf7.py index 0bf870d..c689055 100644 --- a/imapclient/imap_utf7.py +++ b/imapclient/imap_utf7.py @@ -10,10 +10,10 @@ # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: -# +# # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. -# +# # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND @@ -31,6 +31,7 @@ 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. @@ -66,6 +67,7 @@ def encode(s): AMPERSAND_ORD = byte2int(b'&') DASH_ORD = byte2int(b'-') + def decode(s): """Decode a folder name from IMAP modified UTF-7 encoding to unicode. diff --git a/imapclient/imapclient.py b/imapclient/imapclient.py index 88ddec1..5032561 100644 --- a/imapclient/imapclient.py +++ b/imapclient/imapclient.py @@ -51,7 +51,7 @@ if 'STARTTLS' not in imaplib.Commands: # but not that some servers (*cough* FastMail *cough*) don't seem to # accept it in state NONAUTH. if 'ID' not in imaplib.Commands: - imaplib.Commands['ID'] = ('NONAUTH', 'AUTH', 'SELECTED') + imaplib.Commands['ID'] = ('NONAUTH', 'AUTH', 'SELECTED') # System flags @@ -62,7 +62,9 @@ FLAGGED = br'\Flagged' DRAFT = br'\Draft' RECENT = br'\Recent' # This flag is read-only + class Namespace(tuple): + def __new__(cls, personal, other, shared): return tuple.__new__(cls, (personal, other, shared)) @@ -766,7 +768,7 @@ class IMAPClient(object): % algorithm) args = [algorithm, to_bytes(charset)] + \ - _normalise_search_criteria(criteria, charset) + _normalise_search_criteria(criteria, charset) data = self._raw_command_untagged(b'THREAD', args) return parse_response(data) @@ -999,7 +1001,7 @@ class IMAPClient(object): data = self._command_and_check('getacl', self._normalise_folder(folder)) parts = list(response_lexer.TokenSource(data)) parts = parts[1:] # First item is folder name - return [(parts[i], parts[i+1]) for i in xrange(0, len(parts), 2)] + return [(parts[i], parts[i + 1]) for i in xrange(0, len(parts), 2)] def setacl(self, folder, who, what): """Set an ACL (*what*) for user (*who*) for a folder. @@ -1061,7 +1063,7 @@ class IMAPClient(object): if isinstance(args, tuple): args = list(args) if not isinstance(args, list): - args = [args] + args = [args] tag = self._imap._new_tag() prefix = [to_bytes(tag)] @@ -1111,7 +1113,9 @@ class IMAPClient(object): while self._imap._get_response(): tagged_resp = self._imap.tagged_commands.get(tag) if tagged_resp: - raise self.AbortError("unexpected response while waiting for continuation response: " + repr(tagged_resp)) + raise self.AbortError( + "unexpected response while waiting for continuation response: " + + repr(tagged_resp)) if self.debug >= 4: self._log_write(" (literal) > ") @@ -1125,7 +1129,7 @@ class IMAPClient(object): if uid and self.use_uid: if PY3: - command = to_unicode(command) # imaplib must die + command = to_unicode(command) # imaplib must die typ, data = self._imap.uid(command, *args) else: meth = getattr(self._imap, to_unicode(command)) @@ -1177,7 +1181,7 @@ class IMAPClient(object): for i, c in enumerate(text): if c in "\"'": break - text = text[i+1:-1] + text = text[i + 1:-1] self.log_file.write(text) if end: @@ -1230,12 +1234,15 @@ def _maybe_quote(arg): def normalise_text_list(items): return list(_normalise_text_list(items)) + def seq_to_parenstr(items): return _join_and_paren(_normalise_text_list(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, charset=None): if not criteria: raise ValueError('no criteria specified') @@ -1245,24 +1252,29 @@ def _normalise_search_criteria(criteria, charset=None): return [to_bytes(criteria, charset)] return [_handle_one_search_criteria(item, charset) for item in criteria] + def _handle_one_search_criteria(item, charset): if isinstance(item, int): return str(item).encode('ascii') return _maybe_quote(to_bytes(item, charset)) + def _normalise_sort_criteria(criteria, charset=None): if isinstance(criteria, (text_type, binary_type)): criteria = [criteria] 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 = (items,) return (to_unicode(c) for c in items) + def join_message_ids(messages): """Convert a sequence of messages ids or a single integer message id into an id byte string for use with IMAP commands @@ -1271,17 +1283,20 @@ def join_message_ids(messages): messages = (to_bytes(messages),) return b','.join(_maybe_int_to_bytes(m) for m in messages) + def _maybe_int_to_bytes(val): if isinstance(val, integer_types): return str(val).encode('us-ascii') return to_bytes(val) + def normalise_untagged_responses(untagged): out = {} for key, value in iteritems(untagged): out[to_bytes(key)] = value return out + def _parse_untagged_response(text): assert text.startswith(b'* ') text = text[2:] @@ -1289,11 +1304,13 @@ def _parse_untagged_response(text): return tuple(text.split(b' ', 1)) return parse_response([text]) + def pop_with_default(dct, key, default): if key in dct: return dct.pop(key) return default + def as_pairs(items): i = 0 last_item = None @@ -1304,19 +1321,23 @@ def as_pairs(items): last_item = item i += 1 + def to_unicode(s): if isinstance(s, binary_type): return s.decode('ascii') return s + def to_bytes(s, charset='ascii'): if isinstance(s, text_type): return s.encode(charset) return s + def _is8bit(data): return any(b > 127 for b in iterbytes(data)) + def _iter_with_last(items): last_i = len(items) - 1 for i, item in enumerate(items): diff --git a/imapclient/imaplib_ssl_fix.py b/imapclient/imaplib_ssl_fix.py index 76459d8..73ff9f0 100644 --- a/imapclient/imaplib_ssl_fix.py +++ b/imapclient/imaplib_ssl_fix.py @@ -23,6 +23,7 @@ from __future__ import unicode_literals import sys import imaplib + def _is_affected_version(sys_version): sys_version = sys_version[:3] if sys_version < (2, 5, 0): @@ -33,18 +34,21 @@ def _is_affected_version(sys_version): return True return False + def _fixed_readline(self): """Read line from remote.""" line = [] - while 1: + while True: char = self.sslobj.read(1) line.append(char) - if char in ("\n", ""): return ''.join(line) + if char in ("\n", ""): + return ''.join(line) -_fixed_readline.patched = True # Marker to indicate patched version +_fixed_readline.patched = True # Marker to indicate patched version ssl_class = imaplib.IMAP4_SSL + def apply_patch(): if _is_affected_version(sys.version_info) and not hasattr(ssl_class.readline, 'patched'): ssl_class.readline = _fixed_readline diff --git a/imapclient/interact.py b/imapclient/interact.py index f6d754d..a567a27 100644 --- a/imapclient/interact.py +++ b/imapclient/interact.py @@ -12,6 +12,7 @@ from optparse import OptionParser from .config import parse_config_file, create_client_from_config + def command_line(): p = OptionParser() p.add_option('-H', '--host', dest='host', action='store', @@ -52,6 +53,7 @@ def command_line(): opts.stream = False return opts + def main(): opts = command_line() print('Connecting...') @@ -71,7 +73,7 @@ def main(): def builtin(c): import code code.interact(banner, local=dict(c=c)) - + for shell_attempt in (ipython_011, ipython_010, builtin): try: shell_attempt(client) diff --git a/imapclient/livetest.py b/imapclient/livetest.py index 0e0e493..a2c5997 100644 --- a/imapclient/livetest.py +++ b/imapclient/livetest.py @@ -182,6 +182,7 @@ class _TestBase(unittest.TestCase): if self.is_gmail(): self.client.noop() + class TestGeneral(_TestBase): """ Tests that don't involve message number/UID functionality. @@ -199,12 +200,16 @@ class TestGeneral(_TestBase): except Exception as err: if conf.expect_failure: if conf.expect_failure not in str(err): - self.fail("connection test %r failed with %r, expected %r" % (name, err, conf.expect_failure)) + self.fail( + "connection test %r failed with %r, expected %r" % + (name, err, conf.expect_failure)) else: self.fail("connection test %r failed unexpectedly with %r" % (name, err)) else: if conf.expect_failure: - self.fail("connection test %r didn't fail, expected %r" % (name, conf.expect_failure)) + self.fail( + "connection test %r didn't fail, expected %r" % + (name, conf.expect_failure)) def test_capabilities(self): caps = self.client.capabilities() @@ -219,7 +224,7 @@ class TestGeneral(_TestBase): def assertNoneOrTuple(val): assert val is None or isinstance(val, tuple), \ - "unexpected namespace value %r" % val + "unexpected namespace value %r" % val ns = self.client.namespace() self.assertEqual(len(ns), 3) @@ -266,7 +271,7 @@ class TestGeneral(_TestBase): for name in some_folders: self.assertIn(to_unicode(name), folders) - #TODO: test LIST with wildcards + # TODO: test LIST with wildcards def test_gmail_xlist(self): caps = self.client.capabilities() @@ -280,7 +285,7 @@ class TestGeneral(_TestBase): self.assertGreater(len(result), 0, 'No folders returned by XLIST') foundInbox = False - for flags, _, _ in result: + for flags, _, _ in result: if br'\INBOX' in [flag.upper() for flag in flags]: foundInbox = True break @@ -371,7 +376,6 @@ class TestGeneral(_TestBase): finally: self.client.folder_encode = True - def test_rename_folder(self): folders = self.add_prefix_to_folders([ 'foobar', @@ -385,7 +389,7 @@ class TestGeneral(_TestBase): for folder in folders: self.client.create_folder(folder) - if isinstance(folder, binary_type): + if isinstance(folder, binary_type): new_folder = folder + b'x' else: new_folder = folder + 'x' @@ -604,7 +608,8 @@ def createUidTestClass(conf, use_uid): self.assertEqual(len(self.client.search('DELETED')), 1) self.assertEqual(len(self.client.search(['NOT', 'DELETED'])), len(subjects) - 1) - self.assertEqual(len(self.client.search(['NOT', 'DELETED', 'SMALLER', 500])), len(subjects) - 1) + self.assertEqual(len(self.client.search( + ['NOT', 'DELETED', 'SMALLER', 500])), len(subjects) - 1) self.assertEqual(len(self.client.search(['NOT', 'DELETED', 'SMALLER', 5])), 0) self.assertEqual(len(self.client.search(['NOT', 'DELETED', 'SUBJECT', 'a'])), 1) self.assertEqual(len(self.client.search(['NOT', 'DELETED', 'SUBJECT', 'c'])), 0) @@ -620,7 +625,8 @@ def createUidTestClass(conf, use_uid): return self.skipTest("Server doesn't support CONDSTORE") if self.is_gmail(): - return self.skipTest("Gmail doesn't seem to return MODSEQ parts in SEARCH responses") + return self.skipTest( + "Gmail doesn't seem to return MODSEQ parts in SEARCH responses") # A little dance to ensure MODSEQ tracking is turned on. # TODO: use ENABLE for this instead @@ -649,12 +655,13 @@ def createUidTestClass(conf, use_uid): self.assertEqual(len(self.client.search(['BODY', MICRO], charset='UTF-8')), 0) # Try multiple criteria too - self.assertEqual(len(self.client.search(['TEXT', SMILE, 'NOT', 'DELETED'], charset='UTF-8')), 1) + self.assertEqual(len(self.client.search( + ['TEXT', SMILE, 'NOT', 'DELETED'], charset='UTF-8')), 1) 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)) + 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.append_msg(msg) @@ -781,15 +788,15 @@ def createUidTestClass(conf, use_uid): self.assertIsInstance(msginfo[b'INTERNALDATE'], datetime) self.assertIsInstance(msginfo[b'FLAGS'], tuple) self.assertSequenceEqual(msginfo[b'ENVELOPE'], - Envelope( - datetime(2010, 3, 16, 16, 45, 32, tzinfo=FixedOffset(0)), - b'A multipart message', - (Address(b'Bob Smith', None, b'bob', b'smith.com'),), - (Address(b'Bob Smith', None, b'bob', b'smith.com'),), - (Address(b'Bob Smith', None, b'bob', b'smith.com'),), - (Address(b'Some One', None, b'some', b'one.com'), - Address(None, None, b'foo', b'foo.com')), - None, None, None, to_bytes(msg_id_header))) + Envelope( + datetime(2010, 3, 16, 16, 45, 32, tzinfo=FixedOffset(0)), + b'A multipart message', + (Address(b'Bob Smith', None, b'bob', b'smith.com'),), + (Address(b'Bob Smith', None, b'bob', b'smith.com'),), + (Address(b'Bob Smith', None, b'bob', b'smith.com'),), + (Address(b'Some One', None, b'some', b'one.com'), + Address(None, None, b'foo', b'foo.com')), + None, None, None, to_bytes(msg_id_header))) def test_partial_fetch(self): self.client.append(self.base_folder, MULTIPART_MESSAGE) @@ -918,6 +925,7 @@ def createUidTestClass(conf, use_uid): return LiveTest + def quiet_logout(client): """Log out a connection, ignoring errors (say because the connection is down) """ @@ -926,11 +934,13 @@ def quiet_logout(client): except IMAPClient.Error: pass + def maybe_lower(val): if isinstance(val, (text_type, binary_type)): return val.lower() return val + def have_matching_types(a, b, type_or_types): """True if a and b are instances of the same type and that type is one of type_or_types. @@ -939,12 +949,14 @@ def have_matching_types(a, b, type_or_types): return False return isinstance(b, type(a)) + def argv_error(msg): print(msg, file=sys.stderr) print(file=sys.stderr) print("usage: %s [ optional unittest arguments ]" % sys.argv[0], file=sys.stderr) sys.exit(1) + def parse_argv(): args = sys.argv[1:] if not args: @@ -955,6 +967,7 @@ def parse_argv(): host_config = parse_config_file(ini_path) return host_config + def probe_host(config): client = create_client_from_config(config) ns = client.namespace() @@ -963,6 +976,7 @@ def probe_host(config): raise RuntimeError('Can\'t run tests: IMAP account has no personal namespace') return ns.personal[0] # Use first personal namespace + def main(): host_config = parse_argv() diff --git a/imapclient/response_lexer.py b/imapclient/response_lexer.py index 2370da4..88e09fb 100644 --- a/imapclient/response_lexer.py +++ b/imapclient/response_lexer.py @@ -131,6 +131,7 @@ class Lexer(object): # string literal is processed, we peek into this object to grab the # literal. class LiteralHandlingIter: + def __init__(self, lexer, resp_record): self.lexer = lexer if isinstance(resp_record, tuple): @@ -144,7 +145,6 @@ class LiteralHandlingIter: self.src_text = resp_record self.literal = None - def __iter__(self): return PushableIterator(six.iterbytes(self.src_text)) diff --git a/imapclient/response_parser.py b/imapclient/response_parser.py index e522e3b..a2c2a1f 100644 --- a/imapclient/response_parser.py +++ b/imapclient/response_parser.py @@ -9,7 +9,7 @@ returned by imaplib. Initially inspired by http://effbot.org/zone/simple-iterator-parser.htm """ -#TODO more exact error reporting +# TODO more exact error reporting from __future__ import unicode_literals @@ -18,12 +18,12 @@ import sys from collections import defaultdict import six -xrange = six.moves.xrange from .datetime_util import parse_to_datetime from .response_lexer import TokenSource from .response_types import BodyData, Envelope, Address, SearchIds +xrange = six.moves.xrange __all__ = ['parse_response', 'parse_message_list', 'ParseError'] @@ -44,6 +44,7 @@ def parse_response(data): _msg_id_pattern = re.compile("(\d+(?: +\d+)*)") + def parse_message_list(data): """Parse a list of message ids and return them as a list. @@ -132,7 +133,7 @@ def parse_fetch_response(text, normalise_times=True, uid_is_key=True): msg_data = {b'SEQ': seq} for i in xrange(0, len(msg_response), 2): word = msg_response[i].upper() - value = msg_response[i+1] + value = msg_response[i + 1] if word == b'UID': uid = _int_or_error(value, 'invalid UID') @@ -167,6 +168,7 @@ def _convert_INTERNALDATE(date_string, normalise_times=True): except ValueError: return None + def _convert_ENVELOPE(envelope_response, normalise_times=True): dt = None if envelope_response[0]: @@ -196,6 +198,7 @@ def _convert_ENVELOPE(envelope_response, normalise_times=True): message_id=envelope_response[9] ) + def atom(src, token): if token == b'(': return parse_tuple(src) @@ -205,10 +208,10 @@ def atom(src, token): literal_len = int(token[1:-1]) literal_text = src.current_literal if literal_text is None: - raise ParseError('No literal corresponds to %r' % token) + raise ParseError('No literal corresponds to %r' % token) if len(literal_text) != literal_len: raise ParseError('Expecting literal of size %d, got %d' % ( - literal_len, len(literal_text))) + literal_len, len(literal_text))) return literal_text elif len(token) >= 2 and (token[:1] == token[-1:] == b'"'): return token[1:-1] @@ -217,6 +220,7 @@ def atom(src, token): else: return token + def parse_tuple(src): out = [] for token in src: @@ -226,5 +230,6 @@ 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/imapclient_test.py b/imapclient/test/imapclient_test.py index 6e40118..7bef2dc 100644 --- a/imapclient/test/imapclient_test.py +++ b/imapclient/test/imapclient_test.py @@ -1,6 +1,7 @@ from .testable_imapclient import TestableIMAPClient as IMAPClient from .util import unittest + class IMAPClientTest(unittest.TestCase): def setUp(self): diff --git a/imapclient/test/test_datetime_util.py b/imapclient/test/test_datetime_util.py index d1f352e..5762256 100644 --- a/imapclient/test/test_datetime_util.py +++ b/imapclient/test/test_datetime_util.py @@ -34,11 +34,11 @@ class TestParsing(unittest.TestCase): def test_internaldate_style(self): self.check_normalised_and_not( b' 9-Feb-2007 17:08:08 -0430', - datetime(2007, 2, 9, 17, 8, 8, 0, FixedOffset(-4*60 - 30)) + datetime(2007, 2, 9, 17, 8, 8, 0, FixedOffset(-4 * 60 - 30)) ) self.check_normalised_and_not( b'19-Feb-2007 17:08:08 0400', - datetime(2007, 2, 19, 17, 8, 8, 0, FixedOffset(4*60)) + datetime(2007, 2, 19, 17, 8, 8, 0, FixedOffset(4 * 60)) ) def test_dots_for_time_separator(self): @@ -63,7 +63,7 @@ class TestParsing(unittest.TestCase): class TestDatetimeToINTERNALDATE(unittest.TestCase): def test_with_timezone(self): - dt = datetime(2009, 1, 2, 3, 4, 5, 0, FixedOffset(2*60 + 30)) + dt = datetime(2009, 1, 2, 3, 4, 5, 0, FixedOffset(2 * 60 + 30)) self.assertEqual(datetime_to_INTERNALDATE(dt), '02-Jan-2009 03:04:05 +0230') @patch('imapclient.datetime_util.FixedOffset.for_system') diff --git a/imapclient/test/test_fixed_offset.py b/imapclient/test/test_fixed_offset.py index 65744ae..e0a9165 100644 --- a/imapclient/test/test_fixed_offset.py +++ b/imapclient/test/test_fixed_offset.py @@ -9,6 +9,7 @@ from mock import Mock, patch, DEFAULT from imapclient.test.util import unittest from imapclient.fixed_offset import FixedOffset + class TestFixedOffset(unittest.TestCase): def _check(self, offset, expected_delta, expected_name): @@ -25,7 +26,7 @@ class TestFixedOffset(unittest.TestCase): timedelta(minutes=30), '+0030') self._check(FixedOffset(2 * 60), timedelta(hours=2), '+0200') - self._check(FixedOffset(11*60 + 30), + self._check(FixedOffset(11 * 60 + 30), timedelta(hours=11, minutes=30), '+1130') def test_negative(self): @@ -33,11 +34,11 @@ class TestFixedOffset(unittest.TestCase): timedelta(minutes=-30), '-0030') self._check(FixedOffset(-2 * 60), timedelta(hours=-2), '-0200') - self._check(FixedOffset(-11*60 - 30), - timedelta(minutes=(-11*60) - 30), '-1130') + self._check(FixedOffset(-11 * 60 - 30), + timedelta(minutes=(-11 * 60) - 30), '-1130') @patch.multiple('imapclient.fixed_offset.time', - daylight=True, timezone=15*60*60, localtime=DEFAULT) + daylight=True, timezone=15 * 60 * 60, localtime=DEFAULT) def test_for_system_DST_not_active(self, localtime): localtime_mock = Mock() localtime_mock.tm_isdst = False @@ -47,7 +48,7 @@ class TestFixedOffset(unittest.TestCase): self.assertEqual(offset.tzname(None), '-1500') @patch.multiple('imapclient.fixed_offset.time', - daylight=True, altzone=15*60*60, localtime=DEFAULT) + daylight=True, altzone=15 * 60 * 60, localtime=DEFAULT) def test_for_system_DST_active(self, localtime): localtime_mock = Mock() localtime_mock.tm_isdst = True @@ -57,7 +58,7 @@ class TestFixedOffset(unittest.TestCase): self.assertEqual(offset.tzname(None), '-1500') @patch.multiple('imapclient.fixed_offset.time', - daylight=False, timezone=-15*60*60) + daylight=False, timezone=-15 * 60 * 60) def test_for_system_no_DST(self): offset = FixedOffset.for_system() self.assertEqual(offset.tzname(None), '+1500') diff --git a/imapclient/test/test_imap_utf7.py b/imapclient/test/test_imap_utf7.py index b3ae3ec..218e135 100644 --- a/imapclient/test/test_imap_utf7.py +++ b/imapclient/test/test_imap_utf7.py @@ -20,7 +20,7 @@ class IMAP4UTF7TestCase(unittest.TestCase): ['Hello\xffworld', b'Hello&AP8-world'], ['\xff\xfe\xfd\xfc', b'&AP8A,gD9APw-'], ['~peter/mail/\u65e5\u672c\u8a9e/\u53f0\u5317', - b'~peter/mail/&ZeVnLIqe-/&U,BTFw-'], # example from RFC 2060 + b'~peter/mail/&ZeVnLIqe-/&U,BTFw-'], # example from RFC 2060 ['\x00foo', b'&AAA-foo'], ] @@ -30,7 +30,6 @@ class IMAP4UTF7TestCase(unittest.TestCase): self.assertIsInstance(encoded, binary_type) self.assertEqual(encoded, output) - def test_decode(self): for (input, output) in self.tests: decoded = decode(output) diff --git a/imapclient/test/test_imapclient.py b/imapclient/test/test_imapclient.py index 59fdc4f..6f4bfe5 100644 --- a/imapclient/test/test_imapclient.py +++ b/imapclient/test/test_imapclient.py @@ -44,12 +44,10 @@ class TestListFolders(IMAPClientTest): self.assertEqual(self.client._proc_folder_list.call_args, ((sentinel.folder_data,), {})) self.assertTrue(folders is sentinel.folder_list) - def test_list_folders_NO(self): self.client._imap._simple_command.return_value = ('NO', [b'badness']) self.assertRaises(IMAPClient.Error, self.client.list_folders) - def test_list_sub_folders_NO(self): self.client._imap._simple_command.return_value = ('NO', [b'badness']) self.assertRaises(IMAPClient.Error, self.client.list_folders) @@ -90,7 +88,6 @@ class TestListFolders(IMAPClientTest): self.assertEqual(folders, [((b'\\HasNoChildren',), b'/', 'A',), ((b'\\HasNoChildren',), b'/', 'Foo Bar')]) - def test_without_quotes(self): folders = self.client._proc_folder_list([b'(\\HasNoChildren) "/" A', b'(\\HasNoChildren) "/" B', @@ -108,7 +105,8 @@ class TestListFolders(IMAPClientTest): def test_unqouted_numeric_folder_name_parsed_as_long(self): # big enough numeric values might get parsed as longs folder_name = str(sys.maxsize + 1) - folders = self.client._proc_folder_list([b'(\\HasNoChildren) "/" ' + folder_name.encode('ascii')]) + folders = self.client._proc_folder_list( + [b'(\\HasNoChildren) "/" ' + folder_name.encode('ascii')]) self.assertEqual(folders, [((b'\\HasNoChildren', ), b'/', folder_name)]) def test_mixed(self): @@ -120,7 +118,6 @@ class TestListFolders(IMAPClientTest): ((b'\\HasNoChildren',), b'/', 'Foo Bar'), ((b'\\HasNoChildren',), b'/', 'C')]) - def test_funky_characters(self): folders = self.client._proc_folder_list([(b'(\\NoInferiors \\UnMarked) "/" {5}', 'bang\xff'), b'', @@ -128,7 +125,6 @@ class TestListFolders(IMAPClientTest): 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([br'(\HasNoChildren) "/" "Test \"Folder\""', br'(\HasNoChildren) "/" "Left\"Right"', @@ -146,7 +142,6 @@ class TestListFolders(IMAPClientTest): def test_empty_response(self): self.assertEqual(self.client._proc_folder_list([None]), []) - def test_blanks(self): folders = self.client._proc_folder_list(['', None, br'(\HasNoChildren) "/" "last"']) self.assertEqual(folders, [((br'\HasNoChildren',), b'/', 'last')]) @@ -209,7 +204,7 @@ class TestAppend(IMAPClientTest): msg = b'bye' self.client.append('foobar', msg, ['FLAG', 'WAVE'], - datetime(2009, 4, 5, 11, 0, 5, 0, FixedOffset(2*60))) + datetime(2009, 4, 5, 11, 0, 5, 0, FixedOffset(2 * 60))) self.assertTrue(datetime_to_INTERNALDATE.called) self.client._imap.append.assert_called_with( @@ -251,6 +246,7 @@ class TestIdleAndNoop(IMAPClientTest): self.client._imap.sock = self.client._imap.sslobj = mock_sock mock_select.return_value = ([True], [], []) counter = itertools.count() + def fake_get_line(): count = six.next(counter) if count == 0: @@ -289,6 +285,7 @@ class TestIdleAndNoop(IMAPClientTest): self.client._imap.sock = self.client._imap.sslobj = mock_sock mock_select.return_value = ([True], [], []) counter = itertools.count() + def fake_get_line(): count = six.next(counter) if count == 0: @@ -336,6 +333,7 @@ class TestIdleAndNoop(IMAPClientTest): client._imap.tagged_commands = {sentinel.tag: None} counter = itertools.count() + def fake_get_response(): count = six.next(counter) if count == 0: @@ -365,6 +363,7 @@ class TestDebugLogging(IMAPClientTest): self.assertIn('one', output) self.assertIn('two', output) + class TestTimeNormalisation(IMAPClientTest): def test_default(self): @@ -393,7 +392,11 @@ class TestGmailLabels(IMAPClientTest): def setUp(self): super(TestGmailLabels, self).setUp() - patcher = patch.object(self.client, '_store', autospec=True, return_value=sentinel.label_set) + patcher = patch.object( + self.client, + '_store', + autospec=True, + return_value=sentinel.label_set) patcher.start() self.addCleanup(patcher.stop) @@ -455,7 +458,7 @@ class TestNamespace(IMAPClientTest): (("", "/"),), (("~", "/"),), (("#shared/", "/"), ("#public/", "/"), ("#ftp/", "/"), ("#news.", ".")), - )) + )) class TestCapabilities(IMAPClientTest): @@ -549,40 +552,40 @@ class TestRawCommand(IMAPClientTest): def test_plain(self): self.check(b'search', [b'ALL'], - b'tag UID SEARCH ALL\r\n', - ) + b'tag UID SEARCH ALL\r\n', + ) def test_not_uid(self): self.client.use_uid = False self.check(b'search', [b'ALL'], - b'tag SEARCH ALL\r\n', - ) + b'tag SEARCH ALL\r\n', + ) def test_literal_at_end(self): self.check(b'search', [b'TEXT', b'\xfe\xff'], - b'tag UID SEARCH TEXT {2}\r\n' - b'\xfe\xff\r\n' - ) + b'tag UID SEARCH TEXT {2}\r\n' + b'\xfe\xff\r\n' + ) def test_embedded_literal(self): self.check(b'search', [b'TEXT', b'\xfe\xff', b'DELETED'], - b'tag UID SEARCH TEXT {2}\r\n' - b'\xfe\xff DELETED\r\n' - ) + b'tag UID SEARCH TEXT {2}\r\n' + b'\xfe\xff DELETED\r\n' + ) def test_multiple_literals(self): self.check(b'search', [b'TEXT', b'\xfe\xff', b'TEXT', b'\xcc'], - b'tag UID SEARCH TEXT {2}\r\n' - b'\xfe\xff TEXT {1}\r\n' - b'\xcc\r\n' - ) + b'tag UID SEARCH TEXT {2}\r\n' + b'\xfe\xff TEXT {1}\r\n' + b'\xcc\r\n' + ) def test_complex(self): self.check(b'search', [b'FLAGGED', b'TEXT', b'\xfe\xff', b'TEXT', b'\xcc', b'TEXT', b'foo'], - b'tag UID SEARCH FLAGGED TEXT {2}\r\n' - b'\xfe\xff TEXT {1}\r\n' - b'\xcc TEXT foo\r\n' - ) + b'tag UID SEARCH FLAGGED TEXT {2}\r\n' + b'\xfe\xff TEXT {1}\r\n' + b'\xcc TEXT foo\r\n' + ) def test_invalid_input_type(self): self.assertRaises(ValueError, self.client._raw_command, 'foo', []) diff --git a/imapclient/test/test_response_lexer.py b/imapclient/test/test_response_lexer.py index 6b89760..7876faf 100644 --- a/imapclient/test/test_response_lexer.py +++ b/imapclient/test/test_response_lexer.py @@ -31,12 +31,12 @@ class TestTokenSource(unittest.TestCase): [b'abc', b'def']) def test_quoted_strings(self): - self.check([b'"abc def"'], - [b'"abc def"']) - self.check([b'""'], - [b'""']) - self.check([b'111 "abc def" 222'], - [b'111', b'"abc def"', b'222']) + self.check([b'"abc def"'], + [b'"abc def"']) + self.check([b'""'], + [b'""']) + self.check([b'111 "abc def" 222'], + [b'111', b'"abc def"', b'222']) def test_unterminated_strings(self): message = "No closing '\"'" @@ -44,28 +44,28 @@ class TestTokenSource(unittest.TestCase): self.check_error([b'"aaa bbb'], message) def test_escaping(self): - self.check([br'"aaa\"bbb"'], - [br'"aaa"bbb"']) - self.check([br'"aaa\\bbb"'], - [br'"aaa\bbb"']) - self.check([br'"aaa\\bbb \"\""'], - [br'"aaa\bbb """']) + self.check([br'"aaa\"bbb"'], + [br'"aaa"bbb"']) + self.check([br'"aaa\\bbb"'], + [br'"aaa\bbb"']) + self.check([br'"aaa\\bbb \"\""'], + [br'"aaa\bbb """']) def test_invalid_escape(self): - self.check([br'"aaa\Zbbb"'], - [br'"aaa\Zbbb"']) + self.check([br'"aaa\Zbbb"'], + [br'"aaa\Zbbb"']) def test_lists(self): - self.check([b'()'], - [b'(', b')']) - self.check([b'(aaa)'], - [b'(', b'aaa', b')']) - self.check([b'(aaa "bbb def" 123)'], - [b'(', b'aaa', b'"bbb def"', b'123', b')']) - self.check([b'(aaa)(bbb ccc)'], - [b'(', b'aaa', b')', b'(', b'bbb', b'ccc', b')']) - self.check([b'(aaa (bbb ccc))'], - [b'(', b'aaa', b'(', b'bbb', b'ccc', b')', b')']) + self.check([b'()'], + [b'(', b')']) + self.check([b'(aaa)'], + [b'(', b'aaa', b')']) + self.check([b'(aaa "bbb def" 123)'], + [b'(', b'aaa', b'"bbb def"', b'123', b')']) + self.check([b'(aaa)(bbb ccc)'], + [b'(', b'aaa', b')', b'(', b'bbb', b'ccc', b')']) + self.check([b'(aaa (bbb ccc))'], + [b'(', b'aaa', b'(', b'bbb', b'ccc', b')', b')']) def test_square_brackets(self): self.check([b'[aaa bbb]'], @@ -99,7 +99,7 @@ class TestTokenSource(unittest.TestCase): source = TokenSource([ (b'abc {7}', b'foo bar'), (b'{5}', b'snafu'), - b')']) + b')']) tokens = iter(source) self.assertEqual(next(tokens), b'abc') self.assertEqual(next(tokens), b'{7}') diff --git a/imapclient/test/test_response_parser.py b/imapclient/test/test_response_parser.py index cc40e43..2b13486 100644 --- a/imapclient/test/test_response_parser.py +++ b/imapclient/test/test_response_parser.py @@ -12,15 +12,21 @@ from datetime import datetime from imapclient.datetime_util import datetime_to_native from imapclient.fixed_offset import FixedOffset -from imapclient.response_parser import parse_response, parse_message_list, parse_fetch_response, ParseError +from imapclient.response_parser import ( + parse_response, + parse_message_list, + parse_fetch_response, + ParseError, +) from imapclient.response_types import Envelope, Address from imapclient.test.util import unittest -#TODO: test invalid dates and times +# TODO: test invalid dates and times CRLF = b'\r\n' + class TestParseResponse(unittest.TestCase): def test_unquoted(self): @@ -60,7 +66,7 @@ class TestParseResponse(unittest.TestCase): b'"" "foo" "BASE64" 4554 73) "MIXED")', ((b'FOO', b'PLAIN', (b'CHARSET', b'US-ASCII'), None, None, b'7BIT', 1152, 23), (b'TEXT', b'PLAIN', (b'CHARSET', b'US-ASCII', b'NAME', b'cc.diff'), - b'', b'foo', b'BASE64', 4554, 73), b'MIXED')) + b'', b'foo', b'BASE64', 4554, 73), b'MIXED')) def test_envelopey(self): self._test(b'(UID 5 ENVELOPE ("internal_date" "subject" ' @@ -111,7 +117,6 @@ class TestParseResponse(unittest.TestCase): ) self._test([(b'{18}', literal_text)], literal_text) - def test_literal_with_more(self): literal_text = add_crlf( b"012\n" @@ -120,7 +125,6 @@ class TestParseResponse(unittest.TestCase): response = [(b'(12 "foo" {18}', literal_text), b")"] self._test(response, (12, b'foo', literal_text)) - def test_quoted_specials(self): self._test(br'"\"foo bar\""', b'"foo bar"') self._test(br'"foo \"bar\""', b'foo "bar"') @@ -191,107 +195,95 @@ class TestParseFetchResponse(unittest.TestCase): def test_basic(self): self.assertEqual(parse_fetch_response([b'4 ()']), {4: {b'SEQ': 4}}) - def test_none_special_case(self): self.assertEqual(parse_fetch_response([None]), {}) - def test_bad_msgid(self): self.assertRaises(ParseError, parse_fetch_response, [b'abc ()']) - def test_bad_data(self): self.assertRaises(ParseError, parse_fetch_response, [b'2 WHAT']) - def test_missing_data(self): self.assertRaises(ParseError, parse_fetch_response, [b'2']) - def test_simple_pairs(self): self.assertEqual(parse_fetch_response([b'23 (ABC 123 StUfF "hello")']), - {23: {b'ABC': 123, - b'STUFF': b'hello', - b'SEQ': 23}}) - + {23: {b'ABC': 123, + b'STUFF': b'hello', + b'SEQ': 23}}) def test_odd_pairs(self): self.assertRaises(ParseError, parse_fetch_response, [b'(ONE)']) self.assertRaises(ParseError, parse_fetch_response, [b'(ONE TWO THREE)']) - def test_UID(self): self.assertEqual(parse_fetch_response([b'23 (UID 76)']), {76: {b'SEQ': 23}}) self.assertEqual(parse_fetch_response([b'23 (uiD 76)']), {76: {b'SEQ': 23}}) - def test_not_uid_is_key(self): self.assertEqual(parse_fetch_response([b'23 (UID 76)'], uid_is_key=False), - {23: {b'UID': 76, - b'SEQ': 23}}) - + {23: {b'UID': 76, + b'SEQ': 23}}) def test_bad_UID(self): self.assertRaises(ParseError, parse_fetch_response, [b'(UID X)']) - def test_FLAGS(self): self.assertEqual(parse_fetch_response([b'23 (FLAGS (\Seen Stuff))']), - {23: {b'SEQ': 23, b'FLAGS': (br'\Seen', b'Stuff')}}) - + {23: {b'SEQ': 23, b'FLAGS': (br'\Seen', b'Stuff')}}) def test_multiple_messages(self): self.assertEqual(parse_fetch_response( - [b"2 (FLAGS (Foo Bar)) ", - b"7 (FLAGS (Baz Sneeve))"]), - { - 2: {b'FLAGS': (b'Foo', b'Bar'), b'SEQ': 2}, - 7: {b'FLAGS': (b'Baz', b'Sneeve'), b'SEQ': 7}, - }) + [b"2 (FLAGS (Foo Bar)) ", + b"7 (FLAGS (Baz Sneeve))"]), + { + 2: {b'FLAGS': (b'Foo', b'Bar'), b'SEQ': 2}, + 7: {b'FLAGS': (b'Baz', b'Sneeve'), b'SEQ': 7}, + }) def test_same_message_appearing_multiple_times(self): # This can occur when server sends unsolicited FETCH responses # (e.g. RFC 4551) self.assertEqual(parse_fetch_response( - [b"2 (FLAGS (Foo Bar)) ", - b"2 (MODSEQ 4)"]), - {2: {b'FLAGS': (b'Foo', b'Bar'), b'SEQ': 2, b'MODSEQ': 4}}) + [b"2 (FLAGS (Foo Bar)) ", + b"2 (MODSEQ 4)"]), + {2: {b'FLAGS': (b'Foo', b'Bar'), b'SEQ': 2, b'MODSEQ': 4}}) def test_literals(self): self.assertEqual(parse_fetch_response([(b'1 (RFC822.TEXT {4}', b'body'), (b' RFC822 {21}', b'Subject: test\r\n\r\nbody'), b')']), - {1: {b'RFC822.TEXT': b'body', - b'RFC822': b'Subject: test\r\n\r\nbody', - b'SEQ': 1}}) - + {1: {b'RFC822.TEXT': b'body', + b'RFC822': b'Subject: test\r\n\r\nbody', + b'SEQ': 1}}) def test_literals_and_keys_with_square_brackets(self): self.assertEqual(parse_fetch_response([(b'1 (BODY[TEXT] {11}', b'Hi there.\r\n'), b')']), - { 1: {b'BODY[TEXT]': b'Hi there.\r\n', - b'SEQ': 1}}) - + {1: {b'BODY[TEXT]': b'Hi there.\r\n', + b'SEQ': 1}}) def test_BODY_HEADER_FIELDS(self): header_text = b'Subject: A subject\r\nFrom: Some one \r\n\r\n' self.assertEqual(parse_fetch_response( [(b'123 (UID 31710 BODY[HEADER.FIELDS (from subject)] {57}', header_text), b')']), - { 31710: {b'BODY[HEADER.FIELDS (FROM SUBJECT)]': header_text, - b'SEQ': 123}}) + {31710: {b'BODY[HEADER.FIELDS (FROM SUBJECT)]': header_text, + b'SEQ': 123}}) def test_BODY(self): - self.check_BODYish_single_part(b'BODY') - self.check_BODYish_multipart(b'BODY') - self.check_BODYish_nested_multipart(b'BODY') + self.check_BODYish_single_part(b'BODY') + self.check_BODYish_multipart(b'BODY') + self.check_BODYish_nested_multipart(b'BODY') def test_BODYSTRUCTURE(self): - self.check_BODYish_single_part(b'BODYSTRUCTURE') - self.check_BODYish_nested_multipart(b'BODYSTRUCTURE') - + self.check_BODYish_single_part(b'BODYSTRUCTURE') + self.check_BODYish_nested_multipart(b'BODYSTRUCTURE') + def check_BODYish_single_part(self, respType): - text = b'123 (UID 317 ' + respType + b'("TEXT" "PLAIN" ("CHARSET" "us-ascii") NIL NIL "7BIT" 16 1))' + text = b'123 (UID 317 ' + respType + \ + b'("TEXT" "PLAIN" ("CHARSET" "us-ascii") NIL NIL "7BIT" 16 1))' parsed = parse_fetch_response([text]) self.assertEqual(parsed, { 317: { @@ -318,9 +310,9 @@ class TestParseFetchResponse(unittest.TestCase): def check_BODYish_nested_multipart(self, respType): text = b'1 (' + respType + b'(' \ b'(' \ - b'("text" "html" ("charset" "utf-8") NIL NIL "7bit" 97 3 NIL NIL NIL NIL)' \ - b'("text" "plain" ("charset" "utf-8") NIL NIL "7bit" 62 3 NIL NIL NIL NIL)' \ - b'"alternative" ("boundary" "===============8211050864078048428==") NIL NIL NIL' \ + b'("text" "html" ("charset" "utf-8") NIL NIL "7bit" 97 3 NIL NIL NIL NIL)' \ + b'("text" "plain" ("charset" "utf-8") NIL NIL "7bit" 62 3 NIL NIL NIL NIL)' \ + b'"alternative" ("boundary" "===============8211050864078048428==") NIL NIL NIL' \ b')' \ b'("text" "plain" ("charset" "utf-8") NIL NIL "7bit" 16 1 NIL ("attachment" ("filename" "attachment.txt")) NIL NIL) ' \ b'"mixed" ("boundary" "===============0373402508605428821==") NIL NIL NIL))' @@ -331,11 +323,14 @@ class TestParseFetchResponse(unittest.TestCase): [ ( [ - (b'text', b'html', (b'charset', b'utf-8'), None, None, b'7bit', 97, 3, None, None, None, None), - (b'text', b'plain', (b'charset', b'utf-8'), None, None, b'7bit', 62, 3, None, None, None, None) + (b'text', b'html', (b'charset', b'utf-8'), None, + None, b'7bit', 97, 3, None, None, None, None), + (b'text', b'plain', (b'charset', b'utf-8'), None, + None, b'7bit', 62, 3, None, None, None, None) ], b'alternative', (b'boundary', b'===============8211050864078048428=='), None, None, None ), - (b'text', b'plain', (b'charset', b'utf-8'), None, None, b'7bit', 16, 1, None, (b'attachment', (b'filename', b'attachment.txt')), None, None) + (b'text', b'plain', (b'charset', b'utf-8'), None, None, b'7bit', 16, 1, + None, (b'attachment', (b'filename', b'attachment.txt')), None, None) ], b'mixed', (b'boundary', b'===============0373402508605428821=='), None, None, None, ), b'SEQ': 1, @@ -348,37 +343,37 @@ class TestParseFetchResponse(unittest.TestCase): body = b'01234567890123456789' self.assertEqual(parse_fetch_response( [(b'123 (UID 367 BODY[]<0> {20}', body), b')']), - { 367: {b'BODY[]<0>': body, - b'SEQ': 123}}) + {367: {b'BODY[]<0>': body, + b'SEQ': 123}}) def test_ENVELOPE(self): envelope_str = (b'1 (ENVELOPE ( ' - b'"Sun, 24 Mar 2013 22:06:10 +0200" ' - b'"subject" ' - b'(("name" NIL "address1" "domain1.com")) ' # from (name and address) - b'((NIL NIL "address2" "domain2.com")) ' # sender (just address) - b'(("name" NIL "address3" "domain3.com") NIL) ' # reply to - b'NIL' # to (no address) - b'((NIL NIL "address4" "domain4.com") ' # cc - b'("person" NIL "address4b" "domain4b.com")) ' - b'NIL ' # bcc - b'"" ' - b'""))') + b'"Sun, 24 Mar 2013 22:06:10 +0200" ' + b'"subject" ' + b'(("name" NIL "address1" "domain1.com")) ' # from (name and address) + b'((NIL NIL "address2" "domain2.com")) ' # sender (just address) + b'(("name" NIL "address3" "domain3.com") NIL) ' # reply to + b'NIL' # to (no address) + b'((NIL NIL "address4" "domain4.com") ' # cc + b'("person" NIL "address4b" "domain4b.com")) ' + b'NIL ' # bcc + b'"" ' + b'""))') output = parse_fetch_response([envelope_str], normalise_times=False) self.assertSequenceEqual(output[1][b'ENVELOPE'], - Envelope( - datetime(2013, 3, 24, 22, 6, 10, tzinfo=FixedOffset(120)), - b"subject", - (Address(b"name", None, b"address1", b"domain1.com"),), - (Address(None, None, b"address2", b"domain2.com"),), - (Address(b"name", None, b"address3", b"domain3.com"),), - None, - (Address(None, None, b"address4", b"domain4.com"), - Address(b"person", None, b"address4b", b"domain4b.com")), - None, b"", b"" - ) + Envelope( + datetime(2013, 3, 24, 22, 6, 10, tzinfo=FixedOffset(120)), + b"subject", + (Address(b"name", None, b"address1", b"domain1.com"),), + (Address(None, None, b"address2", b"domain2.com"),), + (Address(b"name", None, b"address3", b"domain3.com"),), + None, + (Address(None, None, b"address4", b"domain4.com"), + Address(b"person", None, b"address4b", b"domain4b.com")), + None, b"", b"" + ) ) def test_ENVELOPE_with_no_date(self): @@ -399,64 +394,64 @@ class TestParseFetchResponse(unittest.TestCase): output = parse_fetch_response([envelope_str], normalise_times=False) self.assertSequenceEqual(output[1][b'ENVELOPE'], - Envelope( - None, - b"subject", - None, - None, - None, - None, - None, - None, - b"", b"" - ) + Envelope( + None, + b"subject", + None, + None, + None, + None, + None, + None, + b"", b"" + ) ) def test_ENVELOPE_with_invalid_date(self): envelope_str = (b'1 (ENVELOPE ( ' - b'"wtf" ' # bad date - b'"subject" ' - b'NIL NIL NIL NIL NIL NIL ' - b'"" ""))') + b'"wtf" ' # bad date + b'"subject" ' + b'NIL NIL NIL NIL NIL NIL ' + b'"" ""))') output = parse_fetch_response([envelope_str], normalise_times=False) self.assertSequenceEqual(output[1][b'ENVELOPE'], - Envelope( - None, - b"subject", - None, None, None, None, None, None, - b"", b"", - ) + Envelope( + None, + b"subject", + None, None, None, None, None, None, + b"", b"", + ) ) def test_ENVELOPE_with_empty_addresses(self): envelope_str = (b'1 (ENVELOPE ( ' - b'NIL ' - b'"subject" ' - b'(("name" NIL "address1" "domain1.com") NIL) ' - b'(NIL (NIL NIL "address2" "domain2.com")) ' - b'(("name" NIL "address3" "domain3.com") NIL ("name" NIL "address3b" "domain3b.com")) ' - b'NIL' - b'((NIL NIL "address4" "domain4.com") ' - b'("person" NIL "address4b" "domain4b.com")) ' - b'NIL "" ""))') + b'NIL ' + b'"subject" ' + b'(("name" NIL "address1" "domain1.com") NIL) ' + b'(NIL (NIL NIL "address2" "domain2.com")) ' + b'(("name" NIL "address3" "domain3.com") NIL ("name" NIL "address3b" "domain3b.com")) ' + b'NIL' + b'((NIL NIL "address4" "domain4.com") ' + b'("person" NIL "address4b" "domain4b.com")) ' + b'NIL "" ""))') output = parse_fetch_response([envelope_str], normalise_times=False) self.assertSequenceEqual(output[1][b'ENVELOPE'], - Envelope( - None, - b"subject", - (Address(b"name", None, b"address1", b"domain1.com"),), - (Address(None, None, b"address2", b"domain2.com"),), - (Address(b"name", None, b"address3", b"domain3.com"), - Address(b"name", None, b"address3b", b"domain3b.com")), - None, - (Address(None, None, b"address4", b"domain4.com"), - Address(b"person", None, b"address4b", b"domain4b.com")), - None, b"", b"" - ) + Envelope( + None, + b"subject", + (Address(b"name", None, b"address1", b"domain1.com"),), + (Address(None, None, b"address2", b"domain2.com"),), + (Address(b"name", None, b"address3", b"domain3.com"), + Address(b"name", None, b"address3b", b"domain3b.com")), + None, + (Address(None, None, b"address4", b"domain4.com"), + Address(b"person", None, b"address4b", b"domain4b.com")), + None, b"", b"" + ) ) def test_INTERNALDATE(self): @@ -466,14 +461,15 @@ class TestParseFetchResponse(unittest.TestCase): ) self.assertEqual( out[1][b'INTERNALDATE'], - datetime(2007, 2, 9, 17, 8, 8, 0, FixedOffset(-4*60 - 30)) + datetime(2007, 2, 9, 17, 8, 8, 0, FixedOffset(-4 * 60 - 30)) ) def test_INTERNALDATE_normalised(self): output = parse_fetch_response([b'3 (INTERNALDATE " 9-Feb-2007 17:08:08 -0430")']) dt = output[3][b'INTERNALDATE'] self.assertTrue(dt.tzinfo is None) # Returned date should be in local timezone - expected_dt = datetime_to_native(datetime(2007, 2, 9, 17, 8, 8, 0, FixedOffset(-4*60 - 30))) + expected_dt = datetime_to_native( + datetime(2007, 2, 9, 17, 8, 8, 0, FixedOffset(-4 * 60 - 30))) self.assertEqual(dt, expected_dt) def test_mixed_types(self): diff --git a/imapclient/test/test_util_functions.py b/imapclient/test/test_util_functions.py index 47a4c4b..6becfed 100644 --- a/imapclient/test/test_util_functions.py +++ b/imapclient/test/test_util_functions.py @@ -37,6 +37,7 @@ class Test_normalise_text_list(unittest.TestCase): def test_mixed_list(self): self.check(['FOO', b'Bar'], ['FOO', 'Bar']) + class Test_seq_to_parenstr(unittest.TestCase): def check(self, items, expected): @@ -60,6 +61,7 @@ class Test_seq_to_parenstr(unittest.TestCase): def test_mixed_list(self): self.check(['foo', b'BAR'], '(foo BAR)') + class Test_seq_to_parenstr_upper(unittest.TestCase): def check(self, items, expected): @@ -83,6 +85,7 @@ class Test_seq_to_parenstr_upper(unittest.TestCase): def test_mixed_list(self): self.check(['foo', b'BAR'], '(FOO BAR)') + class Test_join_message_ids(unittest.TestCase): def check(self, items, expected): diff --git a/imapclient/test/util.py b/imapclient/test/util.py index 583f906..02d9910 100644 --- a/imapclient/test/util.py +++ b/imapclient/test/util.py @@ -4,6 +4,7 @@ from __future__ import unicode_literals + def find_unittest2(): import unittest if hasattr(unittest, 'skip') and hasattr(unittest, 'loader'): @@ -11,12 +12,14 @@ def find_unittest2(): try: import unittest2 # try for a separately installed unittest2 package except ImportError: - raise ImportError('unittest2 not installed and unittest in standard library is not unittest2') + raise ImportError( + 'unittest2 not installed and unittest in standard library is not unittest2') else: return unittest2 unittest = find_unittest2() + def patch_TestCase(): TestCase = unittest.TestCase # Older versions of unittest2 don't have @@ -24,6 +27,6 @@ def patch_TestCase(): # when you use assertRaisesRegexp. This helps deal with the # mismatch. if not hasattr(TestCase, 'assertRaisesRegex'): - TestCase.assertRaisesRegex = TestCase.assertRaisesRegexp + TestCase.assertRaisesRegex = TestCase.assertRaisesRegexp patch_TestCase() diff --git a/imapclient/tls.py b/imapclient/tls.py index 18e6da0..6c85fde 100644 --- a/imapclient/tls.py +++ b/imapclient/tls.py @@ -10,10 +10,6 @@ It uses ``backports.ssl`` to provide consistent TLS functionality across Python versions. """ - -__all__ = ('create_default_context',) - - import imaplib import socket import sys @@ -23,6 +19,8 @@ try: except ImportError: raise ImportError("backports.ssl is not installed") +__all__ = ('create_default_context',) + _ossl = ssl.ossl @@ -41,6 +39,8 @@ _RESTRICTED_SERVER_CIPHERS = ( ) # TODO: get this into backports.ssl + + def create_default_context(cafile=None, capath=None, cadata=None): """Return a backports.ssl.SSLContext object configured with sensible default settings. diff --git a/imapclient/version.py b/imapclient/version.py index 8953b9d..721b5f4 100644 --- a/imapclient/version.py +++ b/imapclient/version.py @@ -6,6 +6,7 @@ from __future__ import unicode_literals version_info = (1, 0, 0, 'alpha') + def _imapclient_version_string(vinfo): major, minor, micro, releaselevel = vinfo v = '%d.%d' % (major, minor) diff --git a/setup.py b/setup.py index 7e6b689..76f6160 100644 --- a/setup.py +++ b/setup.py @@ -41,9 +41,11 @@ Features: Python versions 2.6, 2.7, 3.3 and 3.4 are officially supported. -IMAPClient includes fairly comprehensive units tests and automated functional tests that can be run against a live IMAP server. +IMAPClient includes comprehensive units tests and automated +functional tests that can be run against a live IMAP server. """ + class TestDiscoverCommand(TestCommand): """ Use unittest2 to discover and run tests @@ -100,5 +102,4 @@ setup(name='IMAPClient', 'Topic :: Internet', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: System :: Networking'], - cmdclass={'test': TestDiscoverCommand}, -) + cmdclass={'test': TestDiscoverCommand}) diff --git a/tox.ini b/tox.ini index 58364f8..d80306d 100644 --- a/tox.ini +++ b/tox.ini @@ -7,3 +7,7 @@ skipsdist=true [testenv] commands=python setup.py test + +[pep8] +max-line-length=100 +ignore=E731