.tox/
^mock-.+.egg.*
^setuptools-.+
+^unittest2-.+
+^six-.+
+^argparse-.+\.egg$
+^.eggs/
24bb7a2b8662296740d9d7326644b196fe779395 0.10.2
24bb7a2b8662296740d9d7326644b196fe779395 0.10.2
64006446109d81f7f966d532c6508f8d2091759f 0.10.2
+4c11ffc3c77bbf9e597773e6d9b53585bb163b4b 0.11
+4c11ffc3c77bbf9e597773e6d9b53585bb163b4b 0.11
+0000000000000000000000000000000000000000 0.11
+0000000000000000000000000000000000000000 0.11
+74d56cfb324183fdbf074d526927fd1b20def87b 0.11
+10c1e06ec8f27f48eb118ce7fdd988143d3cfc59 0.12
+c076ec55a74f8ae8195dbac440fd0c83b89eafb8 0.13
-This file contains information for those wishing to modify IMAPClient
-and contribute back to the project.
+=============================
+ Contributing To The Project
+=============================
+The best way to contribute changes to IMAPClient is to fork the
+official repository on bitbucket, make changes to your personal fork
+and then submit a pull request.
-Source Code
------------
+Discussion on the mailing list before undertaking development is
+highly encouraged for potentially major changes.
+
+Although not essential, it will make the project maintainer a much
+happier person if change submissions include appropriate updates to
+unit tests and the live tests. Please ask if you're unsure how of how
+the tests work.
+
+Please read on if you plan on submitting changes to IMAPClient.
+
+=============
+ Source Code
+=============
The official source code repository for IMAPClient can be found on
bitbucket at: https://bitbucket.org/mjs0/imapclient/
-Any major feature branches will also be found on bitbucket as forks of
-this repository.
+Any major feature work will also be found as separate forks on
+bitbucket.
Branches
---------
+========
[Note that the branching scheme discussed here started to be used as
of the 0.9.2 release of IMAPClient]
http://stevelosh.com/blog/2010/05/mercurial-workflows-stable-default/
Release Tags
-------------
+============
Each released version is available in the IMAPClient repository
as a Mercurial tag (e.g. "0.9.1"). Release tags will always be created
on the stable branch (as described above).
-Unit Tests
-----------
+============
+ Unit Tests
+============
There are comprehensive unit tests for the server response parser and
a number of other parts of the code. These tests use the unittest2
package which is also included as the standard unittest package in
Python 2.7 and 3.2 onwards.
+Running Unit Tests
+==================
To run the tests run::
python setup.py test
many of the tests.
Where unittest2 is included in the standard library (eg. Python 2.7
-and 3.2) you can also run all unit tests like this (from the root
+and 3.2+) you can also run all unit tests like this (from the root
directory of the IMAPClient source)::
python -m unittest discover
unit2.py discover
Running the Unit Tests Against Multiple Python Versions
--------------------------------------------------------
+=======================================================
It is possible to run the unit tests against all supported Python
versions at once using `tox`_. Once installed, the ``tox`` command
will use the tox.ini file in the root of the source directory and run
the unit tests against the Python versions officially supported by
-IMAPClient.
-
-Contributing To The Project
----------------------------
-The best way to contribute changes to IMAPClient is to fork the
-official repository on bitbucket, make changes to your personal fork
-and then submit a pull request.
-
-Discussion on the mailing list before undertaking development is
-highly encouraged for potentially major changes.
-
-Although not essential, it will make the project maintainer a much
-happier person if change submissions include appropriate updates to
-unit tests and the live tests. Please ask if you're unsure how of how
-the tests work.
+IMAPClient (provided these versions of Python are installed!).
.. _`tox`: http://testrun.org/tox/
+
+Writing Unit Tests
+==================
+Protocol level unit tests should not act against a real IMAP server
+but should use canned data instead. The IMAPClientTest base class
+should typically be used as the base class for any tests - it provides
+a mock IMAPClient instance at `self.client`. See the tests in
+imapclient/tests/test_imapclient.py for examples of how to write unit
+tests using this approach.
+======
+ 0.13
+======
+
+Added support for the ID command [NEW]
+--------------------------------------
+As per RFC2971. Thanks to Eben Freeman from Nylas.
+
+Fix exception with NIL address in envelope address list
+-------------------------------------------------------
+Thanks to Thomas Steinacher for this fix.
+
+Fixed handling of NIL in SEARCH response
+----------------------------------------
+Fixed a regression in the handling of NIL/None SEARCH
+responses. Thanks again to Thomas Steinacher.
+
+Date parsing fixes
+------------------
+Don't traceback when an unparsable date is seen in ENVELOPE
+responses. None is returned instead.
+
+Support quirky timestamp strings which use dots for the time
+separator.
+
+Removed horrible INTERNALDATE parsing code (use parse_to_datetime
+instead).
+
+datetime_to_imap has been moved to the datetime_util module and is now
+called datetime_to_INTERNALDATE. This will only affect you in the
+unlikely case that you were importing this function out of the
+IMAPClient package.
+
+Other
+-----
+ * The docs for various IMAPClient methods, and the HACKING.rst file
+ have been updated.
+ * CONDSTORE live test is now more reliable (especially when running
+ against Gmail)
+
+======
+ 0.12
+======
+
+Fixed unicode handling [API CHANGE]
+-----------------------------------
+During the work to support Python 3, IMAPClient was changed to do
+return unicode for most responses. This was a bad decision, especially
+because it effectively breaks content that uses multiple encodings
+(e.g. RFC822 responses). This release includes major changes so that
+most responses are returned as bytes (Python 3) or str (Python
+2). This means that correct handling of response data is now possible
+by code using IMAPClient.
+
+Folder name handling has also been cleaned up as part of this work. If
+the ``folder_encode`` attribute is ``True`` (the default) then folder
+names will **always** be returned as unicode. If ``folder_encode`` is
+False then folder names will always be returned as bytes/strs.
+
+Code using IMAPClient will most likely need to be updated to account
+these unicode handling changes.
+
+Many thanks to Inbox (now Nilas, https://nilas.com/) for sponsoring this
+work.
+
+Extra __init__ keyword args are passed through [NEW]
+----------------------------------------------------
+Any unused keyword arguments passed to the IMAPClient initialiser will
+now be passed through to the underlying imaplib IMAP4, IMAP4_SSL or
+IMAP4_stream class. This is specifically to allow the use of imaplib
+features that control certificate validation (if available with the
+version of Python being used).
+
+Thanks to Chris Arndt for this change.
+
+MODSEQ parts in SEARCH responses are now handled
+------------------------------------------------
+If the CONDSTORE extension is supported by a server and a MODSEQ
+criteria was used with search(), a TypeError could occur. This has now
+been fixed and the MODSEQ value returned by the server is now
+available via an attribute on the returned list of ids.
+
+Minor Changes
+-------------
+* Small tweaks to support Python 3.4.
+* The deprecated get_folder_delimiter() method has been removed.
+* More control over OAUTH2 parameters. Thanks to Phil Peterson for
+ this.
+* Fixed livetest/interact OAUTH handling under Python 3.
+
+========
+ 0.11.1
+========
+
+* Close folders during livetest cleanup so that livetests work with
+ newer Dovecot servers (#131)
+
======
0.11
======
- Convenience methods are provided for commonly used functionality.
- Exceptions are raised when errors occur.
-Python versions 2.6, 2.7, 3.2 and 3.3 are officially supported.
+Python versions 2.6, 2.7, 3.2, 3.3 and 3.4 are officially supported.
+
+The current stable version of IMAPClient is 0.13. It is licensed under
+the New BSD License.
Why IMAPClient?
---------------
IMAPClient actually uses imaplib internally. This may change at some
point in the future.
-
-Current Status
---------------
-IMAPClient is currently under development but it is unlikely that
-the existing API will change in backwards-incompatible ways. Changes
-planned for the near future will only add extra functionality to the
-API.
-
-You should feel confident using IMAPClient for production
-purposes. Any problems found will be fixed quickly once reported.
-
-The project's home page is a Trac instance at: http://imapclient.freshfoo.com/
-
-Details about upcoming versions and planned features/fixes can be
-found there.
-
-Using IMAPClient
-----------------
+Installing IMAPClient
+---------------------
IMAPClient is listed on the PyPI (Python Package Index). To install
via PyPI use the pip or easy_install tools::
easy_install IMAPClient
-To install from the source distribution::
+The source distributions of all IMAPClient versions are available at
+http://freshfoo.com/projects/IMAPClient/. Alternatively you can also
+use the PyPI page at https://pypi.python.org/pypi/IMAPClient/.
+
+To install from source run::
python setup.py install
Documentation
-------------
-HTML documentation can be found at doc/html in the source
-distribution. The documentation is also available online at:
-http://imapclient.readthedocs.org/
+IMAPClient's manual is available at http://imapclient.readthedocs.org/
-The Sphinx source is at doc/src. If Sphinx is installed, the
-documentation can be rebuilt using::
+The `NEWS <https://bitbucket.org/mjs0/imapclient/src/tip/NEWS.rst>`_
+file also has useful information.
+
+The HTML manual can also be found at doc/html in the source
+distribution. The Sphinx source is at doc/src. If Sphinx is installed,
+the documentation can be rebuilt using::
python setup.py build_sphinx
See imapclient/examples/example.py for a sample of how to use
-IMAPClient. If the IMAPClient was installed from PyPI the examples
+IMAPClient. If the IMAPClient was installed from PyPI, the examples
subdirectory can be found under the imapclient package installation
directory.
+Current Status
+--------------
+IMAPClient is currently under development but it is unlikely that
+the existing API will change in backwards-incompatible ways. Changes
+planned for the near future will only add extra functionality to the
+API.
+
+You should feel confident using IMAPClient for production
+purposes. Any problems found will be fixed quickly once reported.
+
+The project's home page is http://imapclient.freshfoo.com/ (this
+currently redirects to the IMAPClient Bitbucket site). Details about
+upcoming versions and planned features/fixes can be found in the issue
+tracker on Bitbucket. The maintainer also blogs about IMAPClient
+news. Those articles can be found `here
+<http://freshfoo.com/blog/tags/imapclient>`_.
+
Mailing List
------------
The IMAPClient mailing list can be used to ask IMAPClient related
Please send the output of livetest.py to the mailing list if it fails
to run successfully against a particular IMAP server. Reports of
successful runs are also welcome. Please include the type and version
-of the IMAP server, if known.
+of the IMAP server, if known.
\ No newline at end of file
Gmail search support (X-GM-RAW).
Naveen Nathan
- ENVELOPE FETCH response parsing
-
+ ENVELOPE FETCH response parsing.
+
+Chris Arndt
+ Pass-through imaplib kwargs.
+
+Phil Peterson
+ OAUTH2 improvements.
+
+Thomas Steinacher
+ NIL handling fixes.
+
+Eben Freeman
+ ID support
+
Bug Reports
------------
Benjamin Morrise
Brandon Rhodes
-
External Projects
-----------------
IMAPClient uses Michael's excellent 'Mock' package.
cross-version Python compatibility.
(https://pypi.python.org/pypi/six)
+Other Contributions
+-------------------
+Nilas supports development of IMAPClient.
+http://nilas.com/
+
The project was started while the author was working at NetBox Blue.
-(http://netboxblue.com/)
+http://netboxblue.com/
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
-extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode']
+extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode',
+ 'sphinx.ext.intersphinx']
+
+intersphinx_mapping = {'python':('http://docs.python.org/3', None)}
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
to the base protocol. These are referred to in the documentation below
where relevant.
-Python versions 2.6, 2.7, 3.2 and 3.3 are officially supported.
+Python versions 2.6, 2.7, 3.2, 3.3 and 3.4 are officially supported.
A Simple Example
----------------
75 messages that aren't deleted
Messages:
- ID 38273: 1775 bytes, flags=('NonJunk',)
- ID 36459: 2833 bytes, flags=('\\Flagged', '\\Seen')
- ID 34693: 2874 bytes, flags=('\\Flagged', '\\Seen')
- ID 38066: 5368 bytes, flags=('\\Flagged', '\\Seen')
- ID 38154: 9079 bytes, flags=('\\Seen', 'NonJunk')
- ID 14099: 3322 bytes, flags=('\\Flagged', '\\Seen', '$Label1')
- ID 34196: 9163 bytes, flags=('\\Answered', '\\Seen')
- ID 35349: 4266 bytes, flags=('\\Flagged', '\\Seen')
- ID 29335: 5617 bytes, flags=('\\Flagged', '\\Seen', 'NonJunk')
- ID 38041: 7649 bytes, flags=('\\Seen', 'NonJunk')
- ID 22310: 976108 bytes, flags=('\\Flagged', '\\Seen', '$Label1')
- ID 6439: 3792 bytes, flags=('\\Flagged', '\\Seen', '$Label1', 'Junk')
+ ID 38273: 1775 bytes, flags=(b'NonJunk',)
+ ID 36459: 2833 bytes, flags=(b'\\Flagged', v'\\Seen')
+ ID 34693: 2874 bytes, flags=(b'\\Flagged', v'\\Seen')
+ ID 38066: 5368 bytes, flags=(b'\\Flagged', v'\\Seen')
+ ID 38154: 9079 bytes, flags=(b'\\Seen', b'NonJunk')
+ ID 14099: 3322 bytes, flags=(b'\\Flagged', b'\\Seen', b'$Label1')
+ ID 34196: 9163 bytes, flags=(b'\\Answered', b'\\Seen')
+ ID 35349: 4266 bytes, flags=(b'\\Flagged', b'\\Seen')
+ ID 29335: 5617 bytes, flags=(b'\\Flagged', b'\\Seen', b'NonJunk')
+ ID 38041: 7649 bytes, flags=(b'\\Seen', b'NonJunk')
+ ID 22310: 976108 bytes, flags=(b'\\Flagged', b'\\Seen', b'$Label1')
+ ID 6439: 3792 bytes, flags=(b'\\Flagged', b'\\Seen', b'$Label1', b'Junk')
Concepts
for arbitrary unicode characters (eg. non-English characters) to be
used in folder names.
-All folder names returned by IMAPClient are always returned as unicode
-strings.
-
The ampersand character ("&") has special meaning in IMAP folder
names. IMAPClient automatically escapes and unescapes this character
so that the caller doesn't have to.
Automatic folder name encoding and decoding can be enabled or disabled
with the *folder_encode* attribute. It defaults to True.
+If *folder_encode* is True, all folder names returned by IMAPClient
+are always returned as unicode strings. If *folder_encode* is False,
+folder names are returned as str (Python 2) or bytes (Python 3).
+
Exceptions
~~~~~~~~~~
The IMAP related exceptions that will be raised by this class are:
the help (--help) for more details. You'll be prompted for a username
and password if one isn't provided on the command line.
+The connected IMAPClient instance is available as the variable "c".
+
If installed, IPython will be used as the embedded shell. Otherwise
the basic built-in Python shell will be used.
IMAPClient instance is "c"
In [1]: c.select_folder('inbox')
Out[1]:
- {'EXISTS': 2,
- 'FLAGS': ('\\Answered',
- '\\Flagged',
- '\\Deleted',
- '\\Seen',
- '\\Draft'),
- 'PERMANENTFLAGS': ('\\Answered',
- '\\Flagged',
- '\\Deleted',
- '\\Seen',
- '\\Draft'),
- 'READ-WRITE': True,
- 'RECENT': 0,
- 'UIDNEXT': 1339,
- 'UIDVALIDITY': 1239278212}
+ {b'EXISTS': 2,
+ b'FLAGS': (b'\\Answered',
+ b'\\Flagged',
+ b'\\Deleted',
+ b'\\Seen',
+ b'\\Draft'),
+ b'PERMANENTFLAGS': (b'\\Answered',
+ b'\\Flagged',
+ b'\\Deleted',
+ b'\\Seen',
+ b'\\Draft'),
+ b'READ-WRITE': True,
+ b'RECENT': 0,
+ b'UIDNEXT': 1339,
+ b'UIDVALIDITY': 1239278212}
In [2]: c.search()
Out[2]: [1123, 1233]
In [3]: c.logout()
- Out[3]: 'Logging out'
+ Out[3]: b'Logging out'
-Note that the connected IMAPClient instance is available as the variable "c".
+External Documentation
+----------------------
+The `Unofficial IMAP Protocol Wiki <http://www.imapwiki.org/>`_ is
+very useful when writing IMAP related software and is highly
+recommended.
from __future__ import unicode_literals
-version_info = (0, 11, 0, 'final')
+version_info = (0, 13, 0, 'final')
def _imapclient_version_string(vinfo):
major, minor, micro, releaselevel = vinfo
from configparser import SafeConfigParser, NoOptionError
import imapclient
-import urllib
+from .six.moves.urllib.request import urlopen
+from .six.moves.urllib.parse import urlencode
try:
import json
def refresh_oauth2_token(client_id, client_secret, refresh_token):
if not json:
raise RuntimeError("livetest OAUTH2 functionality relies on 'json' module")
- post = dict(client_id=client_id,
- client_secret=client_secret,
- refresh_token=refresh_token,
- grant_type='refresh_token')
- response = urllib.urlopen('https://accounts.google.com/o/oauth2/token',
- urllib.urlencode(post)).read()
- return json.loads(response)['access_token']
+ post = dict(client_id=client_id.encode('ascii'),
+ client_secret=client_secret.encode('ascii'),
+ refresh_token=refresh_token.encode('ascii'),
+ grant_type=b'refresh_token')
+ response = urlopen('https://accounts.google.com/o/oauth2/token',
+ urlencode(post).encode('ascii')).read()
+ return json.loads(response.decode('ascii'))['access_token']
# Tokens are expensive to refresh so use the same one for the duration of the process.
_oauth2_cache = {}
from __future__ import unicode_literals
+import re
from datetime import datetime
from email.utils import parsedate_tz
If normalise is False, then the returned datetime will be
unadjusted but will contain timezone information as per the input.
"""
- time_tuple = parsedate_tz(timestamp)
+ time_tuple = parsedate_tz(_munge(timestamp))
if time_tuple == None:
raise ValueError("couldn't parse datetime %r" % timestamp)
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.
+
+ If timezone information is missing the current system
+ timezone is used.
+ """
+ if not dt.tzinfo:
+ dt = dt.replace(tzinfo=FixedOffset.for_system())
+ return dt.strftime("%d-%b-%Y %H:%M:%S %z")
+
+
+# Matches timestamp strings where the time separator is a dot (see
+# 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):
+ return s.replace(".", ":")
+ return s
response = server.fetch(messages, ['FLAGS', 'RFC822.SIZE'])
for msgid, data in response.iteritems():
print(' ID %d: %d bytes, flags=%s' % (msgid,
- data['RFC822.SIZE'],
- data['FLAGS']))
+ data[b'RFC822.SIZE'],
+ data[b'FLAGS']))
from __future__ import unicode_literals
-from .six import text_type, binary_type, iteritems
+from .six import binary_type, text_type, byte2int, iterbytes, unichr
+
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.
- Despite the function's name, the output is still a unicode string.
+ Input is unicode; output is bytes (Python 3) or str (Python 2). If
+ non-unicode input is provided, the input is returned unchanged.
"""
if not isinstance(s, text_type):
return s
def extend_result_if_chars_buffered():
if _in:
- r.extend(['&', modified_utf7(''.join(_in)), '-'])
+ r.extend([b'&', modified_utf7(''.join(_in)), b'-'])
del _in[:]
for c in s:
if ord(c) in PRINTABLE:
extend_result_if_chars_buffered()
- r.append(c)
+ r.append(c.encode('latin-1'))
elif c == '&':
extend_result_if_chars_buffered()
- r.append('&-')
+ r.append(b'&-')
else:
_in.append(c)
extend_result_if_chars_buffered()
- return ''.join(r)
+ return b''.join(r)
+
+
+AMPERSAND_ORD = byte2int(b'&')
+DASH_ORD = byte2int(b'-')
def decode(s):
"""Decode a folder name from IMAP modified UTF-7 encoding to unicode.
- Despite the function's name, the input may still be a unicode
- string. If the input is bytes, it's first decoded to unicode.
+ Input is bytes (Python 3) or str (Python 2); output is always
+ unicode. If non-bytes/str input is provided, the input is returned
+ unchanged.
"""
- if isinstance(s, binary_type):
- s = s.decode('latin-1')
- if not isinstance(s, text_type):
+
+ if not isinstance(s, binary_type):
return s
r = []
- _in = []
- for c in s:
- if c == '&' and not _in:
- _in.append('&')
- elif c == '-' and _in:
+ _in = bytearray()
+ for c in iterbytes(s):
+ if c == AMPERSAND_ORD and not _in:
+ _in.append(c)
+ elif c == DASH_ORD and _in:
if len(_in) == 1:
r.append('&')
else:
- r.append(modified_deutf7(''.join(_in[1:])))
- _in = []
+ r.append(modified_deutf7(_in[1:]))
+ _in = bytearray()
elif _in:
_in.append(c)
else:
- r.append(c)
+ r.append(unichr(c))
if _in:
- r.append(modified_deutf7(''.join(_in[1:])))
-
+ r.append(modified_deutf7(_in[1:]))
return ''.join(r)
+
def modified_utf7(s):
- # encode to utf-7: '\xff' => b'+AP8-', decode from latin-1 => '+AP8-'
- s_utf7 = s.encode('utf-7').decode('latin-1')
- return s_utf7[1:-1].replace('/', ',')
+ s_utf7 = s.encode('utf-7')
+ return s_utf7[1:-1].replace(b'/', b',')
+
def modified_deutf7(s):
- s_utf7 = '+' + s.replace(',', '/') + '-'
- # encode to latin-1: '+AP8-' => b'+AP8-', decode from utf-7 => '\xff'
- return s_utf7.encode('latin-1').decode('utf-7')
+ s_utf7 = b'+' + s.replace(b',', b'/') + b'-'
+ return s_utf7.decode('utf-7')
from __future__ import unicode_literals
import imaplib
+import itertools
import select
import socket
import sys
import re
-import warnings
from datetime import datetime
from operator import itemgetter
-from . import response_lexer
-
# Confusingly, this module is for OAUTH v1, not v2
try:
import oauth2 as oauth_module
except ImportError:
oauth_module = None
+from . import response_lexer
+from .datetime_util import datetime_to_INTERNALDATE
from .imap_utf7 import encode as encode_utf7, decode as decode_utf7
-from .fixed_offset import FixedOffset
-from .six import moves, iteritems, text_type, integer_types, PY3, binary_type
+from .response_types import SearchIds
+from .six import moves, iteritems, text_type, integer_types, PY3, binary_type, string_types
xrange = moves.xrange
if PY3:
if 'XLIST' not in imaplib.Commands:
imaplib.Commands['XLIST'] = imaplib.Commands['LIST']
+
# ...and IDLE
if 'IDLE' not in imaplib.Commands:
imaplib.Commands['IDLE'] = imaplib.Commands['APPEND']
+# and ID. RFC2971 says that this command is valid in all states, 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')
+
+
# System flags
DELETED = r'\Deleted'
SEEN = r'\Seen'
class IMAPClient(object):
- """
- A connection to the IMAP server specified by *host* is made when
- the class is instantiated.
+ """A connection to the IMAP server specified by *host* is made when
+ this class is instantiated.
*port* defaults to 143, or 993 if *ssl* is ``True``.
``False``). This is useful for exotic connection or authentication
setups.
+ Additional keyword arguments are passed through to the constructor
+ of the :py:class:`imaplib.IMAP4` class, or
+ :py:class:`imaplib.IMAP4_SSL` when *ssl* is ``True`` (these are
+ used by ``IMAPClient`` internally). This allows passing SSL
+ related parameters such as *keyfile*, *certfile* and *ssl_context*
+ (Python version dependent). For details, see the :py:mod:`imaplib`
+ documentation in the standard library reference.
+
+ .. note::
+
+ Support for passthrough keyword arguments may be removed in
+ some future version of IMAPClient. Backwards compatibility is
+ not guaranteed for this feature.
+
The *normalise_times* attribute specifies whether datetimes
returned by ``fetch()`` are normalised to the local system time
and include no timezone information (native), or are datetimes
By default, debug output goes to stderr. The *log_file* attribute
can be assigned to an alternate file handle for writing debug
output to.
+
"""
Error = imaplib.IMAP4.error
AbortError = imaplib.IMAP4.abort
ReadOnlyError = imaplib.IMAP4.readonly
- def __init__(self, host, port=None, use_uid=True, ssl=False, stream=False):
+ def __init__(self, host, port=None, use_uid=True, ssl=False, stream=False,
+ **kwargs):
if stream:
if port is not None:
raise ValueError("can't set 'port' when 'stream' True")
self.normalise_times = True
self._cached_capabilities = None
- self._imap = self._create_IMAP4()
+ self._imap = self._create_IMAP4(**kwargs)
self._imap._mesg = self._log # patch in custom debug log method
self._idle_tag = None
- def _create_IMAP4(self):
+ def _create_IMAP4(self, **kwargs):
# Create the IMAP instance in a separate method to make unit tests easier
if self.stream:
return imaplib.IMAP4_stream(self.host)
ImapClass = self.ssl and imaplib.IMAP4_SSL or imaplib.IMAP4
- return ImapClass(self.host, self.port)
+ return ImapClass(self.host, self.port, **kwargs)
def login(self, username, password):
"""Login using *username* and *password*, returning the
else:
raise self.Error('The optional oauth2 package is needed for OAUTH authentication')
- def oauth2_login(self, user, access_token):
+ def oauth2_login(self, user, access_token, mech='XOAUTH2', vendor=None):
"""Authenticate using the OAUTH2 method.
- This only works with IMAP servers that support OAUTH2 (e.g. Gmail).
+ Gmail and Yahoo both support the 'XOAUTH2' mechanism, but Yahoo requires
+ the 'vendor' portion in the payload.
"""
- auth_string = lambda x: 'user=%s\1auth=Bearer %s\1\1' % (user, access_token)
- return self._command_and_check('authenticate', 'XOAUTH2', auth_string)
+ auth_string = 'user=%s\1auth=Bearer %s\1' % (user, access_token)
+ if vendor:
+ auth_string += 'vendor=%s\1' % vendor
+ auth_string += '\1'
+ return self._command_and_check('authenticate', mech, lambda x: auth_string)
def logout(self):
"""Logout, returning the server response.
"""
typ, data = self._imap.logout()
- data = from_bytes(data)
self._check_resp('BYE', 'logout', typ, data)
return data[0]
+ def id_(self, parameters=None):
+ """Issue the ID command, returning a dict of server implementation
+ fields.
+
+ *parameters* should be specified as a dictionary of field/value pairs,
+ for example: ``{"name": "IMAPClient", "version": "0.12"}``
+ """
+ if not self.has_capability('ID'):
+ raise ValueError('server does not support IMAP ID extension')
+ if parameters is None:
+ args = 'NIL'
+ else:
+ if not isinstance(parameters, dict):
+ raise TypeError("'parameters' should be a dictionary")
+ args = seq_to_parenstr(
+ _quote(v) for v in
+ itertools.chain.from_iterable(parameters.items()))
+
+ typ, data = self._imap._simple_command('ID', args)
+ self._checkok('id', typ, data)
+ typ, data = self._imap._untagged_response(typ, data, 'ID')
+ return parse_response(data)
+
def capabilities(self):
"""Returns the server capability list.
# If server returned an untagged CAPABILITY response (during
# authentication), cache it and return that.
- response = self._imap.untagged_responses.pop('CAPABILITY', None)
+
+ untagged = normalise_untagged_responses(self._imap.untagged_responses)
+ response = untagged.pop(b'CAPABILITY', None)
if response:
return self._save_capabilities(response[0])
# Just return capabilities that imaplib grabbed at connection
# time (pre-auth)
- return from_bytes(self._imap.capabilities)
+ return tuple(to_bytes(c) for c in self._imap.capabilities)
def _save_capabilities(self, raw_response):
- raw_response = from_bytes(raw_response)
+ raw_response = to_bytes(raw_response)
self._cached_capabilities = tuple(raw_response.upper().split())
return self._cached_capabilities
# capabilities may in the future be named SORT2 which is
# still compatible with the current standard and will not
# be detected by this method.
- return capability.upper() in self.capabilities()
+ return to_bytes(capability).upper() in self.capabilities()
def namespace(self):
"""Return the namespace for the account as a (personal, other,
See :rfc:`2342` for more details.
"""
data = self._command_and_check('namespace')
- return Namespace(*parse_response(data))
-
- def get_folder_delimiter(self):
- """Return the folder separator used by the IMAP server.
-
- .. warning::
-
- The implementation just picks the first folder separator
- from the first namespace returned. This is not
- particularly sensible. Use namespace instead().
- """
- warnings.warn(DeprecationWarning('get_folder_delimiter is going away. Use namespace() instead.'))
- for part in self.namespace():
- for ns in part:
- return ns[1]
- raise self.Error('could not determine folder separator')
+ parts = []
+ for item in parse_response(data):
+ if item is None:
+ parts.append(item)
+ else:
+ converted = []
+ for prefix, separator in item:
+ if self.folder_encode:
+ prefix = decode_utf7(prefix)
+ converted.append((prefix, to_unicode(separator)))
+ parts.append(tuple(converted))
+ return Namespace(*parts)
def list_folders(self, directory="", pattern="*"):
"""Get a listing of folders on the server as a list of
``(flags, delimiter, name)`` tuples.
- Calling list_folders with no arguments will list all
- folders.
+ Specifying *directory* will limit returned folders to the
+ given base directory. The directory and any child directories
+ will returned.
- Specifying *directory* will limit returned folders to that
- base directory. Specifying *pattern* will limit returned
- folders to those with matching names. The wildcards are
- supported in *pattern*. ``*`` matches zero or more of any
- character and ``%`` matches 0 or more characters except the
- folder delimiter.
+ Specifying *pattern* will limit returned folders to those with
+ matching names. The wildcards are supported in
+ *pattern*. ``*`` matches zero or more of any character and
+ ``%`` matches 0 or more characters except the folder
+ delimiter.
- Folder names are always returned as unicode strings, and decoded from
- modifier utf-7, except if folder_decode is not set.
+ Calling list_folders with no arguments will recursively list
+ all folders available for the logged in user.
+
+ Folder names are always returned as unicode strings, and
+ decoded from modified UTF-7, except if folder_decode is not
+ set.
"""
return self._do_list('LIST', directory, pattern)
A ``XLIST`` response could look something like::
- [([u'\\HasNoChildren', u'\\Inbox'], '/', u'Inbox'),
- ([u'\\Noselect', u'\\HasChildren'], '/', u'[Gmail]'),
- ([u'\\HasNoChildren', u'\\AllMail'], '/', u'[Gmail]/All Mail'),
- ([u'\\HasNoChildren', u'\\Drafts'], '/', u'[Gmail]/Drafts'),
- ([u'\\HasNoChildren', u'\\Important'], '/', u'[Gmail]/Important'),
- ([u'\\HasNoChildren', u'\\Sent'], '/', u'[Gmail]/Sent Mail'),
- ([u'\\HasNoChildren', u'\\Spam'], '/', u'[Gmail]/Spam'),
- ([u'\\HasNoChildren', u'\\Starred'], '/', u'[Gmail]/Starred'),
- ([u'\\HasNoChildren', u'\\Trash'], '/', u'[Gmail]/Trash')]
+ [((b'\\HasNoChildren', b'\\Inbox'), b'/', u'Inbox'),
+ ((b'\\Noselect', b'\\HasChildren'), b'/', u'[Gmail]'),
+ ((b'\\HasNoChildren', b'\\AllMail'), b'/', u'[Gmail]/All Mail'),
+ ((b'\\HasNoChildren', b'\\Drafts'), b'/', u'[Gmail]/Drafts'),
+ ((b'\\HasNoChildren', b'\\Important'), b'/', u'[Gmail]/Important'),
+ ((b'\\HasNoChildren', b'\\Sent'), b'/', u'[Gmail]/Sent Mail'),
+ ((b'\\HasNoChildren', b'\\Spam'), b'/', u'[Gmail]/Spam'),
+ ((b'\\HasNoChildren', b'\\Starred'), b'/', u'[Gmail]/Starred'),
+ ((b'\\HasNoChildren', b'\\Trash'), b'/', u'[Gmail]/Trash')]
This is a *deprecated* Gmail-specific IMAP extension (See
https://developers.google.com/gmail/imap_extensions#xlist_is_deprecated
- for more information).
- It is the responsibility of the caller to either check for ``XLIST``
- in the server capabilites, or to handle the error if the server
- doesn't support this extension.
+ for more information). It is the responsibility of the caller
+ to either check for ``XLIST`` in the server capabilites, or to
+ handle the error if the server doesn't support this extension.
The *directory* and *pattern* arguments are as per
list_folders().
directory = self._normalise_folder(directory)
pattern = self._normalise_folder(pattern)
typ, dat = self._imap._simple_command(cmd, directory, pattern)
- dat = from_bytes(dat)
self._checkok(cmd, typ, dat)
typ, dat = self._imap._untagged_response(typ, dat, cmd)
- return self._proc_folder_list(from_bytes(dat))
+ return self._proc_folder_list(dat)
def _proc_folder_list(self, folder_data):
# Filter out empty strings and None's.
the selected folder.
Returns a dictionary containing the ``SELECT`` response. At least
- the ``EXISTS``, ``FLAGS`` and ``RECENT`` keys are guaranteed
+ the ``b'EXISTS'``, ``b'FLAGS'`` and ``b'RECENT'`` keys are guaranteed
to exist. An example::
- {'EXISTS': 3,
- 'FLAGS': ('\\Answered', '\\Flagged', '\\Deleted', ... ),
- 'RECENT': 0,
- 'PERMANENTFLAGS': ('\\Answered', '\\Flagged', '\\Deleted', ... ),
- 'READ-WRITE': True,
- 'UIDNEXT': 11,
- 'UIDVALIDITY': 1239278212}
+ {b'EXISTS': 3,
+ b'FLAGS': (b'\\Answered', b'\\Flagged', b'\\Deleted', ... ),
+ b'RECENT': 0,
+ b'PERMANENTFLAGS': (b'\\Answered', b'\\Flagged', b'\\Deleted', ... ),
+ b'READ-WRITE': True,
+ b'UIDNEXT': 11,
+ b'UIDVALIDITY': 1239278212}
"""
self._command_and_check('select', self._normalise_folder(folder), readonly)
- untagged = self._imap.untagged_responses
- return self._process_select_response(from_bytes(untagged))
+ return self._process_select_response(self._imap.untagged_responses)
def _process_select_response(self, resp):
+ untagged = normalise_untagged_responses(resp)
out = {}
# imaplib doesn't parse these correctly (broken regex) so replace
# with the raw values out of the OK section
- for line in resp.get('OK', []):
- match = re.match(r'\[(?P<key>[A-Z-]+)( \((?P<data>.*)\))?\]', line)
+ for line in untagged.get(b'OK', []):
+ match = re.match(br'\[(?P<key>[A-Z-]+)( \((?P<data>.*)\))?\]', line)
if match:
key = match.group('key')
- if key == 'PERMANENTFLAGS':
+ if key == b'PERMANENTFLAGS':
out[key] = tuple(match.group('data').split())
- for key, value in iteritems(resp):
+ for key, value in iteritems(untagged):
key = key.upper()
- if key in ('OK', 'PERMANENTFLAGS'):
+ if key in (b'OK', b'PERMANENTFLAGS'):
continue # already handled above
- elif key in ('EXISTS', 'RECENT', 'UIDNEXT', 'UIDVALIDITY', 'HIGHESTMODSEQ'):
+ elif key in (b'EXISTS', b'RECENT', b'UIDNEXT', b'UIDVALIDITY', b'HIGHESTMODSEQ'):
value = int(value[0])
- elif key == 'READ-WRITE':
+ elif key == b'READ-WRITE':
value = True
- elif key == 'FLAGS':
+ elif key == b'FLAGS':
value = tuple(value[0][1:-1].split())
out[key] = value
return out
The return value is the server command response message
followed by a list of status responses. For example::
- ('NOOP completed.',
- [(4, 'EXISTS'),
- (3, 'FETCH', ('FLAGS', ('bar', 'sne'))),
- (6, 'FETCH', ('FLAGS', ('sne',)))])
+ (b'NOOP completed.',
+ [(4, b'EXISTS'),
+ (3, b'FETCH', (b'FLAGS', (b'bar', b'sne'))),
+ (6, b'FETCH', (b'FLAGS', (b'sne',)))])
"""
tag = self._imap._command('NOOP')
See :rfc:`2177` for more information about the IDLE extension.
"""
self._idle_tag = self._imap._command('IDLE')
- resp = from_bytes(self._imap._get_response())
+ resp = self._imap._get_response()
if resp is not None:
raise self.Error('Unexpected IDLE response: %s' % resp)
will be parsed with values converted to appropriate types. For
example::
- [('OK', 'Still here'),
- (1, 'EXISTS'),
- (1, 'FETCH', ('FLAGS', ('\\NotJunk',)))]
+ [(b'OK', b'Still here'),
+ (1, b'EXISTS'),
+ (1, b'FETCH', (b'FLAGS', (b'\\NotJunk',)))]
"""
# In py2, imaplib has sslobj (for SSL connections), and sock for non-SSL.
# In the py3 version it's just sock.
if rs:
while True:
try:
- line = from_bytes(self._imap._get_line())
+ line = self._imap._get_line()
except (socket.timeout, socket.error):
break
except IMAPClient.AbortError:
The return value is of the form ``(command_text,
idle_responses)`` where *command_text* is the text sent by the
- server when the IDLE command finished (eg. ``'Idle
+ server when the IDLE command finished (eg. ``b'Idle
terminated'``) and *idle_responses* is a list of parsed idle
responses received since the last call to ``idle_check()`` (if
any). These are returned in parsed form as per
criteria. It defaults to US-ASCII.
See :rfc:`3501#section-6.4.4` for more details.
+
+ The returned list of message ids will have its *modseq*
+ attribute set if the server appended a MODSEQ value to the
+ search response (i.e. if a MODSEQ criteria was included in the
+ search).
"""
return self._search(normalise_search_criteria(criteria), charset)
"""Search using Gmail's X-GM-RAW attribute.
*query* should be a valid Gmail search query string. For
- example::
+ example: ``has:attachment in:unread``
- 'has:attachment in:unread'
+ This method only works for IMAP servers that support X-GM-RAW,
+ which is only likely to be Gmail.
See https://developers.google.com/gmail/imap_extensions#extension_of_the_search_command_x-gm-raw
for more info.
search string. It defaults to US-ASCII.
"""
# the the query is sent as a literal to allow for 7-bit query strings
- self._imap.literal = query.encode(charset or 'us-ascii')
- return self._search(['X-GM-RAW'], charset)
+ if isinstance(query, string_types):
+ query = query.encode(charset or 'us-ascii')
+ self._imap.literal = query
+ return self._search([b'X-GM-RAW'], charset)
def _search(self, criteria, charset):
if self.use_uid:
args = []
if charset:
- args.extend(['CHARSET', charset])
+ args.extend([b'CHARSET', charset])
args.extend(criteria)
typ, data = self._imap.uid('SEARCH', *args)
else:
typ, data = self._imap.search(charset, *criteria)
- data = from_bytes(data)
-
self._checkok('search', typ, data)
- data = data[0]
- if data is None: # no untagged responses...
- return []
- return [long(i) for i in data.split()]
+
+ ids = SearchIds()
+ for item in parse_response(data):
+ if isinstance(item, int):
+ ids.append(item)
+ elif isinstance(item, tuple) and len(item) == 2 and item[0].lower() == b'modseq':
+ ids.modseq = item[1]
+ return ids
def thread(self, algorithm='REFERENCES', criteria='ALL', charset='UTF-8'):
"""Return a list of messages threads matching *criteria*.
See :rfc:`5256` for more details.
"""
- if not self.has_capability('THREAD=' + algorithm):
+ algorithm = to_bytes(algorithm)
+ if not self.has_capability(b'THREAD=' + algorithm):
raise ValueError('server does not support %s threading algorithm'
% algorithm)
args = [algorithm]
if charset:
- args.append(charset)
+ args.append(to_bytes(charset))
args.extend(normalise_search_criteria(criteria))
data = self._command_and_check('thread', *args, uid=True)
"""Return the flags set for each message in *messages*.
The return value is a dictionary structured like this: ``{
- msgid1: [flag1, flag2, ... ], }``.
+ msgid1: (flag1, flag2, ... ), }``.
"""
response = self.fetch(messages, ['FLAGS'])
- return self._filter_fetch_dict(response, 'FLAGS')
+ return self._filter_fetch_dict(response, b'FLAGS')
def add_flags(self, messages, flags):
"""Add *flags* to *messages*.
Returns the flags set for each modified message (see
*get_flags*).
"""
- return self._store('+FLAGS', messages, flags, 'FLAGS')
+ return self._store(b'+FLAGS', messages, flags, b'FLAGS')
def remove_flags(self, messages, flags):
"""Remove one or more *flags* from *messages*.
Returns the flags set for each modified message (see
*get_flags*).
"""
- return self._store('-FLAGS', messages, flags, 'FLAGS')
+ return self._store(b'-FLAGS', messages, flags, b'FLAGS')
def set_flags(self, messages, flags):
"""Set the *flags* for *messages*.
Returns the flags set for each modified message (see
*get_flags*).
"""
- return self._store('FLAGS', messages, flags, 'FLAGS')
+ return self._store(b'FLAGS', messages, flags, b'FLAGS')
def get_gmail_labels(self, messages):
"""Return the label set for each message in *messages*.
The return value is a dictionary structured like this: ``{
- msgid1: [label1, label2, ... ], }``.
+ msgid1: (label1, label2, ... ), }``.
This only works with IMAP servers that support the X-GM-LABELS
attribute (eg. Gmail).
"""
- response = self.fetch(messages, ['X-GM-LABELS'])
- return self._filter_fetch_dict(response, 'X-GM-LABELS')
+ response = self.fetch(messages, [b'X-GM-LABELS'])
+ return self._filter_fetch_dict(response, b'X-GM-LABELS')
def add_gmail_labels(self, messages, labels):
"""Add *labels* to *messages*.
This only works with IMAP servers that support the X-GM-LABELS
attribute (eg. Gmail).
"""
- return self._store('+X-GM-LABELS', messages,
- self._normalise_label_list(labels), 'X-GM-LABELS')
+ return self._store(b'+X-GM-LABELS', messages,
+ self._normalise_label_list(labels), b'X-GM-LABELS')
def remove_gmail_labels(self, messages, labels):
"""Remove one or more *labels* from *messages*.
This only works with IMAP servers that support the X-GM-LABELS
attribute (eg. Gmail).
"""
- return self._store('-X-GM-LABELS', messages,
- self._normalise_label_list(labels), 'X-GM-LABELS')
+ return self._store(b'-X-GM-LABELS', messages,
+ self._normalise_label_list(labels), b'X-GM-LABELS')
def set_gmail_labels(self, messages, labels):
"""Set the *labels* for *messages*.
This only works with IMAP servers that support the X-GM-LABELS
attribute (eg. Gmail).
"""
- return self._store('X-GM-LABELS', messages,
- self._normalise_label_list(labels), 'X-GM-LABELS')
+ return self._store(b'X-GM-LABELS', messages,
+ self._normalise_label_list(labels), b'X-GM-LABELS')
def delete_messages(self, messages):
"""Delete one or more *messages* from the currently selected
instances and ENVELOPE responses will be returned as
:py:class:`Envelope <imapclient.response_types.Envelope>` instances.
+ String data will generally be returned as bytes (Python 3) or
+ str (Python 2).
+
In addition to an element for each *data* item, the dict
returned for each message also contains a *SEQ* key containing
the sequence number for the message. This allows for mapping
Example::
>> c.fetch([3293, 3230], ['INTERNALDATE', 'FLAGS'])
- {3230: {'FLAGS': ('\\Seen',),
- 'INTERNALDATE': datetime.datetime(2011, 1, 30, 13, 32, 9),
- 'SEQ': 84},
- 3293: {'FLAGS': (),
- 'INTERNALDATE': datetime.datetime(2011, 2, 24, 19, 30, 36),
- 'SEQ': 110}}
+ {3230: {b'FLAGS': (b'\\Seen',),
+ b'INTERNALDATE': datetime.datetime(2011, 1, 30, 13, 32, 9),
+ b'SEQ': 84},
+ 3293: {b'FLAGS': (),
+ b'INTERNALDATE': datetime.datetime(2011, 2, 24, 19, 30, 36),
+ b'SEQ': 110}}
+
"""
if not messages:
return {}
args = [
'FETCH',
- messages_to_str(messages),
+ join_message_ids(messages),
seq_to_parenstr_upper(data),
seq_to_parenstr_upper(modifiers) if modifiers else None
]
args.insert(0, 'UID')
tag = self._imap._command(*args)
typ, data = self._imap._command_complete('FETCH', tag)
- data = from_bytes(data)
self._checkok('fetch', typ, data)
typ, data = self._imap._untagged_response(typ, data, 'FETCH')
- return parse_fetch_response(from_bytes(data), self.normalise_times, self.use_uid)
+ return parse_fetch_response(data, self.normalise_times, self.use_uid)
def append(self, folder, msg, flags=(), msg_time=None):
"""Append a message to *folder*.
Returns the APPEND response as returned by the server.
"""
if msg_time:
- time_val = '"%s"' % datetime_to_imap(msg_time)
+ time_val = '"%s"' % datetime_to_INTERNALDATE(msg_time)
if PY3:
time_val = to_unicode(time_val)
else:
server.
"""
return self._command_and_check('copy',
- messages_to_str(messages),
+ join_message_ids(messages),
self._normalise_folder(folder),
uid=True, unpack=True)
line = self._imap._get_response()
if tagged_commands[tag]:
break
- resps.append(_parse_untagged_response(from_bytes(line)))
+ resps.append(_parse_untagged_response(line))
typ, data = tagged_commands.pop(tag)
- data = from_bytes(data)
self._checkok(command, typ, data)
return data[0], resps
else:
meth = getattr(self._imap, command)
typ, data = meth(*args)
- data = from_bytes(data)
self._checkok(command, typ, data)
if unpack:
return data[0]
if not messages:
return {}
data = self._command_and_check('store',
- messages_to_str(messages),
+ join_message_ids(messages),
cmd,
seq_to_parenstr(flags),
uid=True)
folder_name = folder_name.decode('ascii')
if self.folder_encode:
folder_name = encode_utf7(folder_name)
- return self._imap._quote(folder_name)
+ return _quote(folder_name)
def _normalise_label_list(self, labels):
return iter(self._imap._quote(l) for l in labels)
+
+def _quote(arg):
+ if isinstance(arg, text_type):
+ arg = arg.replace('\\', '\\\\')
+ arg = arg.replace('"', '\\"')
+ q = '"'
+ else:
+ arg = arg.replace(b'\\', b'\\\\')
+ arg = arg.replace(b'"', b'\\"')
+ q = b'"'
+ return q + arg + q
+
+# normalise_text_list, seq_to_parentstr etc have to return unicode
+# because imaplib handles flags and sort criteria assuming these are
+# passed as unicode
def normalise_text_list(items):
return list(_normalise_text_list(items))
def seq_to_parenstr_upper(items):
return _join_and_paren(item.upper() for item in _normalise_text_list(items))
-def messages_to_str(messages):
- """Convert a sequence of messages ids or a single integer message id
- into an id list string for use with IMAP commands
- """
- if isinstance(messages, (text_type, binary_type, integer_types)):
- messages = (messages,)
- return ','.join(_maybe_int_to_unicode(m) for m in messages)
-
-def _maybe_int_to_unicode(val):
- if isinstance(val, integer_types):
- return text_type(val)
- return to_unicode(val)
-
def normalise_search_criteria(criteria):
if not criteria:
raise ValueError('no criteria specified')
- return ['(%s)' % item for item in _normalise_text_list(criteria)]
+ return ['(' + item + ')' for item in _normalise_text_list(criteria)]
def _join_and_paren(items):
- return '(%s)' % ' '.join(items)
+ return '(' + ' '.join(items) + ')'
def _normalise_text_list(items):
if isinstance(items, (text_type, binary_type)):
- items = (items,)
+ items = (to_unicode(items),)
return (to_unicode(c) for c in items)
-def datetime_to_imap(dt):
- """Convert a datetime instance to a IMAP datetime string.
-
- If timezone information is missing the current system
- timezone is used.
+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
"""
- if not dt.tzinfo:
- dt = dt.replace(tzinfo=FixedOffset.for_system())
- return dt.strftime("%d-%b-%Y %H:%M:%S %z")
+ if isinstance(messages, (text_type, binary_type, integer_types)):
+ 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('* ')
+ assert text.startswith(b'* ')
text = text[2:]
- if text.startswith(('OK ', 'NO ')):
- return tuple(text.split(' ', 1))
+ if text.startswith((b'OK ', b'NO ')):
+ return tuple(text.split(b' ', 1))
return parse_response([text])
def pop_with_default(dct, key, default):
if isinstance(s, text_type):
return s.encode('ascii')
return s
-
-def from_bytes(data):
- """Convert bytes to string in lists, tuples and dicts.
- """
- if isinstance(data, dict):
- decoded = {}
- for key, value in iteritems(data):
- decoded[from_bytes(key)] = from_bytes(value)
- return decoded
- elif isinstance(data, list):
- return [from_bytes(item) for item in data]
- elif isinstance(data, tuple):
- return tuple([from_bytes(item) for item in data])
- elif isinstance(data, binary_type):
- return data.decode('latin-1')
- return data
from email.utils import make_msgid
from .fixed_offset import FixedOffset
-from .imapclient import IMAPClient, DELETED, to_unicode
+from .imapclient import IMAPClient, DELETED, to_unicode, to_bytes, normalise_untagged_responses
from .response_types import Envelope, Address
from .six import binary_type, text_type, PY3
from .test.util import unittest
self.skipTest("Server doesn't support %s" % name)
def just_folder_names(self, dat):
+ if self.client.folder_encode:
+ gmail_special_prefix = '['
+ else:
+ gmail_special_prefix = b'['
ret = []
for _, _, folder_name in dat:
# gmail's "special" folders start with '['
- if not folder_name.startswith('['):
+ if not folder_name.startswith(gmail_special_prefix):
ret.append(folder_name)
return ret
return self.just_folder_names(self.client.list_sub_folders(self.base_folder))
def clear_test_folders(self):
- self.client.folder_encode = False
+ # Some servers (e.g. newer Dovecot) don't like it when you
+ # delete the currently selected folder.
+ try:
+ self.client.close_folder()
+ except IMAPClient.Error:
+ pass
+ self.client.folder_encode = False
folder_names = sorted(self.all_test_folder_names(),
key=self.get_folder_depth,
reverse=True)
# Sort folders depth first because some implementations
# (e.g. MS Exchange) will delete child folders when a
# parent is deleted.
- return folder.count(self.folder_delimiter)
+ return folder.count(self.folder_delimiter.encode('ascii'))
def clear_folder(self, folder):
self.client.select_folder(folder)
def test_select_and_close(self):
resp = self.client.select_folder(self.base_folder)
- self.assertEqual(resp['EXISTS'], 0)
- self.assertIsInstance(resp['RECENT'], int)
- self.assertIsInstance(resp['FLAGS'], tuple)
- self.assertGreater(len(resp['FLAGS']), 1)
+ self.assertEqual(resp[b'EXISTS'], 0)
+ self.assertIsInstance(resp[b'RECENT'], int)
+ self.assertIsInstance(resp[b'FLAGS'], tuple)
+ self.assertGreater(len(resp[b'FLAGS']), 1)
self.client.close_folder()
def test_select_read_only(self):
self.append_msg(SIMPLE_MESSAGE)
- self.assertNotIn('READ-ONLY', self.client._imap.untagged_responses)
+ untagged = normalise_untagged_responses(self.client._imap.untagged_responses)
+ self.assertNotIn(b'READ-ONLY', untagged)
resp = self.client.select_folder(self.base_folder, readonly=True)
- self.assertIn('READ-ONLY', self.client._imap.untagged_responses)
- self.assertEqual(resp['EXISTS'], 1)
- self.assertIsInstance(resp['RECENT'], int)
- self.assertIsInstance(resp['FLAGS'], tuple)
- self.assertGreater(len(resp['FLAGS']), 1)
+ untagged = normalise_untagged_responses(self.client._imap.untagged_responses)
+ self.assertIn(b'READ-ONLY', untagged)
+ self.assertEqual(resp[b'EXISTS'], 1)
+ self.assertIsInstance(resp[b'RECENT'], int)
+ self.assertIsInstance(resp[b'FLAGS'], tuple)
+ self.assertGreater(len(resp[b'FLAGS']), 1)
def test_list_folders(self):
some_folders = ['simple', b'simple2', 'L\xffR']
def test_gmail_xlist(self):
caps = self.client.capabilities()
if self.is_gmail():
- self.assertIn("XLIST", caps, "expected XLIST in Gmail's capabilities")
+ self.assertIn(b"XLIST", caps, "expected XLIST in Gmail's capabilities")
def test_xlist(self):
self.skip_unless_capable('XLIST')
foundInbox = False
for flags, _, _ in result:
- if r'\INBOX' in [flag.upper() for flag in flags]:
+ if br'\INBOX' in [flag.upper() for flag in flags]:
foundInbox = True
break
if not foundInbox:
])
# Run folder tests with folder_encode off
- self.client.folder_encode = False
- try:
- self.run_folder_tests(folders)
- finally:
- self.client.folder_encode = True
+ self.run_folder_tests(folders, False)
# Now with folder_encode on, adding in names that only work
# when this is enabled.
'stuff & things',
b'stuff & things',
])
- self.run_folder_tests(folders)
+ self.run_folder_tests(folders, True)
- def run_folder_tests(self, folder_names):
- folder_names = self.add_prefix_to_folders(folder_names)
+ def run_folder_tests(self, folder_names, folder_encode):
+ self.client.folder_encode = folder_encode
+ try:
+ folder_names = self.add_prefix_to_folders(folder_names)
- for folder in folder_names:
- self.assertFalse(self.client.folder_exists(folder))
+ for folder in folder_names:
+ self.assertFalse(self.client.folder_exists(folder))
- self.client.create_folder(folder)
+ self.client.create_folder(folder)
- self.assertTrue(self.client.folder_exists(folder))
- self.assertIn(to_unicode(folder), self.all_test_folder_names())
+ self.assertTrue(self.client.folder_exists(folder))
- self.client.select_folder(folder)
- self.client.close_folder()
+ self.assertIn(
+ to_unicode(folder) if folder_encode else to_bytes(folder),
+ self.all_test_folder_names()
+ )
+
+ self.client.select_folder(folder)
+ self.client.close_folder()
+
+ self.client.delete_folder(folder)
+ self.assertFalse(self.client.folder_exists(folder))
+ finally:
+ self.client.folder_encode = True
- self.client.delete_folder(folder)
- self.assertFalse(self.client.folder_exists(folder))
def test_rename_folder(self):
folders = self.add_prefix_to_folders([
new_folder = folder + 'x'
resp = self.client.rename_folder(folder, new_folder)
- self.assertIsInstance(resp, text_type)
+ self.assertIsInstance(resp, binary_type)
self.assertTrue(len(resp) > 0)
self.assertFalse(self.client.folder_exists(folder))
self.client.create_folder(new_folder)
try:
status = self.client.folder_status(new_folder)
- self.assertEqual(status['MESSAGES'], 0)
- self.assertEqual(status['RECENT'], 0)
- self.assertEqual(status['UNSEEN'], 0)
+ self.assertEqual(status[b'MESSAGES'], 0)
+ self.assertEqual(status[b'RECENT'], 0)
+ self.assertEqual(status[b'UNSEEN'], 0)
# Add a message to the folder, it should show up now.
self.append_msg(SIMPLE_MESSAGE, new_folder)
status = self.client.folder_status(new_folder)
- self.assertEqual(status['MESSAGES'], 1)
+ self.assertEqual(status[b'MESSAGES'], 1)
if not self.is_gmail():
- self.assertEqual(status['RECENT'], 1)
- self.assertEqual(status['UNSEEN'], 1)
+ self.assertEqual(status[b'RECENT'], 1)
+ self.assertEqual(status[b'UNSEEN'], 1)
finally:
self.client.delete_folder(new_folder)
responses = self.client.idle_check(timeout=5)
finally:
text, more_responses = self.client.idle_done()
- self.assertIn((1, 'EXISTS'), responses)
- self.assertTrue(isinstance(text, text_type))
+ self.assertIn((1, b'EXISTS'), responses)
+ self.assertTrue(isinstance(text, binary_type))
self.assertGreater(len(text), 0)
self.assertTrue(isinstance(more_responses, list))
time.sleep(2) # Allow some time for the IDLE response to be sent
finally:
text, responses = self.client.idle_done()
- self.assertIn((2, 'EXISTS'), responses)
- self.assertTrue(isinstance(text, text_type))
+ self.assertIn((2, b'EXISTS'), responses)
+ self.assertTrue(isinstance(text, binary_type))
self.assertGreater(len(text), 0)
def test_noop(self):
# Initially there should be no responses
text, resps = self.client.noop()
- self.assertTrue(isinstance(text, text_type))
+ self.assertTrue(isinstance(text, binary_type))
self.assertGreater(len(text), 0)
self.assertEqual(resps, [])
# Check for this addition in the NOOP data
msg, resps = self.client.noop()
- self.assertTrue(isinstance(text, text_type))
+ self.assertTrue(isinstance(text, binary_type))
self.assertGreater(len(text), 0)
self.assertTrue(isinstance(resps, list))
- self.assertIn((1, 'EXISTS'), resps)
+ self.assertIn((1, b'EXISTS'), resps)
def createUidTestClass(conf, use_uid):
# Append message
resp = self.client.append(self.base_folder, in_message, ('abc', 'def'), msg_time)
- self.assertIsInstance(resp, text_type)
+ self.assertIsInstance(resp, binary_type)
# Retrieve the just added message and check that all looks well
- self.assertEqual(self.client.select_folder(self.base_folder)['EXISTS'], 1)
+ self.assertEqual(self.client.select_folder(self.base_folder)[b'EXISTS'], 1)
resp = self.client.fetch(self.client.search()[0], ('RFC822', 'FLAGS', 'INTERNALDATE'))
msginfo = tuple(resp.values())[0]
# Time should match the time we specified
- returned_msg_time = msginfo['INTERNALDATE']
+ returned_msg_time = msginfo[b'INTERNALDATE']
self.assertIsNone(returned_msg_time.tzinfo)
self.assertEqual(returned_msg_time, msg_time)
# Flags should be the same
- self.assertIn('abc', msginfo['FLAGS'])
- self.assertIn('def', msginfo['FLAGS'])
+ self.assertIn(b'abc', msginfo[b'FLAGS'])
+ self.assertIn(b'def', msginfo[b'FLAGS'])
# Message body should match
- self.assertEqual(msginfo['RFC822'], out_message)
+ self.assertEqual(msginfo[b'RFC822'], to_bytes(out_message))
def test_flags(self):
self.append_msg(SIMPLE_MESSAGE)
answer = func(msg_id, *args)
self.assertTrue(msg_id in answer)
answer_flags = set(answer[msg_id])
- answer_flags.discard(r'\Recent') # Might be present but don't care
- self.assertSetEqual(answer_flags, set(expected_flags))
+ answer_flags.discard(br'\Recent') # Might be present but don't care
+ self.assertSetEqual(answer_flags, set(to_bytes(f) for f in expected_flags))
base_flags = ['abc', 'def']
_flagtest(self.client.set_flags, [base_flags], base_flags)
actual_labels = set(answer[msg_id])
self.assertSetEqual(actual_labels, set(expected_labels))
- base_labels = ['_imapclient_foo', '_imapclient_bar']
+ base_labels = [b'_imapclient_foo', b'_imapclient_bar']
try:
_labeltest(self.client.set_gmail_labels, [base_labels], base_labels)
_labeltest(self.client.get_gmail_labels, [], base_labels)
- _labeltest(self.client.add_gmail_labels, ['_imapclient_baz'], base_labels + ['_imapclient_baz'])
- _labeltest(self.client.remove_gmail_labels, ['_imapclient_baz'], base_labels)
+ _labeltest(self.client.add_gmail_labels, [b'_imapclient_baz'], base_labels + [b'_imapclient_baz'])
+ _labeltest(self.client.remove_gmail_labels, [b'_imapclient_baz'], base_labels)
finally:
# Clean up
- for label in ['_imapclient_baz'] + base_labels:
+ for label in [b'_imapclient_baz'] + base_labels:
if self.client.folder_exists(label):
self.client.delete_folder(label)
self.assertEqual(len(self.client.search(['NOT DELETED', 'SUBJECT "a"'])), 1)
self.assertEqual(len(self.client.search(['NOT DELETED', 'SUBJECT "c"'])), 0)
+ def test_search_with_modseq(self):
+ # CONDSTORE (RFC 4551) means that the server supports the
+ # MODSEQ search criteria and response.
+ if not self.client.has_capability('CONDSTORE'):
+ 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")
+
+ # A little dance to ensure MODSEQ tracking is turned on.
+ # TODO: use ENABLE for this instead
+ self.client.select_folder(self.base_folder)
+ self.append_msg(SIMPLE_MESSAGE)
+ msg_id = self.client.search()[0]
+ self.client.fetch(msg_id, ["MODSEQ"])
+ self.client.close_folder()
+ self.clear_folder(self.base_folder)
+
+ # Remember the initial MODSEQ
+ initial_modseq = self.client.select_folder(self.base_folder)[b'HIGHESTMODSEQ']
+
+ # Add a message so that the MODSEQ increases
+ self.append_msg(SIMPLE_MESSAGE)
+
+ # Ensure the message is seen and the new MODSEQ value is returned
+ ids = self.client.search(['MODSEQ %d' % initial_modseq])
+ self.assertEqual(len(ids), 1)
+ self.assertGreater(ids.modseq, initial_modseq)
+
def test_gmail_search(self):
self.skip_unless_capable('X-GM-EXT-1', 'Gmail search')
def test_thread(self):
thread_algo = None
for cap in self.client.capabilities():
- if cap.startswith('THREAD='):
- thread_algo = cap.split('=')[-1]
+ if cap.startswith(b'THREAD='):
+ thread_algo = cap.split(b'=')[-1]
break
if not thread_algo:
return self.skipTest("Server doesn't support THREAD")
msgs = self.client.search()
self.assertEqual(len(msgs), 1)
msg_id = msgs[0]
- self.assertIn('something', self.client.fetch(msg_id, ['RFC822'])[msg_id]['RFC822'])
+ self.assertIn(b'something', self.client.fetch(msg_id, ['RFC822'])[msg_id][b'RFC822'])
def test_fetch(self):
# Generate a fresh message-id each time because Gmail is
self.assertSetEqual(
set(msginfo.keys()),
- set([to_unicode(f) for f in fields] + ['SEQ'])
+ set([to_bytes(f) for f in fields] + [b'SEQ'])
)
- self.assertEqual(msginfo['SEQ'], 1)
- self.assertMultiLineEqual(msginfo['RFC822'], msg)
- self.assertIsInstance(msginfo['INTERNALDATE'], datetime)
- self.assertIsInstance(msginfo['FLAGS'], tuple)
- self.assertSequenceEqual(msginfo['ENVELOPE'],
+ self.assertEqual(msginfo[b'SEQ'], 1)
+ self.assertEqual(msginfo[b'RFC822'], to_bytes(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)),
- 'A multipart message',
- (Address('Bob Smith', None, 'bob', 'smith.com'),),
- (Address('Bob Smith', None, 'bob', 'smith.com'),),
- (Address('Bob Smith', None, 'bob', 'smith.com'),),
- (Address('Some One', None, 'some', 'one.com'),
- Address(None, None, 'foo', 'foo.com')),
- None, None, None, msg_id_header))
+ 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)
msg_id = self.client.search()[0]
resp = self.client.fetch(msg_id, ['BODY[]<0.20>'])
- body = resp[msg_id]['BODY[]<0>']
+ body = resp[msg_id][b'BODY[]<0>']
self.assertEqual(len(body), 20)
- self.assertTrue(body.startswith('From: Bob Smith'))
+ self.assertTrue(body.startswith(b'From: Bob Smith'))
resp = self.client.fetch(msg_id, ['BODY[]<2.25>'])
- body = resp[msg_id]['BODY[]<2>']
+ body = resp[msg_id][b'BODY[]<2>']
self.assertEqual(len(body), 25)
- self.assertTrue(body.startswith('om: Bob Smith'))
+ self.assertTrue(body.startswith(b'om: Bob Smith'))
def test_fetch_modifiers(self):
# CONDSTORE (RFC 4551) provides a good way to use FETCH
self.client.close_folder()
self.clear_folder(self.base_folder)
+ #
# Actual testing starts here
- maxModSeq = self.client.select_folder(self.base_folder)['HIGHESTMODSEQ']
+ #
+
+ # Get the starting MODSEQ
+ modseq = self.client.select_folder(self.base_folder)[b'HIGHESTMODSEQ']
+
+ # Add a message so that the MODSEQ gets bumped
self.append_msg(SIMPLE_MESSAGE)
msg_id = self.client.search()[0]
- resp = self.client.fetch(msg_id, ['FLAGS'], ['CHANGEDSINCE %d' % maxModSeq])
- self.assertIn('MODSEQ', resp[msg_id])
- # Prove that the modifier is actually being used
- resp = self.client.fetch(msg_id, ['FLAGS'], ['CHANGEDSINCE %d' % (maxModSeq + 1)])
- self.assertFalse(resp)
+ # Request changes since the starting MODSEQ: this should
+ # return the new message.
+ resp = self.client.fetch(msg_id, ['FLAGS'], ['CHANGEDSINCE %d' % modseq])
+ new_modseq = resp[msg_id][b"MODSEQ"][0]
+ self.assertGreater(new_modseq, modseq)
+
+ # Now asked for changes since the MODSEQ on the added
+ # message. These shouldn't be any.
+ resp = self.client.fetch(msg_id, ['FLAGS'], ['CHANGEDSINCE %d' % new_modseq])
+ self.assertEqual(resp, {})
def test_BODYSTRUCTURE(self):
self.client.select_folder(self.base_folder)
# since we can't predicate what the server we're testing against
# will return.
- expected = ('text', 'plain', ('charset', 'us-ascii'), None, None, '7bit', 5, 1)
- self.check_BODYSTRUCTURE(expected, fetched[msgs[0]]['BODY'], multipart=False)
- self.check_BODYSTRUCTURE(expected, fetched[msgs[0]]['BODYSTRUCTURE'], multipart=False)
+ expected = (b'text', b'plain', (b'charset', b'us-ascii'), None, None, b'7bit', 5, 1)
+ self.check_BODYSTRUCTURE(expected, fetched[msgs[0]][b'BODY'], multipart=False)
+ self.check_BODYSTRUCTURE(expected, fetched[msgs[0]][b'BODYSTRUCTURE'], multipart=False)
- expected = ([('text', 'html', ('charset', 'us-ascii'), None, None, 'quoted-printable', 55, 3),
- ('text', 'plain', ('charset', 'us-ascii'), None, None, '7bit', 26, 1),
+ expected = ([(b'text', b'html', (b'charset', b'us-ascii'), None, None, b'quoted-printable', 55, 3),
+ (b'text', b'plain', (b'charset', b'us-ascii'), None, None, b'7bit', 26, 1),
],
- 'mixed',
- ('boundary', '===============1534046211=='))
- self.check_BODYSTRUCTURE(expected, fetched[msgs[1]]['BODY'], multipart=True)
- self.check_BODYSTRUCTURE(expected, fetched[msgs[1]]['BODYSTRUCTURE'], multipart=True)
+ b'mixed',
+ (b'boundary', b'===============1534046211=='))
+ self.check_BODYSTRUCTURE(expected, fetched[msgs[1]][b'BODY'], multipart=True)
+ self.check_BODYSTRUCTURE(expected, fetched[msgs[1]][b'BODYSTRUCTURE'], multipart=True)
def check_BODYSTRUCTURE(self, expected, actual, multipart=None):
if multipart is not None:
self.assertEqual(actual.is_multipart, multipart)
- # BODYSTRUCTURE lengths can various according to the server so
- # compare up until what is returned
- for e, a in zip(expected, actual):
- if have_matching_types(e, a, (list, tuple)):
- for expected_and_actual in zip(e, a):
- self.check_BODYSTRUCTURE(*expected_and_actual)
- else:
- if e == ('charset', 'us-ascii') and a is None:
- pass # Some servers (eg. Gmail) don't return a charset when it's us-ascii
- else:
- a = lower_if_str(a)
- e = lower_if_str(e)
- self.assertEqual(a, e)
+ if have_matching_types(expected, actual, (list, tuple)):
+ # BODYSTRUCTURE lengths can various according to the
+ # server so compare up until what is returned
+ for pair in zip(expected, actual):
+ self.check_BODYSTRUCTURE(*pair)
+ elif expected == (b'charset', b'us-ascii') and actual is None:
+ pass # Some servers don't return a charset when it's us-ascii
+ else:
+ self.assertEqual(maybe_lower(expected), maybe_lower(actual))
def test_expunge(self):
self.client.select_folder(self.base_folder)
# Test empty mailbox
text, resps = self.client.expunge()
- self.assertTrue(isinstance(text, text_type))
+ self.assertTrue(isinstance(text, binary_type))
self.assertGreater(len(text), 0)
# Some servers return nothing while others (e.g. Exchange) return (0, 'EXISTS')
- self.assertIn(resps, ([], [(0, 'EXISTS')]))
+ self.assertIn(resps, ([], [(0, b'EXISTS')]))
# Now try with a message to expunge
self.client.append(self.base_folder, SIMPLE_MESSAGE, flags=[DELETED])
msg, resps = self.client.expunge()
- self.assertTrue(isinstance(text, text_type))
+ self.assertTrue(isinstance(text, binary_type))
self.assertGreater(len(text), 0)
self.assertTrue(isinstance(resps, list))
if not self.is_gmail():
# GMail has an auto-expunge feature which might be
# on. EXPUNGE won't return anything in this case
- self.assertIn((1, 'EXPUNGE'), resps)
+ self.assertIn((1, b'EXPUNGE'), resps)
def test_getacl(self):
self.skip_unless_capable('ACL')
folder = self.add_prefix_to_folder('test_acl')
- who = conf['username']
self.client.create_folder(folder)
+ who = to_bytes(conf['username'])
rights = self.client.getacl(folder)
self.assertIn(who, [u for u, r in rights])
except IMAPClient.Error:
pass
-def lower_if_str(val):
- if isinstance(val, text_type):
+def maybe_lower(val):
+ if isinstance(val, (text_type, binary_type)):
return val.lower()
return val
"""
A lexical analyzer class for IMAP responses.
-Although Lexer does all the work, TokenSource is probably the class to
-use for external callers.
+Although Lexer does all the work, TokenSource is the class to use for
+external callers.
"""
-# This was heavily inspired by (ie, ripped off from) python 2.6's shlex
-# module with further inspiration from the patch in
-# http://bugs.python.org/issue7594, but redone to be specific to IMAPs
-# requirements while offering nice performance by using generators everywhere.
-
from __future__ import unicode_literals
from . import six
-__all__ = ["Lexer"]
-
-if six.PY3:
- unichr = chr # unichr doesn't exist in py3 where every string is unicode
+__all__ = ["TokenSource"]
-CTRL_CHARS = frozenset(unichr(c) for c in range(32))
-ALL_CHARS = frozenset(unichr(c) for c in range(256))
-SPECIALS = frozenset(' ()%"[')
+CTRL_CHARS = frozenset(c for c in range(32))
+ALL_CHARS = frozenset(c for c in range(256))
+SPECIALS = frozenset(c for c in six.iterbytes(b' ()%"['))
NON_SPECIALS = ALL_CHARS - SPECIALS - CTRL_CHARS
-WHITESPACE = frozenset(' \t\r\n')
+WHITESPACE = frozenset(c for c in six.iterbytes(b' \t\r\n'))
+
+BACKSLASH = ord('\\')
+OPEN_SQUARE = ord('[')
+CLOSE_SQUARE = ord(']')
+DOUBLE_QUOTE = ord('"')
class TokenSource(object):
"""
def __init__(self, text):
- lex = Lexer()
- lex.sources = (LiteralHandlingIter(lex, chunk) for chunk in text)
- self.lex = lex
- self.src = iter(lex)
+ self.lex = Lexer(text)
+ self.src = iter(self.lex)
@property
def current_literal(self):
A lexical analyzer class for IMAP
"""
- def __init__(self):
- self.sources = None
+ def __init__(self, text):
+ self.sources = (LiteralHandlingIter(self, chunk) for chunk in text)
self.current_source = None
def read_until(self, stream_i, end_char, escape=True):
- token = ''
+ token = bytearray()
try:
for nextchar in stream_i:
- if escape and nextchar == "\\":
+ if escape and nextchar == BACKSLASH:
escaper = nextchar
nextchar = six.next(stream_i)
if nextchar != escaper and nextchar != end_char:
- token += escaper.decode
+ token.append(escaper) # Don't touch invalid escaping
elif nextchar == end_char:
break
- token += nextchar
+ token.append(nextchar)
else:
- raise ValueError("No closing '%s'" % end_char)
+ raise ValueError("No closing '%s'" % chr(end_char))
except StopIteration:
- raise ValueError("No closing '%s'" % end_char)
- return token + end_char
+ raise ValueError("No closing '%s'" % chr(end_char))
+ token.append(end_char)
+ return token
def read_token_stream(self, stream_i):
whitespace = WHITESPACE
read_until = self.read_until
while True:
- # whitespace
+ # Whitespace
for nextchar in stream_i:
if nextchar not in whitespace:
stream_i.push(nextchar)
break # done skipping over the whitespace
- # non whitespace
- token = ''
+ # Non-whitespace
+ token = bytearray()
for nextchar in stream_i:
if nextchar in wordchars:
- token += nextchar
- elif nextchar == '[':
- token += nextchar + read_until(stream_i, ']', escape=False)
+ token.append(nextchar)
+ elif nextchar == OPEN_SQUARE:
+ token.append(nextchar)
+ token.extend(read_until(stream_i, CLOSE_SQUARE, escape=False))
else:
if nextchar in whitespace:
yield token
- elif nextchar == '"':
+ elif nextchar == DOUBLE_QUOTE:
assert not token
- yield nextchar + read_until(stream_i, nextchar)
+ token.append(nextchar)
+ token.extend(read_until(stream_i, nextchar))
+ yield token
else:
# Other punctuation, eg. "(". This ends the current token.
if token:
yield token
- yield nextchar
+ yield bytearray([nextchar])
break
else:
if token:
break
def __iter__(self):
- "Generate tokens"
for source in self.sources:
self.current_source = source
for tok in self.read_token_stream(iter(source)):
- yield tok
+ yield bytes(tok)
# imaplib has poor handling of 'literals' - it both fails to remove the
# 'line'. What we end up with is a list of response 'records', where each
# record is either a simple string, or tuple of (str_with_lit, literal) -
# where str_with_lit is a string with the {xxx} marker at its end. Note
-# that each elt of this list does *not* correspond 1:1 with the untagged
-# responses.
+# that each element of this list does *not* correspond 1:1 with the
+# untagged responses.
# (http://bugs.python.org/issue5045 also has comments about this)
-# So: we have a special file-like object for each of these records. When
-# a string literal is finally processed, we peek into this file-like object
-# to grab the literal.
+# So: we have a special object for each of these records. When a
+# string literal is processed, we peek into this object to grab the
+# literal.
class LiteralHandlingIter:
def __init__(self, lexer, resp_record):
self.lexer = lexer
# A 'record' with a string which includes a literal marker, and
# the literal itself.
self.src_text = resp_record[0]
- assert self.src_text.endswith("}"), self.src_text
+ assert self.src_text.endswith(b"}"), self.src_text
self.literal = resp_record[1]
else:
# just a line with no literals.
self.src_text = resp_record
self.literal = None
+
def __iter__(self):
- return PushableIterator(self.src_text)
+ return PushableIterator(six.iterbytes(self.src_text))
class PushableIterator(object):
import sys
from collections import defaultdict
-from datetime import datetime
from . import six
xrange = six.moves.xrange
from .datetime_util import parse_to_datetime
-from .fixed_offset import FixedOffset
from .response_lexer import TokenSource
-from .response_types import Envelope, Address
+from .response_types import BodyData, Envelope, Address
-try:
- import imaplib2 as imaplib
-except ImportError:
- imaplib2 = None
- import imaplib
__all__ = ['parse_response', 'ParseError']
Returns nested tuples of appropriately typed objects.
"""
+ if data == [None]:
+ return []
return tuple(gen_parsed_response(data))
# always return the sequence of the message, so it is available
# even if we return keyed by UID.
- msg_data = {'SEQ': seq}
+ msg_data = {b'SEQ': seq}
for i in xrange(0, len(msg_response), 2):
word = msg_response[i].upper()
value = msg_response[i+1]
- if word == 'UID':
+ if word == b'UID':
uid = _int_or_error(value, 'invalid UID')
if uid_is_key:
msg_id = uid
else:
msg_data[word] = uid
- elif word == 'INTERNALDATE':
+ elif word == b'INTERNALDATE':
msg_data[word] = _convert_INTERNALDATE(value, normalise_times)
- elif word == 'ENVELOPE':
+ elif word == b'ENVELOPE':
msg_data[word] = _convert_ENVELOPE(value, normalise_times)
- elif word in ('BODY', 'BODYSTRUCTURE'):
+ elif word in (b'BODY', b'BODYSTRUCTURE'):
msg_data[word] = BodyData.create(value)
else:
msg_data[word] = value
raise ParseError('%s: %s' % (error_text, repr(value)))
-class BodyData(tuple):
-
- @classmethod
- def create(cls, response):
- # In case of multipart messages we will see at least 2 tuples
- # at the start. Nest these in to a list so that the returned
- # response tuple always has a consistent number of elements
- # regardless of whether the message is multipart or not.
- if isinstance(response[0], tuple):
- # Multipart, find where the message part tuples stop
- for i, part in enumerate(response):
- if isinstance(part, six.string_types):
- break
- return cls(([cls.create(part) for part in response[:i]],) + response[i:])
- else:
- return cls(response)
-
- @property
- def is_multipart(self):
- return isinstance(self[0], list)
-
-
def _convert_INTERNALDATE(date_string, normalise_times=True):
- date_msg = 'INTERNALDATE "%s"' % date_string
- mo = imaplib.InternalDate.match(date_msg.encode('latin-1'))
- if not mo:
- raise ValueError("couldn't parse date %r" % date_string)
-
- zoneh = int(mo.group('zoneh'))
- zonem = (zoneh * 60) + int(mo.group('zonem'))
- if mo.group('zonen') == b'-':
- zonem = -zonem
- tz = FixedOffset(zonem)
-
- year = int(mo.group('year'))
- mon = imaplib.Mon2num[mo.group('mon')]
- day = int(mo.group('day'))
- hour = int(mo.group('hour'))
- min = int(mo.group('min'))
- sec = int(mo.group('sec'))
-
- dt = datetime(year, mon, day, hour, min, sec, 0, tz)
-
- if normalise_times:
- # Normalise to host system's timezone
- return dt.astimezone(FixedOffset.for_system()).replace(tzinfo=None)
- return dt
+ try:
+ return parse_to_datetime(date_string, normalise=normalise_times)
+ except ValueError:
+ return None
def _convert_ENVELOPE(envelope_response, normalise_times=True):
- dt = parse_to_datetime(envelope_response[0], normalise=normalise_times)
+ dt = None
+ if envelope_response[0]:
+ try:
+ dt = parse_to_datetime(envelope_response[0], normalise=normalise_times)
+ except ValueError:
+ pass
+
subject = envelope_response[1]
# addresses contains a tuple of addresses
addrs = []
if addr_list:
for addr_tuple in addr_list:
- addrs.append(Address(*addr_tuple))
+ if addr_tuple:
+ addrs.append(Address(*addr_tuple))
addresses.append(tuple(addrs))
else:
addresses.append(None)
)
def atom(src, token):
- if token == '(':
+ if token == b'(':
return parse_tuple(src)
- elif token == 'NIL':
+ elif token == b'NIL':
return None
- elif token[:1] == '{':
+ elif token[:1] == b'{':
literal_len = int(token[1:-1])
literal_text = src.current_literal
if literal_text is None:
raise ParseError('Expecting literal of size %d, got %d' % (
literal_len, len(literal_text)))
return literal_text
- elif len(token) >= 2 and (token[:1] == token[-1:] == '"'):
+ elif len(token) >= 2 and (token[:1] == token[-1:] == b'"'):
return token[1:-1]
elif token.isdigit():
return int(token)
def parse_tuple(src):
out = []
for token in src:
- if token == ")":
+ if token == b")":
return tuple(out)
out.append(atom(src, token))
# no terminator
from collections import namedtuple
from email.utils import formataddr
+from . import six
+
class Envelope(namedtuple("Envelope", "date subject from_ sender reply_to to " +
"cc bcc in_reply_to message_id")):
def __str__(self):
return formataddr((self.name, self.mailbox + '@' + self.host))
+
+
+class SearchIds(list):
+ """
+ Contains a list of message ids as returned by IMAPClient.search().
+
+ The *modseq* attribute will contain the MODSEQ value returned by
+ the server (only if the SEARCH command sent involved the MODSEQ
+ criteria). See :rfc:`4551` for more details.
+ """
+
+ def __init__(self, *args):
+ list.__init__(self, *args)
+ self.modseq = None
+
+
+class BodyData(tuple):
+ """
+ Returned when parsing BODY and BODYSTRUCTURE responses.
+ """
+
+ @classmethod
+ def create(cls, response):
+ # In case of multipart messages we will see at least 2 tuples
+ # at the start. Nest these in to a list so that the returned
+ # response tuple always has a consistent number of elements
+ # regardless of whether the message is multipart or not.
+ if isinstance(response[0], tuple):
+ # Multipart, find where the message part tuples stop
+ for i, part in enumerate(response):
+ if isinstance(part, six.binary_type):
+ break
+ return cls(([cls.create(part) for part in response[:i]],) + response[i:])
+ else:
+ return cls(response)
+
+ @property
+ def is_multipart(self):
+ return isinstance(self[0], list)
"""Utilities for writing code that runs on Python 2 and 3"""
+# Copyright (c) 2010-2014 Benjamin Peterson
+#
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to deal
+# in the Software without restriction, including without limitation the rights
+# to use, copy, modify, merge, publish, 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 NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+# SOFTWARE.
+
+import functools
import operator
import sys
import types
__author__ = "Benjamin Peterson <benjamin@python.org>"
-__version__ = "1.1.0"
+__version__ = "1.7.3"
-# True if we are running on Python 3.
+# Useful for very coarse version differentiation.
+PY2 = sys.version_info[0] == 2
PY3 = sys.version_info[0] == 3
if PY3:
text_type = unicode
binary_type = str
- # It's possible to have sizeof(long) != sizeof(Py_ssize_t).
- class X(object):
- def __len__(self):
- return 1 << 31
- try:
- len(X())
- except OverflowError:
- # 32-bit
+ if sys.platform.startswith("java"):
+ # Jython always uses 32 bits.
MAXSIZE = int((1 << 31) - 1)
else:
- # 64-bit
- MAXSIZE = int((1 << 63) - 1)
- del X
+ # It's possible to have sizeof(long) != sizeof(Py_ssize_t).
+ class X(object):
+ def __len__(self):
+ return 1 << 31
+ try:
+ len(X())
+ except OverflowError:
+ # 32-bit
+ MAXSIZE = int((1 << 31) - 1)
+ else:
+ # 64-bit
+ MAXSIZE = int((1 << 63) - 1)
+ del X
def _add_doc(func, doc):
def __get__(self, obj, tp):
result = self._resolve()
- setattr(obj, self.name, result)
+ setattr(obj, self.name, result) # Invokes __set__.
# This is a bit ugly, but it avoids running this again.
- delattr(tp, self.name)
+ delattr(obj.__class__, self.name)
return result
def _resolve(self):
return _import_module(self.mod)
+ def __getattr__(self, attr):
+ _module = self._resolve()
+ value = getattr(_module, attr)
+ setattr(self, attr, value)
+ return value
+
+
+class _LazyModule(types.ModuleType):
+
+ def __init__(self, name):
+ super(_LazyModule, self).__init__(name)
+ self.__doc__ = self.__class__.__doc__
+
+ def __dir__(self):
+ attrs = ["__doc__", "__name__"]
+ attrs += [attr.name for attr in self._moved_attributes]
+ return attrs
+
+ # Subclasses should override this
+ _moved_attributes = []
+
class MovedAttribute(_LazyDescr):
return getattr(module, self.attr)
+class _SixMetaPathImporter(object):
+ """
+ A meta path importer to import six.moves and its submodules.
+
+ This class implements a PEP302 finder and loader. It should be compatible
+ with Python 2.5 and all existing versions of Python3
+ """
+ def __init__(self, six_module_name):
+ self.name = six_module_name
+ self.known_modules = {}
+
+ def _add_module(self, mod, *fullnames):
+ for fullname in fullnames:
+ self.known_modules[self.name + "." + fullname] = mod
+
+ def _get_module(self, fullname):
+ return self.known_modules[self.name + "." + fullname]
+
+ def find_module(self, fullname, path=None):
+ if fullname in self.known_modules:
+ return self
+ return None
+
+ def __get_module(self, fullname):
+ try:
+ return self.known_modules[fullname]
+ except KeyError:
+ raise ImportError("This loader does not know module " + fullname)
+
+ def load_module(self, fullname):
+ try:
+ # in case of a reload
+ return sys.modules[fullname]
+ except KeyError:
+ pass
+ mod = self.__get_module(fullname)
+ if isinstance(mod, MovedModule):
+ mod = mod._resolve()
+ else:
+ mod.__loader__ = self
+ sys.modules[fullname] = mod
+ return mod
+
+ def is_package(self, fullname):
+ """
+ Return true, if the named module is a package.
-class _MovedItems(types.ModuleType):
+ We need this method to get correct spec objects with
+ Python 3.4 (see PEP451)
+ """
+ return hasattr(self.__get_module(fullname), "__path__")
+
+ def get_code(self, fullname):
+ """Return None
+
+ Required, if is_package is implemented"""
+ self.__get_module(fullname) # eventually raises ImportError
+ return None
+ get_source = get_code # same as get_code
+
+_importer = _SixMetaPathImporter(__name__)
+
+
+class _MovedItems(_LazyModule):
"""Lazy loading of moved objects"""
+ __path__ = [] # mark as package
_moved_attributes = [
MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"),
MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"),
+ MovedAttribute("filterfalse", "itertools", "itertools", "ifilterfalse", "filterfalse"),
MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"),
MovedAttribute("map", "itertools", "builtins", "imap", "map"),
+ MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"),
MovedAttribute("reload_module", "__builtin__", "imp", "reload"),
MovedAttribute("reduce", "__builtin__", "functools"),
MovedAttribute("StringIO", "StringIO", "io"),
+ MovedAttribute("UserDict", "UserDict", "collections"),
+ MovedAttribute("UserList", "UserList", "collections"),
+ MovedAttribute("UserString", "UserString", "collections"),
MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"),
MovedAttribute("zip", "itertools", "builtins", "izip", "zip"),
+ MovedAttribute("zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"),
MovedModule("builtins", "__builtin__"),
MovedModule("configparser", "ConfigParser"),
MovedModule("copyreg", "copy_reg"),
+ MovedModule("dbm_gnu", "gdbm", "dbm.gnu"),
+ MovedModule("_dummy_thread", "dummy_thread", "_dummy_thread"),
MovedModule("http_cookiejar", "cookielib", "http.cookiejar"),
MovedModule("http_cookies", "Cookie", "http.cookies"),
MovedModule("html_entities", "htmlentitydefs", "html.entities"),
MovedModule("html_parser", "HTMLParser", "html.parser"),
MovedModule("http_client", "httplib", "http.client"),
+ MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"),
+ MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"),
+ MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"),
MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"),
MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"),
MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"),
MovedModule("queue", "Queue"),
MovedModule("reprlib", "repr"),
MovedModule("socketserver", "SocketServer"),
+ MovedModule("_thread", "thread", "_thread"),
MovedModule("tkinter", "Tkinter"),
MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"),
MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"),
MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"),
MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"),
MovedModule("tkinter_tix", "Tix", "tkinter.tix"),
+ MovedModule("tkinter_ttk", "ttk", "tkinter.ttk"),
MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"),
MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"),
MovedModule("tkinter_colorchooser", "tkColorChooser",
MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"),
MovedModule("tkinter_tksimpledialog", "tkSimpleDialog",
"tkinter.simpledialog"),
+ MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"),
+ MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"),
+ MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"),
MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"),
+ MovedModule("xmlrpc_client", "xmlrpclib", "xmlrpc.client"),
+ MovedModule("xmlrpc_server", "SimpleXMLRPCServer", "xmlrpc.server"),
MovedModule("winreg", "_winreg"),
]
for attr in _moved_attributes:
setattr(_MovedItems, attr.name, attr)
+ if isinstance(attr, MovedModule):
+ _importer._add_module(attr, "moves." + attr.name)
+del attr
+
+_MovedItems._moved_attributes = _moved_attributes
+
+moves = _MovedItems(__name__ + ".moves")
+_importer._add_module(moves, "moves")
+
+
+class Module_six_moves_urllib_parse(_LazyModule):
+ """Lazy loading of moved objects in six.moves.urllib_parse"""
+
+
+_urllib_parse_moved_attributes = [
+ MovedAttribute("ParseResult", "urlparse", "urllib.parse"),
+ MovedAttribute("SplitResult", "urlparse", "urllib.parse"),
+ MovedAttribute("parse_qs", "urlparse", "urllib.parse"),
+ MovedAttribute("parse_qsl", "urlparse", "urllib.parse"),
+ MovedAttribute("urldefrag", "urlparse", "urllib.parse"),
+ MovedAttribute("urljoin", "urlparse", "urllib.parse"),
+ MovedAttribute("urlparse", "urlparse", "urllib.parse"),
+ MovedAttribute("urlsplit", "urlparse", "urllib.parse"),
+ MovedAttribute("urlunparse", "urlparse", "urllib.parse"),
+ MovedAttribute("urlunsplit", "urlparse", "urllib.parse"),
+ MovedAttribute("quote", "urllib", "urllib.parse"),
+ MovedAttribute("quote_plus", "urllib", "urllib.parse"),
+ MovedAttribute("unquote", "urllib", "urllib.parse"),
+ MovedAttribute("unquote_plus", "urllib", "urllib.parse"),
+ MovedAttribute("urlencode", "urllib", "urllib.parse"),
+ MovedAttribute("splitquery", "urllib", "urllib.parse"),
+]
+for attr in _urllib_parse_moved_attributes:
+ setattr(Module_six_moves_urllib_parse, attr.name, attr)
+del attr
+
+Module_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes
+
+_importer._add_module(Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse"),
+ "moves.urllib_parse", "moves.urllib.parse")
+
+
+class Module_six_moves_urllib_error(_LazyModule):
+ """Lazy loading of moved objects in six.moves.urllib_error"""
+
+
+_urllib_error_moved_attributes = [
+ MovedAttribute("URLError", "urllib2", "urllib.error"),
+ MovedAttribute("HTTPError", "urllib2", "urllib.error"),
+ MovedAttribute("ContentTooShortError", "urllib", "urllib.error"),
+]
+for attr in _urllib_error_moved_attributes:
+ setattr(Module_six_moves_urllib_error, attr.name, attr)
+del attr
+
+Module_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes
+
+_importer._add_module(Module_six_moves_urllib_error(__name__ + ".moves.urllib.error"),
+ "moves.urllib_error", "moves.urllib.error")
+
+
+class Module_six_moves_urllib_request(_LazyModule):
+ """Lazy loading of moved objects in six.moves.urllib_request"""
+
+
+_urllib_request_moved_attributes = [
+ MovedAttribute("urlopen", "urllib2", "urllib.request"),
+ MovedAttribute("install_opener", "urllib2", "urllib.request"),
+ MovedAttribute("build_opener", "urllib2", "urllib.request"),
+ MovedAttribute("pathname2url", "urllib", "urllib.request"),
+ MovedAttribute("url2pathname", "urllib", "urllib.request"),
+ MovedAttribute("getproxies", "urllib", "urllib.request"),
+ MovedAttribute("Request", "urllib2", "urllib.request"),
+ MovedAttribute("OpenerDirector", "urllib2", "urllib.request"),
+ MovedAttribute("HTTPDefaultErrorHandler", "urllib2", "urllib.request"),
+ MovedAttribute("HTTPRedirectHandler", "urllib2", "urllib.request"),
+ MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"),
+ MovedAttribute("ProxyHandler", "urllib2", "urllib.request"),
+ MovedAttribute("BaseHandler", "urllib2", "urllib.request"),
+ MovedAttribute("HTTPPasswordMgr", "urllib2", "urllib.request"),
+ MovedAttribute("HTTPPasswordMgrWithDefaultRealm", "urllib2", "urllib.request"),
+ MovedAttribute("AbstractBasicAuthHandler", "urllib2", "urllib.request"),
+ MovedAttribute("HTTPBasicAuthHandler", "urllib2", "urllib.request"),
+ MovedAttribute("ProxyBasicAuthHandler", "urllib2", "urllib.request"),
+ MovedAttribute("AbstractDigestAuthHandler", "urllib2", "urllib.request"),
+ MovedAttribute("HTTPDigestAuthHandler", "urllib2", "urllib.request"),
+ MovedAttribute("ProxyDigestAuthHandler", "urllib2", "urllib.request"),
+ MovedAttribute("HTTPHandler", "urllib2", "urllib.request"),
+ MovedAttribute("HTTPSHandler", "urllib2", "urllib.request"),
+ MovedAttribute("FileHandler", "urllib2", "urllib.request"),
+ MovedAttribute("FTPHandler", "urllib2", "urllib.request"),
+ MovedAttribute("CacheFTPHandler", "urllib2", "urllib.request"),
+ MovedAttribute("UnknownHandler", "urllib2", "urllib.request"),
+ MovedAttribute("HTTPErrorProcessor", "urllib2", "urllib.request"),
+ MovedAttribute("urlretrieve", "urllib", "urllib.request"),
+ MovedAttribute("urlcleanup", "urllib", "urllib.request"),
+ MovedAttribute("URLopener", "urllib", "urllib.request"),
+ MovedAttribute("FancyURLopener", "urllib", "urllib.request"),
+ MovedAttribute("proxy_bypass", "urllib", "urllib.request"),
+]
+for attr in _urllib_request_moved_attributes:
+ setattr(Module_six_moves_urllib_request, attr.name, attr)
+del attr
+
+Module_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attributes
+
+_importer._add_module(Module_six_moves_urllib_request(__name__ + ".moves.urllib.request"),
+ "moves.urllib_request", "moves.urllib.request")
+
+
+class Module_six_moves_urllib_response(_LazyModule):
+ """Lazy loading of moved objects in six.moves.urllib_response"""
+
+
+_urllib_response_moved_attributes = [
+ MovedAttribute("addbase", "urllib", "urllib.response"),
+ MovedAttribute("addclosehook", "urllib", "urllib.response"),
+ MovedAttribute("addinfo", "urllib", "urllib.response"),
+ MovedAttribute("addinfourl", "urllib", "urllib.response"),
+]
+for attr in _urllib_response_moved_attributes:
+ setattr(Module_six_moves_urllib_response, attr.name, attr)
+del attr
+
+Module_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attributes
+
+_importer._add_module(Module_six_moves_urllib_response(__name__ + ".moves.urllib.response"),
+ "moves.urllib_response", "moves.urllib.response")
+
+
+class Module_six_moves_urllib_robotparser(_LazyModule):
+ """Lazy loading of moved objects in six.moves.urllib_robotparser"""
+
+
+_urllib_robotparser_moved_attributes = [
+ MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"),
+]
+for attr in _urllib_robotparser_moved_attributes:
+ setattr(Module_six_moves_urllib_robotparser, attr.name, attr)
del attr
-moves = sys.modules["six.moves"] = _MovedItems("moves")
+Module_six_moves_urllib_robotparser._moved_attributes = _urllib_robotparser_moved_attributes
+
+_importer._add_module(Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser"),
+ "moves.urllib_robotparser", "moves.urllib.robotparser")
+
+
+class Module_six_moves_urllib(types.ModuleType):
+ """Create a six.moves.urllib namespace that resembles the Python 3 namespace"""
+ __path__ = [] # mark as package
+ parse = _importer._get_module("moves.urllib_parse")
+ error = _importer._get_module("moves.urllib_error")
+ request = _importer._get_module("moves.urllib_request")
+ response = _importer._get_module("moves.urllib_response")
+ robotparser = _importer._get_module("moves.urllib_robotparser")
+
+ def __dir__(self):
+ return ['parse', 'error', 'request', 'response', 'robotparser']
+
+_importer._add_module(Module_six_moves_urllib(__name__ + ".moves.urllib"),
+ "moves.urllib")
def add_move(move):
_meth_func = "__func__"
_meth_self = "__self__"
+ _func_closure = "__closure__"
_func_code = "__code__"
_func_defaults = "__defaults__"
-
- _iterkeys = "keys"
- _itervalues = "values"
- _iteritems = "items"
+ _func_globals = "__globals__"
else:
_meth_func = "im_func"
_meth_self = "im_self"
+ _func_closure = "func_closure"
_func_code = "func_code"
_func_defaults = "func_defaults"
-
- _iterkeys = "iterkeys"
- _itervalues = "itervalues"
- _iteritems = "iteritems"
+ _func_globals = "func_globals"
try:
next = advance_iterator
+try:
+ callable = callable
+except NameError:
+ def callable(obj):
+ return any("__call__" in klass.__dict__ for klass in type(obj).__mro__)
+
+
if PY3:
def get_unbound_function(unbound):
return unbound
- Iterator = object
+ create_bound_method = types.MethodType
- def callable(obj):
- return any("__call__" in klass.__dict__ for klass in type(obj).__mro__)
+ Iterator = object
else:
def get_unbound_function(unbound):
return unbound.im_func
+ def create_bound_method(func, obj):
+ return types.MethodType(func, obj, obj.__class__)
+
class Iterator(object):
def next(self):
get_method_function = operator.attrgetter(_meth_func)
get_method_self = operator.attrgetter(_meth_self)
+get_function_closure = operator.attrgetter(_func_closure)
get_function_code = operator.attrgetter(_func_code)
get_function_defaults = operator.attrgetter(_func_defaults)
+get_function_globals = operator.attrgetter(_func_globals)
-def iterkeys(d):
- """Return an iterator over the keys of a dictionary."""
- return getattr(d, _iterkeys)()
+if PY3:
+ def iterkeys(d, **kw):
+ return iter(d.keys(**kw))
+
+ def itervalues(d, **kw):
+ return iter(d.values(**kw))
+
+ def iteritems(d, **kw):
+ return iter(d.items(**kw))
+
+ def iterlists(d, **kw):
+ return iter(d.lists(**kw))
+else:
+ def iterkeys(d, **kw):
+ return iter(d.iterkeys(**kw))
-def itervalues(d):
- """Return an iterator over the values of a dictionary."""
- return getattr(d, _itervalues)()
+ def itervalues(d, **kw):
+ return iter(d.itervalues(**kw))
-def iteritems(d):
- """Return an iterator over the (key, value) pairs of a dictionary."""
- return getattr(d, _iteritems)()
+ def iteritems(d, **kw):
+ return iter(d.iteritems(**kw))
+
+ def iterlists(d, **kw):
+ return iter(d.iterlists(**kw))
+
+_add_doc(iterkeys, "Return an iterator over the keys of a dictionary.")
+_add_doc(itervalues, "Return an iterator over the values of a dictionary.")
+_add_doc(iteritems,
+ "Return an iterator over the (key, value) pairs of a dictionary.")
+_add_doc(iterlists,
+ "Return an iterator over the (key, [values]) pairs of a dictionary.")
if PY3:
return s.encode("latin-1")
def u(s):
return s
+ unichr = chr
if sys.version_info[1] <= 1:
def int2byte(i):
return bytes((i,))
else:
# This is about 2x faster than the implementation above on 3.2+
int2byte = operator.methodcaller("to_bytes", 1, "big")
+ byte2int = operator.itemgetter(0)
+ indexbytes = operator.getitem
+ iterbytes = iter
import io
StringIO = io.StringIO
BytesIO = io.BytesIO
else:
def b(s):
return s
+ # Workaround for standalone backslash
def u(s):
- return unicode(s, "unicode_escape")
+ return unicode(s.replace(r'\\', r'\\\\'), "unicode_escape")
+ unichr = unichr
int2byte = chr
+ def byte2int(bs):
+ return ord(bs[0])
+ def indexbytes(buf, i):
+ return ord(buf[i])
+ def iterbytes(buf):
+ return (ord(byte) for byte in buf)
import StringIO
StringIO = BytesIO = StringIO.StringIO
_add_doc(b, """Byte literal""")
if PY3:
- import builtins
- exec_ = getattr(builtins, "exec")
+ exec_ = getattr(moves.builtins, "exec")
def reraise(tp, value, tb=None):
raise value.with_traceback(tb)
raise value
-
- print_ = getattr(builtins, "print")
- del builtins
-
else:
- def exec_(code, globs=None, locs=None):
+ def exec_(_code_, _globs_=None, _locs_=None):
"""Execute code in a namespace."""
- if globs is None:
+ if _globs_ is None:
frame = sys._getframe(1)
- globs = frame.f_globals
- if locs is None:
- locs = frame.f_locals
+ _globs_ = frame.f_globals
+ if _locs_ is None:
+ _locs_ = frame.f_locals
del frame
- elif locs is None:
- locs = globs
- exec("""exec code in globs, locs""")
+ elif _locs_ is None:
+ _locs_ = _globs_
+ exec("""exec _code_ in _globs_, _locs_""")
exec_("""def reraise(tp, value, tb=None):
""")
+print_ = getattr(moves.builtins, "print", None)
+if print_ is None:
def print_(*args, **kwargs):
- """The new-style print function."""
+ """The new-style print function for Python 2.4 and 2.5."""
fp = kwargs.pop("file", sys.stdout)
if fp is None:
return
def write(data):
if not isinstance(data, basestring):
data = str(data)
+ # If the file has an encoding, encode unicode with it.
+ if (isinstance(fp, file) and
+ isinstance(data, unicode) and
+ fp.encoding is not None):
+ errors = getattr(fp, "errors", None)
+ if errors is None:
+ errors = "strict"
+ data = data.encode(fp.encoding, errors)
fp.write(data)
want_unicode = False
sep = kwargs.pop("sep", None)
_add_doc(reraise, """Reraise an exception.""")
+if sys.version_info[0:2] < (3, 4):
+ def wraps(wrapped):
+ def wrapper(f):
+ f = functools.wraps(wrapped)(f)
+ f.__wrapped__ = wrapped
+ return f
+ return wrapper
+else:
+ wraps = functools.wraps
-def with_metaclass(meta, base=object):
+def with_metaclass(meta, *bases):
"""Create a base class with a metaclass."""
- return meta("NewBase", (base,), {})
+ # This requires a bit of explanation: the basic idea is to make a dummy
+ # metaclass for one level of class instantiation that replaces itself with
+ # the actual metaclass.
+ class metaclass(meta):
+ def __new__(cls, name, this_bases, d):
+ return meta(name, bases, d)
+ return type.__new__(metaclass, 'temporary_class', (), {})
+
+
+def add_metaclass(metaclass):
+ """Class decorator for creating a class with a metaclass."""
+ def wrapper(cls):
+ orig_vars = cls.__dict__.copy()
+ orig_vars.pop('__dict__', None)
+ orig_vars.pop('__weakref__', None)
+ slots = orig_vars.get('__slots__')
+ if slots is not None:
+ if isinstance(slots, str):
+ slots = [slots]
+ for slots_var in slots:
+ orig_vars.pop(slots_var)
+ return metaclass(cls.__name__, cls.__bases__, orig_vars)
+ return wrapper
+
+# Complete the moves implementation.
+# This code is at the end of this module to speed up module loading.
+# Turn this module into a package.
+__path__ = [] # required for PEP 302 and PEP 451
+__package__ = __name__ # see PEP 366 @ReservedAssignment
+if globals().get("__spec__") is not None:
+ __spec__.submodule_search_locations = [] # PEP 451 @UndefinedVariable
+# Remove other six meta path importers, since they cause problems. This can
+# happen if six is removed from sys.modules and then reloaded. (Setuptools does
+# this for some reason.)
+if sys.meta_path:
+ for i, importer in enumerate(sys.meta_path):
+ # Here's some real nastiness: Another "instance" of the six module might
+ # be floating around. Therefore, we can't use isinstance() to check for
+ # the six meta path importer, since the other six instance will have
+ # inserted an importer with different class.
+ if (type(importer).__name__ == "_SixMetaPathImporter" and
+ importer.name == __name__):
+ del sys.meta_path[i]
+ break
+ del i, importer
+# Finally, add the importer to the meta path import hook.
+sys.meta_path.append(_importer)
from datetime import datetime
-from ..datetime_util import parse_to_datetime, datetime_to_native
+from mock import patch
+
+from ..datetime_util import parse_to_datetime, datetime_to_native, datetime_to_INTERNALDATE
from ..fixed_offset import FixedOffset
from .util import unittest
def test_rfc822_style(self):
self.check_normalised_and_not(
- 'Sun, 24 Mar 2013 22:06:10 +0200',
+ b'Sun, 24 Mar 2013 22:06:10 +0200',
datetime(2013, 3, 24, 22, 6, 10, 0, FixedOffset(120))
)
def test_internaldate_style(self):
self.check_normalised_and_not(
- ' 9-Feb-2007 17:08:08 -0430',
+ b' 9-Feb-2007 17:08:08 -0430',
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))
+ )
+
+ def test_dots_for_time_separator(self):
+ # As reported in issue #154.
+ self.check_normalised_and_not(
+ b'Sat, 8 May 2010 16.03.09 +0200',
+ datetime(2010, 5, 8, 16, 3, 9, 0, FixedOffset(120))
+ )
+ self.check_normalised_and_not(
+ b'Tue, 18 May 2010 16.03.09 -0200',
+ datetime(2010, 5, 18, 16, 3, 9, 0, FixedOffset(-120))
+ )
+ self.check_normalised_and_not(
+ b'Wednesday,18 August 2010 16.03.09 -0200',
+ datetime(2010, 8, 18, 16, 3, 9, 0, FixedOffset(-120))
+ )
def test_invalid(self):
- self.assertRaises(ValueError, parse_to_datetime, 'ABC')
+ self.assertRaises(ValueError, parse_to_datetime, b'ABC')
+
+
+class TestDatetimeToINTERNALDATE(unittest.TestCase):
+
+ def test_with_timezone(self):
+ 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')
+ def test_without_timezone(self, for_system):
+ dt = datetime(2009, 1, 2, 3, 4, 5, 0)
+ for_system.return_value = FixedOffset(-5 * 60)
+
+ self.assertEqual(datetime_to_INTERNALDATE(dt), '02-Jan-2009 03:04:05 -0500')
from __future__ import unicode_literals
-from imapclient.six import text_type, PY3
+from imapclient.six import text_type, binary_type, int2byte, unichr
from imapclient.imap_utf7 import decode, encode
from imapclient.test.util import unittest
-if PY3:
- unichr = chr # unichr doesn't exist in py3 where every string is unicode
class IMAP4UTF7TestCase(unittest.TestCase):
tests = [
- ['Foo', 'Foo'],
- ['Foo Bar', 'Foo Bar'],
- ['Stuff & Things', 'Stuff &- Things'],
- ['Hello world', 'Hello world'],
- ['Hello & world', 'Hello &- world'],
- ['Hello\xffworld', 'Hello&AP8-world'],
- ['\xff\xfe\xfd\xfc', '&AP8A,gD9APw-'],
+ ['Foo', b'Foo'],
+ ['Foo Bar', b'Foo Bar'],
+ ['Stuff & Things', b'Stuff &- Things'],
+ ['Hello world', b'Hello world'],
+ ['Hello & world', b'Hello &- world'],
+ ['Hello\xffworld', b'Hello&AP8-world'],
+ ['\xff\xfe\xfd\xfc', b'&AP8A,gD9APw-'],
['~peter/mail/\u65e5\u672c\u8a9e/\u53f0\u5317',
- '~peter/mail/&ZeVnLIqe-/&U,BTFw-'], # example from RFC 2060
- ['\x00foo', '&AAA-foo'],
+ b'~peter/mail/&ZeVnLIqe-/&U,BTFw-'], # example from RFC 2060
+ ['\x00foo', b'&AAA-foo'],
]
def test_encode(self):
for (input, output) in self.tests:
encoded = encode(input)
- self.assertIsInstance(encoded, text_type)
+ self.assertIsInstance(encoded, binary_type)
self.assertEqual(encoded, output)
self.assertIsInstance(decoded, text_type)
self.assertEqual(input, decoded)
- def test_printableSingletons(self):
+ def test_printable_singletons(self):
"""
The IMAP4 modified UTF-7 implementation encodes all printable
characters which are in ASCII using the corresponding ASCII byte.
"""
# All printables represent themselves
for o in list(range(0x20, 0x26)) + list(range(0x27, 0x7f)):
- self.assertEqual(unichr(o), encode(chr(o)))
- self.assertEqual(unichr(o), decode(unichr(o)))
- self.assertEqual(encode('&'), '&-')
- self.assertEqual(encode('&'), '&-')
+ self.assertEqual(int2byte(o), encode(unichr(o)))
+ self.assertEqual(unichr(o), decode(int2byte(o)))
+ self.assertEqual(encode('&'), b'&-')
+ self.assertEqual(encode('&'), b'&-')
self.assertEqual(decode(b'&-'), '&')
-
-if __name__ == '__main__':
- unittest.main()
from .testable_imapclient import TestableIMAPClient as IMAPClient
from .imapclient_test import IMAPClientTest
+
class TestListFolders(IMAPClientTest):
def test_list_folders(self):
folders = self.client.list_folders('foo', 'bar')
self.client._imap._simple_command.assert_called_once_with(
- 'LIST', '"foo"', '"bar"')
+ 'LIST', b'"foo"', b'"bar"')
self.assertEqual(self.client._proc_folder_list.call_args, ((sentinel.folder_data,), {}))
self.assertTrue(folders is sentinel.folder_list)
folders = self.client.list_sub_folders('foo', 'bar')
self.client._imap._simple_command.assert_called_once_with(
- 'LSUB', '"foo"', '"bar"')
+ 'LSUB', b'"foo"', b'"bar"')
self.assertEqual(self.client._proc_folder_list.call_args, ((sentinel.folder_data,), {}))
self.assertTrue(folders is sentinel.folder_list)
folders = self.client.list_folders('foo', 'bar')
- self.client._imap._simple_command.assert_called_once_with('LIST', '"foo"', '"bar"')
- self.assertEqual(folders, [(('\\HasNoChildren',), '/', 'A'),
- (('\\HasNoChildren',), '/', 'Hello\xffworld')])
+ self.client._imap._simple_command.assert_called_once_with('LIST', b'"foo"', b'"bar"')
+ self.assertEqual(folders, [((b'\\HasNoChildren',), b'/', 'A'),
+ ((b'\\HasNoChildren',), b'/', 'Hello\xffworld')])
def test_folder_encode_off(self):
self.client.folder_encode = False
folders = self.client.list_folders('foo', 'bar')
self.client._imap._simple_command.assert_called_once_with('LIST', '"foo"', '"bar"')
- self.assertEqual(folders, [(('\\HasNoChildren',), '/', 'A'),
- (('\\HasNoChildren',), '/', 'Hello&AP8-world')])
+ self.assertEqual(folders, [((b'\\HasNoChildren',), b'/', b'A'),
+ ((b'\\HasNoChildren',), b'/', b'Hello&AP8-world')])
def test_simple(self):
- folders = self.client._proc_folder_list(['(\\HasNoChildren) "/" "A"',
- '(\\HasNoChildren) "/" "Foo Bar"',
+ folders = self.client._proc_folder_list([b'(\\HasNoChildren) "/" "A"',
+ b'(\\HasNoChildren) "/" "Foo Bar"',
])
- self.assertEqual(folders, [(('\\HasNoChildren',), '/', 'A',),
- (('\\HasNoChildren',), '/', 'Foo Bar')])
+ self.assertEqual(folders, [((b'\\HasNoChildren',), b'/', 'A',),
+ ((b'\\HasNoChildren',), b'/', 'Foo Bar')])
def test_without_quotes(self):
- folders = self.client._proc_folder_list(['(\\HasNoChildren) "/" A',
- '(\\HasNoChildren) "/" B',
- '(\\HasNoChildren) "/" C',
+ folders = self.client._proc_folder_list([b'(\\HasNoChildren) "/" A',
+ b'(\\HasNoChildren) "/" B',
+ b'(\\HasNoChildren) "/" C',
])
- self.assertEqual(folders, [(('\\HasNoChildren',), '/', 'A'),
- (('\\HasNoChildren',), '/', 'B'),
- (('\\HasNoChildren',), '/', 'C')])
+ self.assertEqual(folders, [((b'\\HasNoChildren',), b'/', 'A'),
+ ((b'\\HasNoChildren',), b'/', 'B'),
+ ((b'\\HasNoChildren',), b'/', 'C')])
def test_unquoted_numeric_folder_name(self):
# Some IMAP implementations do this
- folders = self.client._proc_folder_list(['(\\HasNoChildren) "/" 123'])
- self.assertEqual(folders, [(('\\HasNoChildren',), '/', '123')])
+ folders = self.client._proc_folder_list([b'(\\HasNoChildren) "/" 123'])
+ self.assertEqual(folders, [((b'\\HasNoChildren',), b'/', '123')])
def test_mixed(self):
- folders = self.client._proc_folder_list(['(\\HasNoChildren) "/" Alpha',
- '(\\HasNoChildren) "/" "Foo Bar"',
- '(\\HasNoChildren) "/" C',
+ folders = self.client._proc_folder_list([b'(\\HasNoChildren) "/" Alpha',
+ b'(\\HasNoChildren) "/" "Foo Bar"',
+ b'(\\HasNoChildren) "/" C',
])
- self.assertEqual(folders, [(('\\HasNoChildren',), '/', 'Alpha'),
- (('\\HasNoChildren',), '/', 'Foo Bar'),
- (('\\HasNoChildren',), '/', 'C')])
+ self.assertEqual(folders, [((b'\\HasNoChildren',), b'/', 'Alpha'),
+ ((b'\\HasNoChildren',), b'/', 'Foo Bar'),
+ ((b'\\HasNoChildren',), b'/', 'C')])
def test_funky_characters(self):
- folders = self.client._proc_folder_list([('(\\NoInferiors \\UnMarked) "/" {5}', 'bang\xff'),
- '',
- '(\\HasNoChildren \\UnMarked) "/" "INBOX"'])
- self.assertEqual(folders, [(('\\NoInferiors', '\\UnMarked'), "/", 'bang\xff'),
- (('\\HasNoChildren', '\\UnMarked'), "/", 'INBOX')])
+ folders = self.client._proc_folder_list([(b'(\\NoInferiors \\UnMarked) "/" {5}', 'bang\xff'),
+ b'',
+ b'(\\HasNoChildren \\UnMarked) "/" "INBOX"'])
+ 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([r'(\HasNoChildren) "/" "Test \"Folder\""',
- r'(\HasNoChildren) "/" "Left\"Right"',
- r'(\HasNoChildren) "/" "Left\\Right"',
- r'(\HasNoChildren) "/" "\"Left Right\""',
- r'(\HasNoChildren) "/" "\"Left\\Right\""',
+ folders = self.client._proc_folder_list([br'(\HasNoChildren) "/" "Test \"Folder\""',
+ br'(\HasNoChildren) "/" "Left\"Right"',
+ br'(\HasNoChildren) "/" "Left\\Right"',
+ br'(\HasNoChildren) "/" "\"Left Right\""',
+ br'(\HasNoChildren) "/" "\"Left\\Right\""',
])
- self.assertEqual(folders, [(('\\HasNoChildren',), '/', 'Test "Folder"'),
- (('\\HasNoChildren',), '/', 'Left\"Right'),
- (('\\HasNoChildren',), '/', r'Left\Right'),
- (('\\HasNoChildren',), '/', r'"Left Right"'),
- (('\\HasNoChildren',), '/', r'"Left\Right"'),
+ self.assertEqual(folders, [((b'\\HasNoChildren',), b'/', 'Test "Folder"'),
+ ((b'\\HasNoChildren',), b'/', 'Left\"Right'),
+ ((b'\\HasNoChildren',), b'/', r'Left\Right'),
+ ((b'\\HasNoChildren',), b'/', r'"Left Right"'),
+ ((b'\\HasNoChildren',), b'/', r'"Left\Right"'),
])
def test_empty_response(self):
def test_blanks(self):
- folders = self.client._proc_folder_list(['', None, r'(\HasNoChildren) "/" "last"'])
- self.assertEqual(folders, [((r'\HasNoChildren',), '/', 'last')])
+ folders = self.client._proc_folder_list(['', None, br'(\HasNoChildren) "/" "last"'])
+ self.assertEqual(folders, [((br'\HasNoChildren',), b'/', 'last')])
class TestSelectFolder(IMAPClientTest):
result = self.client.select_folder(b'folder_name', sentinel.readonly)
self.client._command_and_check.assert_called_once_with('select',
- '"folder_name"',
+ b'"folder_name"',
sentinel.readonly)
self.maxDiff = 99999
self.assertEqual(result, {
- 'EXISTS': 3,
- 'RECENT': 0,
- 'UIDNEXT': 1281,
- 'UIDVALIDITY': 631062293,
- 'HIGHESTMODSEQ': 127110,
- 'FLAGS': (r'\Flagged', r'\Deleted', 'abc', '[foo]/bar', 'def'),
- 'PERMANENTFLAGS': (r'\Flagged', r'\Deleted', 'abc', '[foo]/bar', 'def', r'\*'),
- 'READ-WRITE': True,
- 'OTHER': ['blah']
+ b'EXISTS': 3,
+ b'RECENT': 0,
+ b'UIDNEXT': 1281,
+ b'UIDVALIDITY': 631062293,
+ b'HIGHESTMODSEQ': 127110,
+ b'FLAGS': (br'\Flagged', br'\Deleted', b'abc', b'[foo]/bar', b'def'),
+ b'PERMANENTFLAGS': (br'\Flagged', br'\Deleted', b'abc', b'[foo]/bar', b'def', br'\*'),
+ b'READ-WRITE': True,
+ b'OTHER': [b'blah']
})
self.client.append('foobar', msg, ['FLAG', 'WAVE'], None)
self.client._imap.append.assert_called_with(
- '"foobar"', '(FLAG WAVE)', None, b'hi')
+ b'"foobar"', '(FLAG WAVE)', None, b'hi')
- @patch('imapclient.imapclient.datetime_to_imap')
- def test_with_msg_time(self, datetime_to_imap):
- datetime_to_imap.return_value = 'somedate'
+ @patch('imapclient.imapclient.datetime_to_INTERNALDATE')
+ def test_with_msg_time(self, datetime_to_INTERNALDATE):
+ datetime_to_INTERNALDATE.return_value = 'somedate'
self.client._imap.append.return_value = ('OK', [b'Good'])
msg = b'bye'
self.client.append('foobar', msg, ['FLAG', 'WAVE'],
datetime(2009, 4, 5, 11, 0, 5, 0, FixedOffset(2*60)))
- self.assertTrue(datetime_to_imap.called)
+ self.assertTrue(datetime_to_INTERNALDATE.called)
self.client._imap.append.assert_called_with(
- '"foobar"', '(FLAG WAVE)', '"somedate"', msg)
+ b'"foobar"', '(FLAG WAVE)', '"somedate"', msg)
class TestAclMethods(IMAPClientTest):
def test_getacl(self):
self.client._imap.getacl.return_value = ('OK', [b'INBOX Fred rwipslda Sally rwip'])
acl = self.client.getacl('INBOX')
- self.assertSequenceEqual(acl, [('Fred', 'rwipslda'), ('Sally', 'rwip')])
+ self.assertSequenceEqual(acl, [(b'Fred', b'rwipslda'), (b'Sally', b'rwip')])
def test_setacl(self):
self.client._imap.setacl.return_value = ('OK', [b"SETACL done"])
response = self.client.setacl('folder', sentinel.who, sentinel.what)
- self.client._imap.setacl.assert_called_with('"folder"',
+ self.client._imap.setacl.assert_called_with(b'"folder"',
sentinel.who,
sentinel.what)
- self.assertEqual(response, "SETACL done")
+ self.assertEqual(response, b"SETACL done")
class TestIdleAndNoop(IMAPClientTest):
def fake_get_line():
count = six.next(counter)
if count == 0:
- return '* 1 EXISTS'
+ return b'* 1 EXISTS'
elif count == 1:
- return '* 0 EXPUNGE'
+ return b'* 0 EXPUNGE'
else:
raise socket.timeout
self.client._imap._get_line = fake_get_line
self.assertListEqual(mock_sock.method_calls,
[('setblocking', (0,), {}),
('setblocking', (1,), {})])
- self.assertListEqual([(1, 'EXISTS'), (0, 'EXPUNGE')], responses)
+ self.assertListEqual([(1, b'EXISTS'), (0, b'EXPUNGE')], responses)
@patch('imapclient.imapclient.select.select')
def test_idle_check_timeout(self, mock_select):
self.assertListEqual(mock_sock.method_calls,
[('setblocking', (0,), {}),
('setblocking', (1,), {})])
- self.assertListEqual([(99, 'EXISTS')], responses)
+ self.assertListEqual([(99, b'EXISTS')], responses)
def test_idle_done(self):
self.client._idle_tag = sentinel.tag
def fake_get_response():
count = six.next(counter)
if count == 0:
- return '* 99 EXISTS'
- client._imap.tagged_commands[sentinel.tag] = ('OK', ['Idle done'])
+ return b'* 99 EXISTS'
+ client._imap.tagged_commands[sentinel.tag] = ('OK', [b'Idle done'])
client._imap._get_response = fake_get_response
-
- text, responses = client._consume_until_tagged_response(sentinel.tag,
- 'IDLE')
+
+ text, responses = client._consume_until_tagged_response(sentinel.tag, b'IDLE')
self.assertEqual(client._imap.tagged_commands, {})
- self.assertEqual(text, 'Idle done')
- self.assertListEqual([(99, 'EXISTS')], responses)
+ self.assertEqual(text, b'Idle done')
+ self.assertListEqual([(99, b'EXISTS')], responses)
-
class TestDebugLogging(IMAPClientTest):
def test_default_is_stderr(self):
def test_get(self):
with patch.object(self.client, 'fetch', autospec=True,
- return_value={123: {'X-GM-LABELS': ['foo', 'bar']},
- 444: {'X-GM-LABELS': ['foo']}}):
+ return_value={123: {b'X-GM-LABELS': [b'foo', b'bar']},
+ 444: {b'X-GM-LABELS': [b'foo']}}):
out = self.client.get_gmail_labels(sentinel.messages)
- self.client.fetch.assert_called_with(sentinel.messages, ['X-GM-LABELS'])
- self.assertEqual(out, {123: ['foo', 'bar'],
- 444: ['foo']})
+ self.client.fetch.assert_called_with(sentinel.messages, [b'X-GM-LABELS'])
+ self.assertEqual(out, {123: [b'foo', b'bar'],
+ 444: [b'foo']})
def test_add(self):
self.client.add_gmail_labels(sentinel.messages, sentinel.labels)
- self.client._store.assert_called_with('+X-GM-LABELS', sentinel.messages, sentinel.labels, 'X-GM-LABELS')
+ self.client._store.assert_called_with(b'+X-GM-LABELS', sentinel.messages, sentinel.labels, b'X-GM-LABELS')
def test_remove(self):
self.client.remove_gmail_labels(sentinel.messages, sentinel.labels)
- self.client._store.assert_called_with('-X-GM-LABELS', sentinel.messages, sentinel.labels, 'X-GM-LABELS')
+ self.client._store.assert_called_with(b'-X-GM-LABELS', sentinel.messages, sentinel.labels, b'X-GM-LABELS')
def test_set(self):
self.client.set_gmail_labels(sentinel.messages, sentinel.labels)
- self.client._store.assert_called_with('X-GM-LABELS', sentinel.messages, sentinel.labels, 'X-GM-LABELS')
+ self.client._store.assert_called_with(b'X-GM-LABELS', sentinel.messages, sentinel.labels, b'X-GM-LABELS')
class TestNamespace(IMAPClientTest):
self.set_return(b'(("FOO." "/")) NIL NIL')
self.assertEqual(self.client.namespace(), ((('FOO.', '/'),), None, None))
+ def test_folder_decoding(self):
+ self.set_return(b'(("&AP8-." "/")) NIL NIL')
+ self.assertEqual(self.client.namespace(), ((('\xff.', '/'),), None, None))
+
+ def test_without_folder_decoding(self):
+ self.set_return(b'(("&AP8-." "/")) NIL NIL')
+ self.client.folder_encode = False
+ self.assertEqual(self.client.namespace(), (((b'&AP8-.', '/'),), None, None))
+
def test_other_only(self):
self.set_return(b'NIL NIL (("" "."))')
self.assertEqual(self.client.namespace(), (None, None, (("", "."),)))
(("#shared/", "/"), ("#public/", "/"), ("#ftp/", "/"), ("#news.", ".")),
))
+
class TestCapabilities(IMAPClientTest):
def test_preauth(self):
self.client._imap.capabilities = ('FOO', 'BAR')
self.client._imap.untagged_responses = {}
- self.assertEqual(self.client.capabilities(), ('FOO', 'BAR'))
+ self.assertEqual(self.client.capabilities(), (b'FOO', b'BAR'))
def test_server_returned_capability_after_auth(self):
- self.client._imap.capabilities = ('FOO',)
- self.client._imap.untagged_responses = {'CAPABILITY': ['FOO MORE']}
+ self.client._imap.capabilities = (b'FOO',)
+ self.client._imap.untagged_responses = {'CAPABILITY': [b'FOO MORE']}
self.assertEqual(self.client._cached_capabilities, None)
- self.assertEqual(self.client.capabilities(), ('FOO', 'MORE'))
- self.assertEqual(self.client._cached_capabilities, ('FOO', 'MORE'))
+ self.assertEqual(self.client.capabilities(), (b'FOO', b'MORE'))
+ self.assertEqual(self.client._cached_capabilities, (b'FOO', b'MORE'))
def test_caching(self):
self.client._imap.capabilities = ('FOO',)
self.client._imap.untagged_responses = {}
- self.client._cached_capabilities = ('FOO', 'MORE')
+ self.client._cached_capabilities = (b'FOO', b'MORE')
- self.assertEqual(self.client.capabilities(), ('FOO', 'MORE'))
+ self.assertEqual(self.client.capabilities(), (b'FOO', b'MORE'))
def test_post_auth_request(self):
self.client._imap.capabilities = ('FOO',)
self.client._imap.state = 'SELECTED'
self.client._imap.capability.return_value = ('OK', [b'FOO BAR'])
- self.assertEqual(self.client.capabilities(), ('FOO', 'BAR'))
- self.assertEqual(self.client._cached_capabilities, ('FOO', 'BAR'))
+ self.assertEqual(self.client.capabilities(), (b'FOO', b'BAR'))
+ self.assertEqual(self.client._cached_capabilities, (b'FOO', b'BAR'))
+
+ def test_has_capability(self):
+ self.client._cached_capabilities = (b'FOO', b'MORE')
+
+ self.assertTrue(self.client.has_capability(b'FOO'))
+ self.assertTrue(self.client.has_capability(b'foo'))
+ self.assertFalse(self.client.has_capability(b'BAR'))
+
+ self.assertTrue(self.client.has_capability('FOO'))
+ self.assertTrue(self.client.has_capability('foo'))
+ self.assertFalse(self.client.has_capability('BAR'))
class TestThread(IMAPClientTest):
def test_thread_without_uid(self):
- self.client._cached_capabilities = ('THREAD=REFERENCES',)
+ self.client._cached_capabilities = (b'THREAD=REFERENCES',)
self.client.use_uid = False
self.client._imap.thread.return_value = ('OK', [b'(1 2)(3)(4 5 6)'])
self.assertSequenceEqual(threads, ((1, 2), (3,), (4, 5, 6)))
def test_thread_with_uid(self):
- self.client._cached_capabilities = ('THREAD=REFERENCES',)
+ self.client._cached_capabilities = (b'THREAD=REFERENCES',)
self.client.use_uid = True
self.client._imap.uid.return_value = ('OK', [b'(1 2)(3)(4 5 6)'])
self.assertSequenceEqual(threads, ((1, 2), (3,), (4, 5, 6)))
def test_no_support(self):
- self.client._cached_capabilities = ('NOT-THREAD',)
+ self.client._cached_capabilities = (b'NOT-THREAD',)
self.assertRaises(ValueError, self.client.thread)
def test_no_support2(self):
- self.client._cached_capabilities = ('THREAD=FOO',)
+ self.client._cached_capabilities = (b'THREAD=FOO',)
self.assertRaises(ValueError, self.client.thread)
def test_all_args_with_uid(self):
- self.client._cached_capabilities = ('THREAD=FOO',)
+ self.client._cached_capabilities = (b'THREAD=FOO',)
self.client._imap.uid.return_value = ('OK', [])
self.client.thread(algorithm='FOO', criteria='STUFF', charset='ASCII')
- self.client._imap.uid.assert_called_once_with('thread', 'FOO', 'ASCII', '(STUFF)')
+ self.client._imap.uid.assert_called_once_with('thread', b'FOO', b'ASCII', '(STUFF)')
def test_all_args_without_uid(self):
self.client.use_uid = False
- self.client._cached_capabilities = ('THREAD=FOO',)
+ self.client._cached_capabilities = (b'THREAD=FOO',)
self.client._imap.thread.return_value = ('OK', [])
self.client.thread(algorithm='FOO', criteria='STUFF', charset='ASCII')
- self.client._imap.thread.assert_called_once_with('FOO', 'ASCII','(STUFF)')
+ self.client._imap.thread.assert_called_once_with(b'FOO', b'ASCII', '(STUFF)')
+
+
+class TestId(IMAPClientTest):
+
+ def test_id(self):
+ self.client._cached_capabilities = (b'ID',)
+ self.client._imap._simple_command.return_value = ('OK', [b'Success'])
+ self.client._imap._untagged_response.return_value = (
+ b'OK', [b'("name" "GImap" "vendor" "Google, Inc.")'])
+
+ id_response = self.client.id_({'name': 'IMAPClient'})
+ self.client._imap._simple_command.assert_called_with(
+ 'ID', '("name" "IMAPClient")')
+
+ self.assertSequenceEqual(
+ id_response,
+ ((b'name', b'GImap', b'vendor', b'Google, Inc.'),))
+
+ def test_no_support(self):
+ self.client._cached_capabilities = (b'IMAP4rev1',)
+ self.assertRaises(ValueError, self.client.id_)
+
+ def test_invalid_parameters(self):
+ self.assertRaises(TypeError, self.client.id_, 'bananarama')
self.assertEqual(imap.ssl, True)
self.assertEqual(imap.stream, False)
+ def test_SSL_kwargs(self):
+ self.imaplib.IMAP4_SSL.return_value = sentinel.IMAP4_SSL
+
+ imap = IMAPClient('1.2.3.4', ssl=True, keyfile='key.pem',
+ certfile='cert.pem')
+
+ self.assertEqual(imap._imap, sentinel.IMAP4_SSL)
+ self.imaplib.IMAP4_SSL.assert_called_with('1.2.3.4', 993,
+ keyfile='key.pem', certfile='cert.pem')
+ self.assertEqual(imap.ssl, True)
+ self.assertEqual(imap.stream, False)
+
+ imap = IMAPClient('1.2.3.4', ssl=True, ssl_context=sentinel.context)
+ self.imaplib.IMAP4_SSL.assert_called_with('1.2.3.4', 993,
+ ssl_context=sentinel.context)
+ self.assertEqual(imap.ssl, True)
+ self.assertEqual(imap.stream, False)
+
+
def test_stream(self):
self.imaplib.IMAP4_stream.return_value = sentinel.IMAP4_stream
from __future__ import unicode_literals
from datetime import datetime
-from textwrap import dedent
+from imapclient.datetime_util import datetime_to_native
from imapclient.fixed_offset import FixedOffset
from imapclient.response_parser import parse_response, parse_fetch_response, ParseError
from imapclient.response_types import Envelope, Address
from imapclient.test.util import unittest
-#TODO: tokenising tests
#TODO: test invalid dates and times
-CRLF = '\r\n'
+CRLF = b'\r\n'
class TestParseResponse(unittest.TestCase):
def test_unquoted(self):
- self._test('FOO', 'FOO')
- self._test('F.O:-O_0;', 'F.O:-O_0;')
- self._test(r'\Seen', r'\Seen')
+ self._test(b'FOO', b'FOO')
+ self._test(b'F.O:-O_0;', b'F.O:-O_0;')
+ self._test(br'\Seen', br'\Seen')
def test_string(self):
- self._test('"TEST"', 'TEST')
+ self._test(b'"TEST"', b'TEST')
def test_int(self):
- self._test('45', 45)
+ self._test(b'45', 45)
def test_nil(self):
- self._test('NIL', None)
+ self._test(b'NIL', None)
def test_empty_tuple(self):
- self._test('()', ())
+ self._test(b'()', ())
def test_tuple(self):
- self._test('(123 "foo" GeE)', (123, 'foo', 'GeE'))
+ self._test(b'(123 "foo" GeE)', (123, b'foo', b'GeE'))
def test_int_and_tuple(self):
- self._test('1 (123 "foo")', (1, (123, 'foo')), wrap=False)
+ self._test(b'1 (123 "foo")', (1, (123, b'foo')), wrap=False)
def test_nested_tuple(self):
- self._test('(123 "foo" ("more" NIL) 66)',
- (123, "foo", ("more", None), 66))
+ self._test(b'(123 "foo" ("more" NIL) 66)',
+ (123, b"foo", (b"more", None), 66))
def test_deeper_nest_tuple(self):
- self._test('(123 "foo" ((0 1 2) "more" NIL) 66)',
- (123, "foo", ((0, 1, 2), "more", None), 66))
+ self._test(b'(123 "foo" ((0 1 2) "more" NIL) 66)',
+ (123, b"foo", ((0, 1, 2), b"more", None), 66))
def test_complex_mixed(self):
- self._test('((FOO "PLAIN" ("CHARSET" "US-ASCII") NIL NIL "7BIT" 1152 23) '
- '("TEXT" "PLAIN" ("CHARSET" "US-ASCII" "NAME" "cc.diff") '
- '"<hi.there>" "foo" "BASE64" 4554 73) "MIXED")',
- (('FOO', 'PLAIN', ('CHARSET', 'US-ASCII'), None, None, '7BIT', 1152, 23),
- ('TEXT', 'PLAIN', ('CHARSET', 'US-ASCII', 'NAME', 'cc.diff'),
- '<hi.there>', 'foo', 'BASE64', 4554, 73), 'MIXED'))
+ self._test(b'((FOO "PLAIN" ("CHARSET" "US-ASCII") NIL NIL "7BIT" 1152 23) '
+ b'("TEXT" "PLAIN" ("CHARSET" "US-ASCII" "NAME" "cc.diff") '
+ 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'))
def test_envelopey(self):
- self._test('(UID 5 ENVELOPE ("internal_date" "subject" '
- '(("name" NIL "address1" "domain1.com")) '
- '((NIL NIL "address2" "domain2.com")) '
- '(("name" NIL "address3" "domain3.com")) '
- '((NIL NIL "address4" "domain4.com")) '
- 'NIL NIL "<reply-to-id>" "<msg_id>"))',
- ('UID',
+ self._test(b'(UID 5 ENVELOPE ("internal_date" "subject" '
+ b'(("name" NIL "address1" "domain1.com")) '
+ b'((NIL NIL "address2" "domain2.com")) '
+ b'(("name" NIL "address3" "domain3.com")) '
+ b'((NIL NIL "address4" "domain4.com")) '
+ b'NIL NIL "<reply-to-id>" "<msg_id>"))',
+ (b'UID',
5,
- 'ENVELOPE',
- ('internal_date',
- 'subject',
- (('name', None, 'address1', 'domain1.com'),),
- ((None, None, 'address2', 'domain2.com'),),
- (('name', None, 'address3', 'domain3.com'),),
- ((None, None, 'address4', 'domain4.com'),),
+ b'ENVELOPE',
+ (b'internal_date',
+ b'subject',
+ ((b'name', None, b'address1', b'domain1.com'),),
+ ((None, None, b'address2', b'domain2.com'),),
+ ((b'name', None, b'address3', b'domain3.com'),),
+ ((None, None, b'address4', b'domain4.com'),),
None,
None,
- '<reply-to-id>',
- '<msg_id>')))
+ b'<reply-to-id>',
+ b'<msg_id>')))
def test_envelopey_quoted(self):
- self._test('(UID 5 ENVELOPE ("internal_date" "subject with \\"quotes\\"" '
- '(("name" NIL "address1" "domain1.com")) '
- '((NIL NIL "address2" "domain2.com")) '
- '(("name" NIL "address3" "domain3.com")) '
- '((NIL NIL "address4" "domain4.com")) '
- 'NIL NIL "<reply-to-id>" "<msg_id>"))',
- ('UID',
+ self._test(b'(UID 5 ENVELOPE ("internal_date" "subject with \\"quotes\\"" '
+ b'(("name" NIL "address1" "domain1.com")) '
+ b'((NIL NIL "address2" "domain2.com")) '
+ b'(("name" NIL "address3" "domain3.com")) '
+ b'((NIL NIL "address4" "domain4.com")) '
+ b'NIL NIL "<reply-to-id>" "<msg_id>"))',
+ (b'UID',
5,
- 'ENVELOPE',
- ('internal_date',
- 'subject with "quotes"',
- (('name', None, 'address1', 'domain1.com'),),
- ((None, None, 'address2', 'domain2.com'),),
- (('name', None, 'address3', 'domain3.com'),),
- ((None, None, 'address4', 'domain4.com'),),
+ b'ENVELOPE',
+ (b'internal_date',
+ b'subject with "quotes"',
+ ((b'name', None, b'address1', b'domain1.com'),),
+ ((None, None, b'address2', b'domain2.com'),),
+ ((b'name', None, b'address3', b'domain3.com'),),
+ ((None, None, b'address4', b'domain4.com'),),
None,
None,
- '<reply-to-id>',
- '<msg_id>')))
+ b'<reply-to-id>',
+ b'<msg_id>')))
def test_literal(self):
- literal_text = add_crlf(dedent("""\
- 012
- abc def XYZ
- """))
- self._test([('{18}', literal_text)], literal_text)
+ literal_text = add_crlf(
+ b"012\n"
+ b"abc def XYZ\n"
+ )
+ self._test([(b'{18}', literal_text)], literal_text)
def test_literal_with_more(self):
- literal_text = add_crlf(dedent("""\
- 012
- abc def XYZ
- """))
- response = [('(12 "foo" {18}', literal_text), ")"]
- self._test(response, (12, 'foo', literal_text))
+ literal_text = add_crlf(
+ b"012\n"
+ b"abc def XYZ\n"
+ )
+ response = [(b'(12 "foo" {18}', literal_text), b")"]
+ self._test(response, (12, b'foo', literal_text))
def test_quoted_specials(self):
- self._test(r'"\"foo bar\""', '"foo bar"')
- self._test(r'"foo \"bar\""', 'foo "bar"')
- self._test(r'"foo\\bar"', r'foo\bar')
+ self._test(br'"\"foo bar\""', b'"foo bar"')
+ self._test(br'"foo \"bar\""', b'foo "bar"')
+ self._test(br'"foo\\bar"', br'foo\bar')
def test_square_brackets(self):
- self._test('foo[bar rrr]', 'foo[bar rrr]')
- self._test('"foo[bar rrr]"', 'foo[bar rrr]')
- self._test('[foo bar]def', '[foo bar]def')
- self._test('(foo [bar rrr])', ('foo', '[bar rrr]'))
- self._test('(foo foo[bar rrr])', ('foo', 'foo[bar rrr]'))
+ self._test(b'foo[bar rrr]', b'foo[bar rrr]')
+ self._test(b'"foo[bar rrr]"', b'foo[bar rrr]')
+ self._test(b'[foo bar]def', b'[foo bar]def')
+ self._test(b'(foo [bar rrr])', (b'foo', b'[bar rrr]'))
+ self._test(b'(foo foo[bar rrr])', (b'foo', b'foo[bar rrr]'))
def test_incomplete_tuple(self):
- self._test_parse_error('abc (1 2', 'Tuple incomplete before "\(1 2"')
+ self._test_parse_error(b'abc (1 2', 'Tuple incomplete before "\(1 2"')
def test_bad_literal(self):
- self._test_parse_error([('{99}', 'abc')],
+ self._test_parse_error([(b'{99}', b'abc')],
'Expecting literal of size 99, got 3')
def test_bad_quoting(self):
- self._test_parse_error('"abc next', """No closing '"'""")
+ self._test_parse_error(b'"abc next', """No closing '"'""")
def _test(self, to_parse, expected, wrap=True):
if wrap:
class TestParseFetchResponse(unittest.TestCase):
def test_basic(self):
- self.assertEqual(parse_fetch_response('4 ()'), {4: {'SEQ': 4}})
+ self.assertEqual(parse_fetch_response([b'4 ()']), {4: {b'SEQ': 4}})
def test_none_special_case(self):
def test_bad_msgid(self):
- self.assertRaises(ParseError, parse_fetch_response, ['abc ()'])
+ self.assertRaises(ParseError, parse_fetch_response, [b'abc ()'])
def test_bad_data(self):
- self.assertRaises(ParseError, parse_fetch_response, ['2 WHAT'])
+ self.assertRaises(ParseError, parse_fetch_response, [b'2 WHAT'])
def test_missing_data(self):
- self.assertRaises(ParseError, parse_fetch_response, ['2'])
+ self.assertRaises(ParseError, parse_fetch_response, [b'2'])
def test_simple_pairs(self):
- self.assertEqual(parse_fetch_response(['23 (ABC 123 StUfF "hello")']),
- {23: {'ABC': 123,
- 'STUFF': 'hello',
- 'SEQ': 23}})
+ self.assertEqual(parse_fetch_response([b'23 (ABC 123 StUfF "hello")']),
+ {23: {b'ABC': 123,
+ b'STUFF': b'hello',
+ b'SEQ': 23}})
def test_odd_pairs(self):
- self.assertRaises(ParseError, parse_fetch_response, ['(ONE)'])
- self.assertRaises(ParseError, parse_fetch_response, ['(ONE TWO THREE)'])
+ 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(['23 (UID 76)']),
- {76: {'SEQ': 23}})
- self.assertEqual(parse_fetch_response(['23 (uiD 76)']),
- {76: {'SEQ': 23}})
+ 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(['23 (UID 76)'], uid_is_key=False),
- {23: {'UID': 76,
- 'SEQ': 23}})
+ self.assertEqual(parse_fetch_response([b'23 (UID 76)'], uid_is_key=False),
+ {23: {b'UID': 76,
+ b'SEQ': 23}})
def test_bad_UID(self):
- self.assertRaises(ParseError, parse_fetch_response, ['(UID X)'])
-
+ self.assertRaises(ParseError, parse_fetch_response, [b'(UID X)'])
+
def test_FLAGS(self):
- self.assertEqual(parse_fetch_response(['23 (FLAGS (\Seen Stuff))']),
- {23: {'SEQ': 23, 'FLAGS': (r'\Seen', 'Stuff')}})
+ self.assertEqual(parse_fetch_response([b'23 (FLAGS (\Seen Stuff))']),
+ {23: {b'SEQ': 23, b'FLAGS': (br'\Seen', b'Stuff')}})
def test_multiple_messages(self):
self.assertEqual(parse_fetch_response(
- ["2 (FLAGS (Foo Bar)) ",
- "7 (FLAGS (Baz Sneeve))"]),
+ [b"2 (FLAGS (Foo Bar)) ",
+ b"7 (FLAGS (Baz Sneeve))"]),
{
- 2: {'FLAGS': ('Foo', 'Bar'), 'SEQ': 2},
- 7: {'FLAGS': ('Baz', 'Sneeve'), 'SEQ': 7},
+ 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(
- ["2 (FLAGS (Foo Bar)) ",
- "2 (MODSEQ 4)"]),
- {2: {'FLAGS': ('Foo', 'Bar'), 'SEQ': 2, '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([('1 (RFC822.TEXT {4}', 'body'),
- (' RFC822 {21}', 'Subject: test\r\n\r\nbody'),
- ')']),
- {1: {'RFC822.TEXT': 'body',
- 'RFC822': 'Subject: test\r\n\r\nbody',
- 'SEQ': 1}})
+ 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}})
def test_literals_and_keys_with_square_brackets(self):
- self.assertEqual(parse_fetch_response([('1 (BODY[TEXT] {11}', 'Hi there.\r\n'), ')']),
- { 1: {'BODY[TEXT]': 'Hi there.\r\n',
- 'SEQ': 1}})
+ 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}})
def test_BODY_HEADER_FIELDS(self):
- header_text = 'Subject: A subject\r\nFrom: Some one <someone@mail.com>\r\n\r\n'
+ header_text = b'Subject: A subject\r\nFrom: Some one <someone@mail.com>\r\n\r\n'
self.assertEqual(parse_fetch_response(
- [('123 (UID 31710 BODY[HEADER.FIELDS (from subject)] {57}', header_text), ')']),
- { 31710: {'BODY[HEADER.FIELDS (FROM SUBJECT)]': header_text,
- 'SEQ': 123}})
+ [(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}})
def test_BODY(self):
- self.check_BODYish_single_part('BODY')
- self.check_BODYish_multipart('BODY')
- self.check_BODYish_nested_multipart('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('BODYSTRUCTURE')
- self.check_BODYish_nested_multipart('BODYSTRUCTURE')
+ self.check_BODYish_single_part(b'BODYSTRUCTURE')
+ self.check_BODYish_nested_multipart(b'BODYSTRUCTURE')
def check_BODYish_single_part(self, respType):
- text = '123 (UID 317 %s ("TEXT" "PLAIN" ("CHARSET" "us-ascii") NIL NIL "7BIT" 16 1))' % respType
+ text = b'123 (UID 317 ' + respType + b'("TEXT" "PLAIN" ("CHARSET" "us-ascii") NIL NIL "7BIT" 16 1))'
parsed = parse_fetch_response([text])
- self.assertEqual(parsed, {317: {respType: ('TEXT', 'PLAIN', ('CHARSET', 'us-ascii'), None, None, '7BIT', 16, 1),
- 'SEQ': 123 }
- })
+ self.assertEqual(parsed, {
+ 317: {
+ respType: (b'TEXT', b'PLAIN', (b'CHARSET', b'us-ascii'), None, None, b'7BIT', 16, 1),
+ b'SEQ': 123
+ }
+ })
self.assertFalse(parsed[317][respType].is_multipart)
def check_BODYish_multipart(self, respType):
- text = '123 (UID 269 %s (("TEXT" "HTML" ("CHARSET" "us-ascii") NIL NIL "QUOTED-PRINTABLE" 55 3)' \
- '("TEXT" "PLAIN" ("CHARSET" "us-ascii") NIL NIL "7BIT" 26 1) "MIXED"))' \
- % respType
+ text = b'123 (UID 269 ' + respType + b' ' \
+ b'(("TEXT" "HTML" ("CHARSET" "us-ascii") NIL NIL "QUOTED-PRINTABLE" 55 3)' \
+ b'("TEXT" "PLAIN" ("CHARSET" "us-ascii") NIL NIL "7BIT" 26 1) "MIXED"))'
parsed = parse_fetch_response([text])
- self.assertEqual(parsed, {269: {respType: ([('TEXT', 'HTML', ('CHARSET', 'us-ascii'), None, None, 'QUOTED-PRINTABLE', 55, 3),
- ('TEXT', 'PLAIN', ('CHARSET', 'us-ascii'), None, None, '7BIT', 26, 1)],
- 'MIXED'),
- 'SEQ': 123}
- })
+ self.assertEqual(parsed, {
+ 269: {
+ respType: ([(b'TEXT', b'HTML', (b'CHARSET', b'us-ascii'), None, None, b'QUOTED-PRINTABLE', 55, 3),
+ (b'TEXT', b'PLAIN', (b'CHARSET', b'us-ascii'), None, None, b'7BIT', 26, 1)],
+ b'MIXED'),
+ b'SEQ': 123}
+ })
self.assertTrue(parsed[269][respType].is_multipart)
def check_BODYish_nested_multipart(self, respType):
- text = '1 (%s (' \
- '(' \
- '("text" "html" ("charset" "utf-8") NIL NIL "7bit" 97 3 NIL NIL NIL NIL)' \
- '("text" "plain" ("charset" "utf-8") NIL NIL "7bit" 62 3 NIL NIL NIL NIL)' \
- '"alternative" ("boundary" "===============8211050864078048428==") NIL NIL NIL' \
- ')' \
- '("text" "plain" ("charset" "utf-8") NIL NIL "7bit" 16 1 NIL ("attachment" ("filename" "attachment.txt")) NIL NIL) ' \
- '"mixed" ("boundary" "===============0373402508605428821==") NIL NIL NIL))' \
- % 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')' \
+ 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))'
parsed = parse_fetch_response([text])
self.assertEqual(parsed, {1: {
[
(
[
- ('text', 'html', ('charset', 'utf-8'), None, None, '7bit', 97, 3, None, None, None, None),
- ('text', 'plain', ('charset', 'utf-8'), None, None, '7bit', 62, 3, None, None, None, None)
- ], 'alternative', ('boundary', '===============8211050864078048428=='), 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
),
- ('text', 'plain', ('charset', 'utf-8'), None, None, '7bit', 16, 1, None, ('attachment', ('filename', 'attachment.txt')), None, None)
- ], 'mixed', ('boundary', '===============0373402508605428821=='), 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'mixed', (b'boundary', b'===============0373402508605428821=='), None, None, None,
),
- 'SEQ': 1,
+ b'SEQ': 1,
}})
self.assertTrue(parsed[1][respType].is_multipart)
self.assertTrue(parsed[1][respType][0][0].is_multipart)
self.assertFalse(parsed[1][respType][0][0][0][0].is_multipart)
def test_partial_fetch(self):
- body = '01234567890123456789'
+ body = b'01234567890123456789'
self.assertEqual(parse_fetch_response(
- [('123 (UID 367 BODY[]<0> {20}', body), ')']),
- { 367: {'BODY[]<0>': body,
- 'SEQ': 123}})
+ [(b'123 (UID 367 BODY[]<0> {20}', body), b')']),
+ { 367: {b'BODY[]<0>': body,
+ b'SEQ': 123}})
def test_ENVELOPE(self):
- envelope_str = ('1 (ENVELOPE ( '
- '"Sun, 24 Mar 2013 22:06:10 +0200" '
- '"subject" '
- '(("name" NIL "address1" "domain1.com")) '
- '((NIL NIL "address2" "domain2.com")) '
- '(("name" NIL "address3" "domain3.com")) '
- 'NIL'
- '((NIL NIL "address4" "domain4.com") '
- '("person" NIL "address4b" "domain4b.com")) '
- 'NIL "<reply-to-id>" "<msg_id>"))')
+ 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>"))')
output = parse_fetch_response([envelope_str], normalise_times=False)
- self.assertSequenceEqual(output[1]['ENVELOPE'],
+ self.assertSequenceEqual(output[1][b'ENVELOPE'],
Envelope(
datetime(2013, 3, 24, 22, 6, 10, tzinfo=FixedOffset(120)),
- "subject",
- (Address("name", None, "address1", "domain1.com"),),
- (Address(None, None, "address2", "domain2.com"),),
- (Address("name", None, "address3", "domain3.com"),),
+ 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, "address4", "domain4.com"),
- Address("person", None, "address4b", "domain4b.com")),
- None, "<reply-to-id>", "<msg_id>"
+ (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_normalised(self):
- def check(date_str, expected_dt):
- output = parse_fetch_response(['3 (INTERNALDATE "%s")' % date_str])
- actual_dt = output[3]['INTERNALDATE']
- self.assertTrue(actual_dt.tzinfo is None) # Returned date should be in local timezone
- expected_dt = datetime_to_native(expected_dt)
- self.assertEqual(actual_dt, expected_dt)
-
- check(' 9-Feb-2007 17:08:08 -0430',
- datetime(2007, 2, 9, 17, 8, 8, 0, FixedOffset(-4*60 - 30)))
-
- check('12-Feb-2007 17:08:08 +0200',
- datetime(2007, 2, 12, 17, 8, 8, 0, FixedOffset(2*60)))
-
- check(' 9-Dec-2007 17:08:08 +0000',
- datetime(2007, 12, 9, 17, 8, 8, 0, FixedOffset(0)))
+ def test_ENVELOPE_with_no_date(self):
+ envelope_str = (
+ b'1 (ENVELOPE ( '
+ b'NIL '
+ b'"subject" '
+ b'NIL '
+ b'NIL '
+ b'NIL '
+ b'NIL '
+ b'NIL '
+ b'NIL '
+ b'"<reply-to-id>" '
+ b'"<msg_id>"))'
+ )
- def test_INTERNALDATE(self):
- def check(date_str, expected_dt):
- output = parse_fetch_response(['3 (INTERNALDATE "%s")' % date_str], normalise_times=False)
- actual_dt = output[3]['INTERNALDATE']
- self.assertEqual(actual_dt, expected_dt)
-
- check(' 9-Feb-2007 17:08:08 -0430',
- datetime(2007, 2, 9, 17, 8, 8, 0, FixedOffset(-4*60 - 30)))
-
- check('12-Feb-2007 17:08:08 +0200',
- datetime(2007, 2, 12, 17, 8, 8, 0, FixedOffset(2*60)))
-
- check(' 9-Dec-2007 17:08:08 +0000',
- datetime(2007, 12, 9, 17, 8, 8, 0, FixedOffset(0)))
+ output = parse_fetch_response([envelope_str], normalise_times=False)
- def test_mixed_types(self):
- self.assertEqual(parse_fetch_response([('1 (INTERNALDATE " 9-Feb-2007 17:08:08 +0100" RFC822 {21}',
- 'Subject: test\r\n\r\nbody'),
- ')']),
- {1: {'INTERNALDATE': datetime_to_native(datetime(2007, 2, 9,
- 17, 8, 8, 0,
- FixedOffset(60))),
- 'RFC822': 'Subject: test\r\n\r\nbody',
- 'SEQ': 1}})
+ self.assertSequenceEqual(output[1][b'ENVELOPE'],
+ 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>"))')
-def add_crlf(text):
- return CRLF.join(text.splitlines()) + CRLF
+ 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>",
+ )
+ )
-system_offset = FixedOffset.for_system()
-def datetime_to_native(dt):
- return dt.astimezone(system_offset).replace(tzinfo=None)
+ 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>"))')
+ 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>"
+ )
+ )
+
+ def test_INTERNALDATE(self):
+ out = parse_fetch_response(
+ [b'1 (INTERNALDATE " 9-Feb-2007 17:08:08 -0430")'],
+ normalise_times=False
+ )
+ self.assertEqual(
+ out[1][b'INTERNALDATE'],
+ 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)))
+ self.assertEqual(dt, expected_dt)
+
+ def test_mixed_types(self):
+ self.assertEqual(parse_fetch_response([(
+ b'1 (INTERNALDATE " 9-Feb-2007 17:08:08 +0100" RFC822 {21}',
+ b'Subject: test\r\n\r\nbody'
+ ), b')']), {
+ 1: {
+ b'INTERNALDATE': datetime_to_native(datetime(2007, 2, 9, 17, 8, 8, 0, FixedOffset(60))),
+ b'RFC822': b'Subject: test\r\n\r\nbody',
+ b'SEQ': 1
+ }
+ })
+
+
+def add_crlf(text):
+ return CRLF.join(text.splitlines()) + CRLF
self.client._imap.uid.assert_called_once_with('SEARCH', '(FOO)')
self.assertEqual(result, [1, 2, 44])
+ self.assertEqual(result.modseq, None)
+
+ def test_with_uid_none(self):
+ self.client.use_uid = True
+ self.client._imap.uid.return_value = ('OK', [None])
+
+ result = self.client.search('FOO')
+
+ self.client._imap.uid.assert_called_once_with('SEARCH', '(FOO)')
+ self.assertEqual(result, [])
+ self.assertEqual(result.modseq, None)
def test_without_uid(self):
self.client.use_uid = False
self.client._imap.search.assert_called_once_with(None, '(FOO)')
self.assertEqual(result, [1, 2, 44])
+ self.assertEqual(result.modseq, None)
def test_with_uid_with_charset(self):
self.client.use_uid = True
self.client._imap.uid.assert_called_once_with(
'SEARCH',
- 'CHARSET', 'UTF9',
+ b'CHARSET', 'UTF9',
'(FOO)')
self.assertEqual(result, [1, 2, 44])
self.client._imap.search.assert_called_once_with('UTF9', '(FOO)', '(BAR)')
self.assertEqual(result, [1, 2, 44])
+ def test_modseq(self):
+ self.client._imap.uid.return_value = ('OK', [b'1 2 (MODSEQ 51101)'])
+
+ result = self.client.search(['MODSEQ 40000'])
+
+ self.client._imap.uid.assert_called_once_with('SEARCH', '(MODSEQ 40000)')
+ self.assertEqual(result, [1, 2])
+ self.assertEqual(result.modseq, 51101)
+
def test_error_from_server(self):
self.client._imap.uid.return_value = ('NO', [b'bad karma'])
self.assertRaisesRegex(IMAPClient.Error,
'bad karma',
- self.client.search, 'FOO')
+ self.client.search, b'FOO')
class TestGmailSearch(IMAPClientTest):
result = self.client.gmail_search('FOO')
- self.client._imap.uid.assert_called_once_with('SEARCH', 'X-GM-RAW')
+ self.client._imap.uid.assert_called_once_with('SEARCH', b'X-GM-RAW')
self.assertEqual(self.client._imap.literal, b'FOO')
self.assertEqual(result, [1, 2, 44])
result = self.client.gmail_search('FOO')
- self.client._imap.search.assert_called_once_with(None, 'X-GM-RAW')
+ self.client._imap.search.assert_called_once_with(None, b'X-GM-RAW')
self.assertEqual(self.client._imap.literal, b'FOO')
self.assertEqual(result, [1, 2, 44])
self.client._imap.uid.assert_called_once_with(
'SEARCH',
- 'CHARSET', 'UTF8',
- 'X-GM-RAW')
+ b'CHARSET', 'UTF8',
+ b'X-GM-RAW')
self.assertEqual(self.client._imap.literal, b'\xe2\x98\xa0')
self.assertEqual(result, [1, 2, 44])
result = self.client.gmail_search('\u2620', 'UTF8')
- self.client._imap.search.assert_called_once_with('UTF8', 'X-GM-RAW')
+ self.client._imap.search.assert_called_once_with('UTF8', b'X-GM-RAW')
self.assertEqual(self.client._imap.literal, b'\xe2\x98\xa0')
self.assertEqual(result, [1, 2, 44])
self.assertRaisesRegex(IMAPClient.Error,
'bad karma',
- self.client.gmail_search, 'FOO')
+ self.client.gmail_search, b'FOO')
from __future__ import unicode_literals
-from datetime import datetime
-
-from mock import patch
-
from imapclient.imapclient import (
- datetime_to_imap,
- messages_to_str,
+ join_message_ids,
normalise_search_criteria,
normalise_text_list,
seq_to_parenstr,
seq_to_parenstr_upper,
)
-from imapclient.fixed_offset import FixedOffset
from imapclient.test.util import unittest
def test_mixed_list(self):
self.check(['foo', b'BAR'], '(FOO BAR)')
-class Test_messages_to_str(unittest.TestCase):
+class Test_join_message_ids(unittest.TestCase):
def check(self, items, expected):
- self.assertEqual(messages_to_str(items), expected)
+ self.assertEqual(join_message_ids(items), expected)
def test_int(self):
- self.check(123, '123')
+ self.check(123, b'123')
def test_unicode(self):
- self.check('123', '123')
+ self.check('123', b'123')
def test_unicode_non_numeric(self):
- self.check('2:*', '2:*')
+ self.check('2:*', b'2:*')
def test_binary(self):
- self.check(b'123', '123')
+ self.check(b'123', b'123')
def test_binary_non_numeric(self):
- self.check(b'2:*', '2:*')
+ self.check(b'2:*', b'2:*')
def test_tuple(self):
- self.check((123, 99), '123,99')
+ self.check((123, 99), b'123,99')
def test_mixed_list(self):
- self.check(['2:3', 123, b'44'], '2:3,123,44')
+ self.check(['2:3', 123, b'44'], b'2:3,123,44')
def test_iter(self):
- self.check(iter([123, 99]), '123,99')
+ self.check(iter([123, 99]), b'123,99')
class Test_normalise_search_criteria(unittest.TestCase):
def test_empty(self):
self.assertRaises(ValueError, normalise_search_criteria, '')
-
-class TestDateTimeToImap(unittest.TestCase):
-
- def test_with_timezone(self):
- dt = datetime(2009, 1, 2, 3, 4, 5, 0, FixedOffset(2*60 + 30))
- self.assertEqual(datetime_to_imap(dt), '02-Jan-2009 03:04:05 +0230')
-
- @patch('imapclient.imapclient.FixedOffset.for_system')
- def test_without_timezone(self, for_system):
- dt = datetime(2009, 1, 2, 3, 4, 5, 0)
- for_system.return_value = FixedOffset(-5 * 60)
-
- self.assertEqual(datetime_to_imap(dt), '02-Jan-2009 03:04:05 -0500')
super(TestableIMAPClient, self).__init__('somehost')
def _create_IMAP4(self):
- mock_IMAP4 = Mock()
- mock_IMAP4._quote = self._quote
- return mock_IMAP4
-
- def _quote(self, arg):
- """The real code from IMAP4._quote."""
- arg = arg.replace('\\', '\\\\')
- arg = arg.replace('"', '\\"')
- return '"%s"' % arg
+ return Mock()
def patch_TestCase():
TestCase = unittest.TestCase
# Older versions of unittest2 don't have
- # TestCase.assertRaisesRegex # and newer version raises warnings
- # when you use # assertRaisesRegexp. This helps deal with the
+ # TestCase.assertRaisesRegex and newer version raises warnings
+ # when you use assertRaisesRegexp. This helps deal with the
# mismatch.
if not hasattr(TestCase, 'assertRaisesRegex'):
TestCase.assertRaisesRegex = TestCase.assertRaisesRegexp
from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
+import sys
import imapclient
version = imapclient.__version__
+MAJ_MIN = sys.version_info[:2]
+IS_PY_26_OR_OLDER = MAJ_MIN <= (2, 6)
+IS_PY_34_OR_NEWER = MAJ_MIN >= (3, 4)
+
desc = """\
IMAPClient is an easy-to-use, Pythonic and complete IMAP client library.
* Convenience methods are provided for commonly used functionality.
* Exceptions are raised when errors occur.
-Python versions 2.6, 2.7, 3.2 and 3.3 are officially supported.
+Python versions 2.6, 2.7, 3.2, 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.
"""
def run_tests(self):
from imapclient.test.util import unittest # this will import unittest2
- unittest.main(argv=['', 'discover'])
+ module = "__main__"
+ if IS_PY_26_OR_OLDER or IS_PY_34_OR_NEWER:
+ module = None
+ unittest.main(argv=['', 'discover'], module=module)
+test_deps = ['mock==0.8.0']
+if IS_PY_26_OR_OLDER:
+ test_deps.append('unittest2')
setup(name='IMAPClient',
version=version,
download_url='http://freshfoo.com/projects/IMAPClient/IMAPClient-%s.zip' % version,
packages=find_packages(),
package_data=dict(imapclient=['examples/*.py']),
- tests_require=['mock==0.8.0'],
+ tests_require=test_deps,
description="Easy-to-use, Pythonic and complete IMAP client library",
long_description=desc,
classifiers=[
[tox]
-envlist=py26,py27,py32,py33
+envlist=py26,py27,py32,py33,py34
[testenv]
commands=python setup.py test
-
-[testenv:py26]
-deps=unittest2