Added pep8 tool config to tox.ini.
Closes #141.
oauth2_client_secret=None,
oauth2_refresh_token=None,
expect_failure=None,
- ))
+ ))
with open(filename, 'r') as fh:
parser.readfp(fh)
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)
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")
# 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)
_oauth2_cache[cache_key] = token
return token
+
def create_client_from_config(conf):
ssl_context = None
if conf.ssl:
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,
client.shutdown()
raise
+
class Bunch(dict):
def __getattr__(self, k):
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]
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.
# 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):
-from __future__ import unicode_literals\r
-\r
-from imapclient import IMAPClient\r
-\r
-# Populate these with actual values\r
-CONSUMER_KEY = '...'\r
-CONSUMER_SECRET = '...'\r
-OAUTH_TOKEN = '...'\r
-OAUTH_TOKEN_SECRET = '...'\r
-\r
-HOST = 'imap.host.com'\r
-URL = "https://somedomain.com/someuser/imap/"\r
-ssl = True\r
-\r
-server = IMAPClient(HOST, use_uid=True, ssl=ssl)\r
-\r
-resp = server.oauth_login(URL, OAUTH_TOKEN, OAUTH_TOKEN_SECRET,\r
- CONSUMER_KEY, CONSUMER_SECRET)\r
-print(resp)\r
-\r
-select_info = server.select_folder('INBOX')\r
-print(select_info)\r
-\r
-server.logout()\r
+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()
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):
# 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
# TODO: module needs refactoring (e.g. variable names suck)
+
def encode(s):
"""Encode a folder name using IMAP modified UTF-7 encoding.
AMPERSAND_ORD = byte2int(b'&')
DASH_ORD = byte2int(b'-')
+
def decode(s):
"""Decode a folder name from IMAP modified UTF-7 encoding to unicode.
# 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
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))
% 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)
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.
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)]
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) > ")
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))
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:
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')
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
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:]
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
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):
import sys
import imaplib
+
def _is_affected_version(sys_version):
sys_version = sys_version[:3]
if sys_version < (2, 5, 0):
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
from .config import parse_config_file, create_client_from_config
+
def command_line():
p = OptionParser()
p.add_option('-H', '--host', dest='host', action='store',
opts.stream = False
return opts
+
def main():
opts = command_line()
print('Connecting...')
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)
if self.is_gmail():
self.client.noop()
+
class TestGeneral(_TestBase):
"""
Tests that don't involve message number/UID functionality.
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()
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)
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()
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
finally:
self.client.folder_encode = True
-
def test_rename_folder(self):
folders = self.add_prefix_to_folders([
'foobar',
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'
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)
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
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)
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)
return LiveTest
+
def quiet_logout(client):
"""Log out a connection, ignoring errors (say because the connection is down)
"""
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.
return False
return isinstance(b, type(a))
+
def argv_error(msg):
print(msg, file=sys.stderr)
print(file=sys.stderr)
print("usage: %s <livetest.ini> [ optional unittest arguments ]" % sys.argv[0], file=sys.stderr)
sys.exit(1)
+
def parse_argv():
args = sys.argv[1:]
if not args:
host_config = parse_config_file(ini_path)
return host_config
+
def probe_host(config):
client = create_client_from_config(config)
ns = client.namespace()
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()
# 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):
self.src_text = resp_record
self.literal = None
-
def __iter__(self):
return PushableIterator(six.iterbytes(self.src_text))
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
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']
_msg_id_pattern = re.compile("(\d+(?: +\d+)*)")
+
def parse_message_list(data):
"""Parse a list of message ids and return them as a list.
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')
except ValueError:
return None
+
def _convert_ENVELOPE(envelope_response, normalise_times=True):
dt = None
if envelope_response[0]:
message_id=envelope_response[9]
)
+
def atom(src, token):
if token == b'(':
return parse_tuple(src)
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]
else:
return token
+
def parse_tuple(src):
out = []
for token in src:
# no terminator
raise ParseError('Tuple incomplete before "(%s"' % _fmt_tuple(out))
+
def _fmt_tuple(t):
return ' '.join(str(item) for item in t)
from .testable_imapclient import TestableIMAPClient as IMAPClient
from .util import unittest
+
class IMAPClientTest(unittest.TestCase):
def setUp(self):
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):
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')
from imapclient.test.util import unittest
from imapclient.fixed_offset import FixedOffset
+
class TestFixedOffset(unittest.TestCase):
def _check(self, offset, expected_delta, expected_name):
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):
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
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
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')
['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'],
]
self.assertIsInstance(encoded, binary_type)
self.assertEqual(encoded, output)
-
def test_decode(self):
for (input, output) in self.tests:
decoded = decode(output)
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)
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',
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):
((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'',
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"',
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')])
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(
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:
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:
client._imap.tagged_commands = {sentinel.tag: None}
counter = itertools.count()
+
def fake_get_response():
count = six.next(counter)
if count == 0:
self.assertIn('one', output)
self.assertIn('two', output)
+
class TestTimeNormalisation(IMAPClientTest):
def test_default(self):
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)
(("", "/"),),
(("~", "/"),),
(("#shared/", "/"), ("#public/", "/"), ("#ftp/", "/"), ("#news.", ".")),
- ))
+ ))
class TestCapabilities(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', [])
[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 '\"'"
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]'],
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}')
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):
b'"<hi.there>" "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'<hi.there>', b'foo', b'BASE64', 4554, 73), b'MIXED'))
+ b'<hi.there>', b'foo', b'BASE64', 4554, 73), b'MIXED'))
def test_envelopey(self):
self._test(b'(UID 5 ENVELOPE ("internal_date" "subject" '
)
self._test([(b'{18}', literal_text)], literal_text)
-
def test_literal_with_more(self):
literal_text = add_crlf(
b"012\n"
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"')
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 <someone@mail.com>\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: {
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))'
[
(
[
- (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,
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'"<reply-to-id>" '
- b'"<msg_id>"))')
+ 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'"<reply-to-id>" '
+ b'"<msg_id>"))')
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"<reply-to-id>", b"<msg_id>"
- )
+ 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"<reply-to-id>", b"<msg_id>"
+ )
)
def test_ENVELOPE_with_no_date(self):
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"<reply-to-id>", b"<msg_id>"
- )
+ Envelope(
+ None,
+ b"subject",
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ b"<reply-to-id>", b"<msg_id>"
+ )
)
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'"<reply-to-id>" "<msg_id>"))')
+ b'"wtf" ' # bad date
+ b'"subject" '
+ b'NIL NIL NIL NIL NIL NIL '
+ b'"<reply-to-id>" "<msg_id>"))')
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"<reply-to-id>", b"<msg_id>",
- )
+ Envelope(
+ None,
+ b"subject",
+ None, None, None, None, None, None,
+ b"<reply-to-id>", b"<msg_id>",
+ )
)
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 "<reply-to-id>" "<msg_id>"))')
+ 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 "<reply-to-id>" "<msg_id>"))')
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"<reply-to-id>", b"<msg_id>"
- )
+ 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"<reply-to-id>", b"<msg_id>"
+ )
)
def test_INTERNALDATE(self):
)
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):
def test_mixed_list(self):
self.check(['FOO', b'Bar'], ['FOO', 'Bar'])
+
class Test_seq_to_parenstr(unittest.TestCase):
def check(self, items, expected):
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):
def test_mixed_list(self):
self.check(['foo', b'BAR'], '(FOO BAR)')
+
class Test_join_message_ids(unittest.TestCase):
def check(self, items, expected):
from __future__ import unicode_literals
+
def find_unittest2():
import unittest
if hasattr(unittest, 'skip') and hasattr(unittest, 'loader'):
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
# 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()
across Python versions.
"""
-
-__all__ = ('create_default_context',)
-
-
import imaplib
import socket
import sys
except ImportError:
raise ImportError("backports.ssl is not installed")
+__all__ = ('create_default_context',)
+
_ossl = ssl.ossl
)
# 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.
version_info = (1, 0, 0, 'alpha')
+
def _imapclient_version_string(vinfo):
major, minor, micro, releaselevel = vinfo
v = '%d.%d' % (major, minor)
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
'Topic :: Internet',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: System :: Networking'],
- cmdclass={'test': TestDiscoverCommand},
-)
+ cmdclass={'test': TestDiscoverCommand})
[testenv]
commands=python setup.py test
+
+[pep8]
+max-line-length=100
+ignore=E731