]> khamidou — GitHub mirrors - flanker.git/commitdiff
Make EmailAddress.display_name to be a arbitrary string
authorMaxim Vladimirsky <horkhe@gmail.com>
Fri, 25 Jul 2014 17:46:50 +0000 (21:46 +0400)
committerMaxim Vladimirsky <horkhe@gmail.com>
Wed, 30 Jul 2014 05:17:27 +0000 (09:17 +0400)
flanker/addresslib/address.py
flanker/addresslib/parser.py
flanker/addresslib/quote.py [new file with mode: 0644]
tests/addresslib/address_test.py
tests/addresslib/parser_address_list_test.py
tests/addresslib/parser_mailbox_test.py
tests/addresslib/quote_test.py [new file with mode: 0644]

index 7c5712038551719443f07d90ce3b8a6901e02aee..e3756ece746e0bf2e788384d9fabd6a56dfcb472 100644 (file)
@@ -36,6 +36,7 @@ See the parser.py module for implementation details of the parser.
 
 import time
 import flanker.addresslib.parser
+from flanker.addresslib.quote import smart_unquote, smart_quote
 import flanker.addresslib.validate
 
 from flanker.addresslib.parser import MAX_ADDRESS_LENGTH
@@ -345,18 +346,19 @@ class EmailAddress(Address):
 
     __slots__ = ['display_name', 'mailbox', 'hostname', 'address']
 
-    def __init__(self, display_name, spec=None):
+    def __init__(self, display_name, spec=None, parsed_name=None):
         if spec is None:
             spec = display_name
             display_name = None
 
         assert(spec)
 
-        if display_name is None:
-            self.display_name = u''
+        if parsed_name:
+            self.display_name = smart_unquote(mime_to_unicode(parsed_name))
+        elif display_name:
+            self.display_name = display_name
         else:
-            self.display_name = encode_string(None, display_name,
-                                              maxlinelen=MAX_ADDRESS_LENGTH)
+            self.display_name = u''
 
         parts = spec.rsplit('@', 1)
         self.mailbox = parts[0]
@@ -385,16 +387,6 @@ class EmailAddress(Address):
         """
         return True
 
-    @property
-    def display_name(self):
-        if self._display_name is None:
-            return u''
-        return mime_to_unicode(self._display_name)
-
-    @display_name.setter
-    def display_name(self, value):
-        self._display_name = value
-
     def full_spec(self):
         """
         Returns a full spec of an email address. Always in ASCII, RFC-2822
@@ -405,8 +397,10 @@ class EmailAddress(Address):
            >>> EmailAddress("Жека", "ev@example.com").full_spec()
            '=?utf-8?b?0JbQtdC60LA=?= <ev@example.com>'
         """
-        if self._display_name:
-            return '{0} <{1}>'.format(self._display_name, self.address)
+        if self.display_name:
+            encoded_display_name = smart_quote(encode_string(
+                None, self.display_name, maxlinelen=MAX_ADDRESS_LENGTH))
+            return '{0} <{1}>'.format(encoded_display_name, self.address)
         return u'{0}'.format(self.address)
 
     def to_unicode(self):
@@ -535,7 +529,6 @@ class AddressList(object):
             container = []
         self.container = container
 
-
     def append(self, n):
         self.container.append(n)
 
index 70794b6b7bac8591d849d606ce0e631ea847be25..4f96804458b35557ba93d139ef33548285acc352 100644 (file)
@@ -356,8 +356,9 @@ class _AddressParser(object):
             return None
 
         if dname:
-            return flanker.addresslib.address.EmailAddress(dname, aaddr)
-        return flanker.addresslib.address.EmailAddress(None, aaddr)
+            return flanker.addresslib.address.EmailAddress(aaddr,
+                                                           parsed_name=dname)
+        return flanker.addresslib.address.EmailAddress(aaddr)
 
     def _display_name_rfc(self):
         """
@@ -440,8 +441,9 @@ class _AddressParser(object):
             return None
 
         if dname:
-            return flanker.addresslib.address.EmailAddress(dname, aaddr)
-        return flanker.addresslib.address.EmailAddress(None, aaddr)
+            return flanker.addresslib.address.EmailAddress(aaddr,
+                                                           parsed_name=dname)
+        return flanker.addresslib.address.EmailAddress(aaddr)
 
     def _display_name_lax(self):
         """
@@ -548,7 +550,7 @@ class _AddressParser(object):
         aspec = cleanup_email(''.join([lpart, asym, domn]))
         if as_string:
             return aspec
-        return flanker.addresslib.address.EmailAddress(None, aspec)
+        return flanker.addresslib.address.EmailAddress(aspec)
 
     def _local_part(self):
         """
diff --git a/flanker/addresslib/quote.py b/flanker/addresslib/quote.py
new file mode 100644 (file)
index 0000000..7004c3c
--- /dev/null
@@ -0,0 +1,56 @@
+from StringIO import StringIO
+import re
+from flanker.addresslib.tokenizer import ATOM, WHITESPACE
+
+
+_RE_ATOM_PHRASE = re.compile(
+    r'({atom}({whitespace}{atom})*)|^$'
+    .format(atom=ATOM.pattern, whitespace=WHITESPACE.pattern),
+    re.MULTILINE | re.VERBOSE)
+
+
+def smart_quote(s):
+    """
+    Quotes the input string but only if it contains at least one word that is
+    not an rfc2822 atom. That is probably a little bit excessive but we better
+    be safe then sorry.
+    """
+    if _contains_atoms_only(s):
+        return s
+
+    return '"' + s.replace('\\', '\\\\').replace('"', '\\"') + '"'
+
+
+def smart_unquote(s):
+    """
+    Returns a string that is created from the input string by unquoting all
+    quoted regions in there. If there are no quoted regions in the input string
+    then output string is identical to the input string.
+    """
+    unquoted = StringIO()
+    escaped_char = False
+    is_quoted_section = False
+    for c in s:
+        if is_quoted_section:
+            if escaped_char:
+                escaped_char = False
+            else:
+                if c == '"':
+                    is_quoted_section = False
+                    continue
+                elif c == '\\':
+                    escaped_char = True
+                    continue
+        else:
+            if c == '"':
+                is_quoted_section = True
+                continue
+
+        unquoted.write(c)
+
+    return unquoted.getvalue()
+
+
+def _contains_atoms_only(s):
+    match_result = _RE_ATOM_PHRASE.match(s)
+    return match_result and match_result.end(0) == len(s)
index 6a8ef13d7af86094e61b26090e8b19e894f6e7d9..969e7a479db09d1f5ec816a3a72762e41ba4c238 100644 (file)
@@ -99,13 +99,37 @@ def test_addresslist_with_apostrophe():
     s = '''"Allan G\'o"  <allan@example.com>, "Os Wi" <oswi@example.com>'''
     lst = parse_list(s)
     eq_ (2, len(lst))
-    eq_ ('"Allan G\'o" <allan@example.com>', lst[0].full_spec())
-    eq_ ('"Os Wi" <oswi@example.com>', lst[1].full_spec())
+    eq_ ('Allan G\'o <allan@example.com>', lst[0].full_spec())
+    eq_ ('Os Wi <oswi@example.com>', lst[1].full_spec())
     lst = parse_list("=?UTF-8?Q?Eugueny_=CF=8E_Kontsevoy?= <eugueny@gmail.com>")
-    eq_ ('=?UTF-8?Q?Eugueny_=CF=8E_Kontsevoy?= <eugueny@gmail.com>', lst.full_spec())
+    eq_ ('=?utf-8?q?Eugueny_=CF=8E_Kontsevoy?= <eugueny@gmail.com>', lst.full_spec())
     eq_ (u'Eugueny ώ Kontsevoy', lst[0].display_name)
 
 
 def test_edge_cases():
     email = EmailAddress('"foo.bar@"@example.com')
     eq_('"foo.bar@"@example.com', email.address)
+
+
+def test_display_name__to_full_spec():
+    eq_('"foo (\\"bar\\") blah" <foo@bar.com>',
+        EmailAddress('foo ("bar") blah', 'foo@bar.com').full_spec())
+    eq_('"foo. bar" <foo@bar.com>',
+        EmailAddress('foo. bar', 'foo@bar.com').full_spec())
+    eq_('"\\"\\"" <foo@bar.com>',
+        EmailAddress('""', 'foo@bar.com').full_spec()),
+    eq_('=?utf-8?b?0J/RgNC40LLQtdGCINCc0LXQtNCy0LXQtA==?= <foo@bar.com>',
+        EmailAddress(u'Привет Медвед', 'foo@bar.com').full_spec())
+
+
+def test_display_name__update():
+    # Given
+    a = EmailAddress('foo bar', 'foo@bar.com')
+    eq_('foo bar <foo@bar.com>', a.full_spec())
+
+    # When
+    a.display_name = u'Привет Медвед'
+
+    # Then
+    eq_('=?utf-8?b?0J/RgNC40LLQtdGCINCc0LXQtNCy0LXQtA==?= <foo@bar.com>',
+        a.full_spec())
index 08231b5e0e354d9ff89e5220351ae81b07b8e082..81c19cc1c74e7ed0d580d6b9aa616c50283d8042 100644 (file)
@@ -53,17 +53,17 @@ def test_simple_valid():
     assert_equal(addrs[0].full_spec(), 'http://foo.com:8080')
 
     assert_equal(addrs[1].addr_type, 'email')
-    assert_equal(addrs[1].display_name, '"Ev K."')
+    assert_equal(addrs[1].display_name, 'Ev K.')
     assert_equal(addrs[1].address, 'ev@host.com')
     assert_equal(addrs[1].full_spec(), '"Ev K." <ev@host.com>')
 
     assert_equal(addrs[2].addr_type, 'email')
-    assert_equal(addrs[2].display_name, '"Alex K"')
+    assert_equal(addrs[2].display_name, 'Alex K')
     assert_equal(addrs[2].address, 'alex@yahoo.net')
-    assert_equal(addrs[2].full_spec(), '"Alex K" <alex@yahoo.net>')
+    assert_equal(addrs[2].full_spec(), 'Alex K <alex@yahoo.net>')
 
     assert_equal(addrs[3].addr_type, 'email')
-    assert_equal(addrs[3].display_name, '"Tom, S"')
+    assert_equal(addrs[3].display_name, 'Tom, S')
     assert_equal(addrs[3].address, '"tom+[a]"@s.com')
     assert_equal(addrs[3].full_spec(), '"Tom, S" <"tom+[a]"@s.com>')
 
@@ -74,14 +74,14 @@ def test_simple_valid():
     assert_equal(2, len(addrs))
 
     assert_equal(addrs[0].addr_type, 'email')
-    assert_equal(addrs[0].display_name, '"Allan G\'o"')
+    assert_equal(addrs[0].display_name, 'Allan G\'o')
     assert_equal(addrs[0].address, 'allan@example.com')
-    assert_equal(addrs[0].full_spec(), '"Allan G\'o" <allan@example.com>')
+    assert_equal(addrs[0].full_spec(), 'Allan G\'o <allan@example.com>')
 
     assert_equal(addrs[1].addr_type, 'email')
-    assert_equal(addrs[1].display_name, '"Os Wi"')
+    assert_equal(addrs[1].display_name, 'Os Wi')
     assert_equal(addrs[1].address, 'oswi@example.com')
-    assert_equal(addrs[1].full_spec(), '"Os Wi" <oswi@example.com>')
+    assert_equal(addrs[1].full_spec(), 'Os Wi <oswi@example.com>')
 
 
     s = u'''I am also A <a@HOST.com>, Zeka <EV@host.coM> ;Gonzalo Bañuelos<gonz@host.com>'''
@@ -111,18 +111,18 @@ def test_simple_valid():
     assert_equal(3, len(addrs))
 
     assert_equal(addrs[0].addr_type, 'email')
-    assert_equal(addrs[0].display_name, '"Escaped"')
+    assert_equal(addrs[0].display_name, 'Escaped')
     assert_equal(addrs[0].address, '"\e\s\c\\a\p\e\d"@sld.com')
-    assert_equal(addrs[0].full_spec(), '"Escaped" <"\e\s\c\\a\p\e\d"@sld.com>')
+    assert_equal(addrs[0].full_spec(), 'Escaped <"\e\s\c\\a\p\e\d"@sld.com>')
 
     assert_equal(addrs[1].addr_type, 'url')
     assert_equal(addrs[1].address, 'http://userid:password@example.com:8080')
     assert_equal(addrs[1].full_spec(), 'http://userid:password@example.com:8080')
 
     assert_equal(addrs[2].addr_type, 'email')
-    assert_equal(addrs[2].display_name, '"Dmitry"')
+    assert_equal(addrs[2].display_name, 'Dmitry')
     assert_equal(addrs[2].address, 'my|\'`!#_~%$&{}?^+-*@host.com')
-    assert_equal(addrs[2].full_spec(), '"Dmitry" <my|\'`!#_~%$&{}?^+-*@host.com>')
+    assert_equal(addrs[2].full_spec(), 'Dmitry <my|\'`!#_~%$&{}?^+-*@host.com>')
 
 
     s = "http://foo.com/blah_blah_(wikipedia)"
index 3ea39d1244e20c6f3b26aaaa4cb7c8dab5ebb0f5..f80e3579eaa40f108018fce7c712c52a4719fb41 100644 (file)
@@ -1,7 +1,6 @@
 # coding:utf-8
 
-from nose.tools import assert_equal, assert_not_equal
-from nose.tools import nottest
+from nose.tools import nottest, assert_equal, assert_not_equal
 
 from flanker.addresslib import address
 from flanker.addresslib.address import EmailAddress
@@ -24,20 +23,20 @@ def chunks(l, n):
 def run_full_mailbox_test(string, expected, full_spec=None):
     mbox = address.parse(string)
     if mbox:
-        assert_equal(mbox.display_name, expected.display_name)
-        assert_equal(mbox.address, expected.address)
+        assert_equal(expected.display_name, mbox.display_name)
+        assert_equal(expected.address, mbox.address)
         if full_spec:
-            assert_equal(mbox.full_spec(), full_spec)
+            assert_equal(full_spec, mbox.full_spec())
         return
-    assert_equal(mbox, expected)
+    assert_equal(expected, mbox)
 
 @nottest
 def run_mailbox_test(string, expected_string):
     mbox = address.parse(string)
     if mbox:
-        assert_equal(mbox.address, expected_string)
+        assert_equal(expected_string, mbox.address)
         return
-    assert_equal(mbox, expected_string)
+    assert_equal(expected_string, mbox)
 
 
 def test_mailbox():
@@ -45,11 +44,11 @@ def test_mailbox():
 
     # sanity
     run_full_mailbox_test('Steve Jobs <steve@apple.com>', EmailAddress('Steve Jobs', 'steve@apple.com'))
-    run_full_mailbox_test('"Steve Jobs" <steve@apple.com>', EmailAddress('"Steve Jobs"', 'steve@apple.com'))
+    run_full_mailbox_test('"Steve Jobs" <steve@apple.com>', EmailAddress('Steve Jobs', 'steve@apple.com'))
     run_mailbox_test('<steve@apple.com>', 'steve@apple.com')
 
     run_full_mailbox_test('Steve Jobs steve@apple.com', EmailAddress('Steve Jobs', 'steve@apple.com'))
-    run_full_mailbox_test('"Steve Jobs" steve@apple.com', EmailAddress('"Steve Jobs"', 'steve@apple.com'))
+    run_full_mailbox_test('"Steve Jobs" steve@apple.com', EmailAddress('Steve Jobs', 'steve@apple.com'))
     run_mailbox_test('steve@apple.com', 'steve@apple.com')
 
 
@@ -106,17 +105,24 @@ def test_display_name():
     run_full_mailbox_test('< bill bill@microsoft.com', None)
     run_full_mailbox_test(' < bill @microsoft.com', None)
 
-
     # pass display-name quoted-string rfc
-    run_full_mailbox_test('"{0}" <a@b>'.format(FULL_QTEXT), EmailAddress('"' + FULL_QTEXT + '"', 'a@b'))
-    run_full_mailbox_test('"{0}" <a@b>'.format(FULL_QUOTED_PAIR), EmailAddress('"' + FULL_QUOTED_PAIR + '"', 'a@b'))
-    run_full_mailbox_test('"<a@b>" <a@b>', EmailAddress('"<a@b>"', 'a@b'))
-    run_full_mailbox_test('"Bill" <bill@microsoft.com>', EmailAddress('"Bill"', 'bill@microsoft.com'))
-    run_full_mailbox_test('"Bill Gates" <bill@microsoft.com>', EmailAddress('"Bill Gates"', 'bill@microsoft.com'))
-    run_full_mailbox_test('" Bill Gates" <bill@microsoft.com>', EmailAddress('" Bill Gates"', 'bill@microsoft.com'))
-    run_full_mailbox_test('"Bill Gates " <bill@microsoft.com>', EmailAddress('"Bill Gates "', 'bill@microsoft.com'))
-    run_full_mailbox_test('" Bill Gates " <bill@microsoft.com>', EmailAddress('" Bill Gates "', 'bill@microsoft.com'))
-    run_full_mailbox_test(' " Bill Gates "<bill@microsoft.com>', EmailAddress('" Bill Gates "', 'bill@microsoft.com'))
+    run_full_mailbox_test('"{0}" <a@b>'.format(FULL_QTEXT),
+                          EmailAddress(FULL_QTEXT, 'a@b'))
+    run_full_mailbox_test('"{0}" <a@b>'.format(FULL_QUOTED_PAIR),
+                          EmailAddress(''.join(VALID_QUOTED_PAIR), 'a@b'))
+    run_full_mailbox_test('"<a@b>" <a@b>', EmailAddress('<a@b>', 'a@b'))
+    run_full_mailbox_test('"Bill" <bill@microsoft.com>',
+                          EmailAddress('Bill', 'bill@microsoft.com'))
+    run_full_mailbox_test('"Bill Gates" <bill@microsoft.com>',
+                          EmailAddress('Bill Gates', 'bill@microsoft.com'))
+    run_full_mailbox_test('" Bill Gates" <bill@microsoft.com>',
+                          EmailAddress(' Bill Gates', 'bill@microsoft.com'))
+    run_full_mailbox_test('"Bill Gates " <bill@microsoft.com>',
+                          EmailAddress('Bill Gates ', 'bill@microsoft.com'))
+    run_full_mailbox_test('" Bill Gates " <bill@microsoft.com>',
+                          EmailAddress(' Bill Gates ', 'bill@microsoft.com'))
+    run_full_mailbox_test(' " Bill Gates "<bill@microsoft.com>',
+                          EmailAddress(' Bill Gates ', 'bill@microsoft.com'))
 
     # fail display-name quoted-string rfc
     run_mailbox_test('"{0} <a@b>"'.format(FULL_QUOTED_PAIR), None)
@@ -130,14 +136,21 @@ def test_display_name():
         run_mailbox_test(u'{0} <a@b>'.format(cc), None)
 
     # pass display-name quoted-string lax
-    run_full_mailbox_test('"{0}" a@b'.format(FULL_QTEXT), EmailAddress('"' + FULL_QTEXT + '"', 'a@b'))
-    run_full_mailbox_test('"{0}" a@b'.format(FULL_QUOTED_PAIR), EmailAddress('"' + FULL_QUOTED_PAIR + '"', 'a@b'))
-    run_full_mailbox_test('"a@b" a@b', EmailAddress('"a@b"', 'a@b'))
-    run_full_mailbox_test('"Bill" bill@microsoft.com', EmailAddress('"Bill"', 'bill@microsoft.com'))
-    run_full_mailbox_test('"Bill Gates" bill@microsoft.com', EmailAddress('"Bill Gates"', 'bill@microsoft.com'))
-    run_full_mailbox_test('" Bill Gates" bill@microsoft.com', EmailAddress('" Bill Gates"', 'bill@microsoft.com'))
-    run_full_mailbox_test('"Bill Gates " bill@microsoft.com', EmailAddress('"Bill Gates "', 'bill@microsoft.com'))
-    run_full_mailbox_test('" Bill Gates " bill@microsoft.com', EmailAddress('" Bill Gates "', 'bill@microsoft.com'))
+    run_full_mailbox_test('"{0}" a@b'.format(FULL_QTEXT),
+                          EmailAddress(FULL_QTEXT, 'a@b'))
+    run_full_mailbox_test('"{0}" a@b'.format(FULL_QUOTED_PAIR),
+                          EmailAddress(''.join(VALID_QUOTED_PAIR), 'a@b'))
+    run_full_mailbox_test('"a@b" a@b', EmailAddress('a@b', 'a@b'))
+    run_full_mailbox_test('"Bill" bill@microsoft.com',
+                          EmailAddress('Bill', 'bill@microsoft.com'))
+    run_full_mailbox_test('"Bill Gates" bill@microsoft.com',
+                          EmailAddress('Bill Gates', 'bill@microsoft.com'))
+    run_full_mailbox_test('" Bill Gates" bill@microsoft.com',
+                          EmailAddress(' Bill Gates', 'bill@microsoft.com'))
+    run_full_mailbox_test('"Bill Gates " bill@microsoft.com',
+                          EmailAddress('Bill Gates ', 'bill@microsoft.com'))
+    run_full_mailbox_test('" Bill Gates " bill@microsoft.com',
+                          EmailAddress(' Bill Gates ', 'bill@microsoft.com'))
 
     # fail display-name quoted-string lax
     run_mailbox_test('"Bill Gates"bill@microsoft.com', None)
@@ -192,35 +205,59 @@ def test_unicode_display_name():
     run_full_mailbox_test(u'Foo Föö Foo Föö {0}'.format(u'foo@example.com'),
         EmailAddress(u'Foo Föö Foo Föö', 'foo@example.com'), '=?utf-8?b?Rm9vIEbDtsO2IEZvbyBGw7bDtg==?= <foo@example.com>')
 
-
     # unicode, quotes, display-name rfc
-    run_full_mailbox_test(u'"ö" <{0}>'.format(u'foo@example.com'),
-        EmailAddress(u'"ö"', 'foo@example.com'), '"=?utf-8?b?w7Y=?=" <foo@example.com>')
-    run_full_mailbox_test(u'"Föö" <{0}>'.format(u'foo@example.com'),
-        EmailAddress(u'"Föö"', 'foo@example.com'), '"=?utf-8?b?RsO2w7Y=?=" <foo@example.com>')
-    run_full_mailbox_test(u'"Foo ö" <{0}>'.format(u'foo@example.com'),
-        EmailAddress(u'"Foo ö"', 'foo@example.com'), '"=?utf-8?b?Rm9vIMO2?=" <foo@example.com>')
-    run_full_mailbox_test(u'"Foo Föö" <{0}>'.format(u'foo@example.com'),
-        EmailAddress(u'"Foo Föö"', 'foo@example.com'), '"=?utf-8?b?Rm9vIEbDtsO2?=" <foo@example.com>')
-    run_full_mailbox_test(u'"Foo Föö Foo" <{0}>'.format(u'foo@example.com'),
-        EmailAddress(u'"Foo Föö Foo"', 'foo@example.com'), '"=?utf-8?b?Rm9vIEbDtsO2IEZvbw==?=" <foo@example.com>')
-    run_full_mailbox_test(u'"Foo Föö Foo Föö" <{0}>'.format(u'foo@example.com'),
-        EmailAddress(u'"Foo Föö Foo Föö"', 'foo@example.com'), '"=?utf-8?b?Rm9vIEbDtsO2IEZvbyBGw7bDtg==?=" <foo@example.com>')
+    # Note that redundant quotes are removed from the parsed address
+    run_full_mailbox_test(
+        u'"ö" <foo@example.com>',
+        EmailAddress(u'ö', 'foo@example.com'),
+        '=?utf-8?b?w7Y=?= <foo@example.com>')
+    run_full_mailbox_test(
+        u'"Föö" <foo@example.com>',
+        EmailAddress(u'Föö', 'foo@example.com'),
+        '=?utf-8?b?RsO2w7Y=?= <foo@example.com>')
+    run_full_mailbox_test(
+        u'"Foo ö" <foo@example.com>',
+        EmailAddress(u'Foo ö', 'foo@example.com'),
+        '=?utf-8?b?Rm9vIMO2?= <foo@example.com>')
+    run_full_mailbox_test(
+        u'"Foo Föö" <foo@example.com>',
+        EmailAddress(u'Foo Föö', 'foo@example.com'),
+        '=?utf-8?b?Rm9vIEbDtsO2?= <foo@example.com>')
+    run_full_mailbox_test(
+        u'"Foo Föö Foo" <foo@example.com>',
+        EmailAddress(u'Foo Föö Foo', 'foo@example.com'),
+        '=?utf-8?b?Rm9vIEbDtsO2IEZvbw==?= <foo@example.com>')
+    run_full_mailbox_test(
+        u'"Foo Föö Foo Föö" <foo@example.com>',
+        EmailAddress(u'Foo Föö Foo Föö', 'foo@example.com'),
+        '=?utf-8?b?Rm9vIEbDtsO2IEZvbyBGw7bDtg==?= <foo@example.com>')
 
     # unicode, quotes, display-name lax
-    run_full_mailbox_test(u'"ö" {0}'.format(u'foo@example.com'),
-        EmailAddress(u'"ö"', 'foo@example.com'), '"=?utf-8?b?w7Y=?=" <foo@example.com>')
-    run_full_mailbox_test(u'"Föö" {0}'.format(u'foo@example.com'),
-        EmailAddress(u'"Föö"', 'foo@example.com'), '"=?utf-8?b?RsO2w7Y=?=" <foo@example.com>')
-    run_full_mailbox_test(u'"Foo ö" {0}'.format(u'foo@example.com'),
-        EmailAddress(u'"Foo ö"', 'foo@example.com'), '"=?utf-8?b?Rm9vIMO2?=" <foo@example.com>')
-    run_full_mailbox_test(u'"Foo Föö" {0}'.format(u'foo@example.com'),
-        EmailAddress(u'"Foo Föö"', 'foo@example.com'), '"=?utf-8?b?Rm9vIEbDtsO2?=" <foo@example.com>')
-    run_full_mailbox_test(u'"Foo Föö Foo" {0}'.format(u'foo@example.com'),
-        EmailAddress(u'"Foo Föö Foo"', 'foo@example.com'), '"=?utf-8?b?Rm9vIEbDtsO2IEZvbw==?=" <foo@example.com>')
-    run_full_mailbox_test(u'"Foo Föö Foo Föö" {0}'.format(u'foo@example.com'),
-        EmailAddress(u'"Foo Föö Foo Föö"', 'foo@example.com'), '"=?utf-8?b?Rm9vIEbDtsO2IEZvbyBGw7bDtg==?=" <foo@example.com>')
-
+    # Note that the quotes are removed from the parsed address
+    run_full_mailbox_test(
+        u'"ö" foo@example.com',
+        EmailAddress(u'ö', 'foo@example.com'),
+        '=?utf-8?b?w7Y=?= <foo@example.com>')
+    run_full_mailbox_test(
+        u'"Föö" foo@example.com',
+        EmailAddress(u'Föö', 'foo@example.com'),
+        '=?utf-8?b?RsO2w7Y=?= <foo@example.com>')
+    run_full_mailbox_test(
+        u'"Foo ö" foo@example.com',
+        EmailAddress(u'Foo ö', 'foo@example.com'),
+        '=?utf-8?b?Rm9vIMO2?= <foo@example.com>')
+    run_full_mailbox_test(
+        u'"Foo Föö" foo@example.com',
+        EmailAddress(u'Foo Föö', 'foo@example.com'),
+        '=?utf-8?b?Rm9vIEbDtsO2?= <foo@example.com>')
+    run_full_mailbox_test(
+        u'"Foo Föö Foo" foo@example.com',
+        EmailAddress(u'Foo Föö Foo', 'foo@example.com'),
+        '=?utf-8?b?Rm9vIEbDtsO2IEZvbw==?= <foo@example.com>')
+    run_full_mailbox_test(
+        u'"Foo Föö Foo Föö" foo@example.com',
+        EmailAddress(u'Foo Föö Foo Föö', 'foo@example.com'),
+        '=?utf-8?b?Rm9vIEbDtsO2IEZvbyBGw7bDtg==?= <foo@example.com>')
 
     # unicode, random language sampling, see: http://www.columbia.edu/~fdc/utf8/index.html
     run_full_mailbox_test(u'나는 유리를 먹을 수 있어요 <foo@example.com>',
@@ -242,15 +279,10 @@ def test_unicode_display_name():
         EmailAddress(u'ξεσκεπάζω την', 'foo@example.com'),
         '=?utf-8?b?zr7Otc+DzrrOtc+AzqzOts+JIM+EzrfOvQ==?= <foo@example.com>')
 
-    # unicode, no quotes, punctuation
-    for i in u'''.!#$%&*+-/=?^_`{|}~''':
-        run_full_mailbox_test(u'ö {0} <foo@example.com>'.format(i),
-            EmailAddress(u'ö {0}'.format(i), 'foo@example.com'))
-
-    # unicode, quotes, punctuation
+    # unicode + punctuation
     for i in u'''.!#$%&*+-/=?^_`{|}~''':
         run_full_mailbox_test(u'"ö {0}" <foo@example.com>'.format(i),
-            EmailAddress(u'"ö {0}"'.format(i), 'foo@example.com'))
+            EmailAddress(u'ö {0}'.format(i), 'foo@example.com'))
 
 
 def test_unicode_special_chars():
@@ -308,54 +340,55 @@ def test_unicode_special_chars():
         '=?utf-8?b?Zm9vIPCfkqkgYmFy?= <foo@example.com>')
 
     # unicode, special chars, quotes
+    # Note that quotes are removed from the parsed display name
     run_full_mailbox_test(u'"foo © bar" <foo@example.com>',
-        EmailAddress(u'"foo © bar"', u'foo@example.com'),
-        '"=?utf-8?q?foo_=C2=A9_bar?=" <foo@example.com>')
+        EmailAddress(u'foo © bar', u'foo@example.com'),
+        '=?utf-8?q?foo_=C2=A9_bar?= <foo@example.com>')
     run_full_mailbox_test(u'"foo œ bar" <foo@example.com>',
-        EmailAddress(u'"foo œ bar"', u'foo@example.com'),
-        '"=?utf-8?q?foo_=C5=93_bar?=" <foo@example.com>')
+        EmailAddress(u'foo œ bar', u'foo@example.com'),
+        '=?utf-8?q?foo_=C5=93_bar?= <foo@example.com>')
     run_full_mailbox_test(u'"foo – bar" <foo@example.com>',
-        EmailAddress(u'"foo – bar"', 'foo@example.com'),
-        '"=?utf-8?b?Zm9vIOKAkyBiYXI=?=" <foo@example.com>')
+        EmailAddress(u'foo – bar', 'foo@example.com'),
+        '=?utf-8?b?Zm9vIOKAkyBiYXI=?= <foo@example.com>')
     run_full_mailbox_test(u'"foo Ǽ bar" <foo@example.com>',
-        EmailAddress(u'"foo Ǽ bar"', u'foo@example.com'),
-        '"=?utf-8?q?foo_=C7=BC_bar?=" <foo@example.com>')
+        EmailAddress(u'foo Ǽ bar', u'foo@example.com'),
+        '=?utf-8?q?foo_=C7=BC_bar?= <foo@example.com>')
     run_full_mailbox_test(u'"foo Ω bar" <foo@example.com>',
-        EmailAddress(u'"foo Ω bar"', u'foo@example.com'),
-        '"=?utf-8?b?Zm9vIOKEpiBiYXI=?=" <foo@example.com>')
+        EmailAddress(u'foo Ω bar', u'foo@example.com'),
+        '=?utf-8?b?Zm9vIOKEpiBiYXI=?= <foo@example.com>')
     run_full_mailbox_test(u'"foo ↵ bar" <foo@example.com>',
-        EmailAddress(u'"foo ↵ bar"', u'foo@example.com'),
-        '"=?utf-8?b?Zm9vIOKGtSBiYXI=?=" <foo@example.com>')
+        EmailAddress(u'foo ↵ bar', u'foo@example.com'),
+        '=?utf-8?b?Zm9vIOKGtSBiYXI=?= <foo@example.com>')
     run_full_mailbox_test(u'"foo ∑ bar" <foo@example.com>',
-        EmailAddress(u'"foo ∑ bar"', u'foo@example.com'),
-        '"=?utf-8?b?Zm9vIOKIkSBiYXI=?=" <foo@example.com>')
+        EmailAddress(u'foo ∑ bar', u'foo@example.com'),
+        '=?utf-8?b?Zm9vIOKIkSBiYXI=?= <foo@example.com>')
     run_full_mailbox_test(u'"foo ⏲ bar" <foo@example.com>',
-        EmailAddress(u'"foo ⏲ bar"', u'foo@example.com'),
-        '"=?utf-8?b?Zm9vIOKPsiBiYXI=?=" <foo@example.com>')
+        EmailAddress(u'foo ⏲ bar', u'foo@example.com'),
+        '=?utf-8?b?Zm9vIOKPsiBiYXI=?= <foo@example.com>')
     run_full_mailbox_test(u'"foo Ⓐ bar" <foo@example.com>',
-        EmailAddress(u'"foo Ⓐ bar"', u'foo@example.com'),
-        '"=?utf-8?b?Zm9vIOKStiBiYXI=?=" <foo@example.com>')
+        EmailAddress(u'foo Ⓐ bar', u'foo@example.com'),
+        '=?utf-8?b?Zm9vIOKStiBiYXI=?= <foo@example.com>')
     run_full_mailbox_test(u'"foo ▒ bar" <foo@example.com>',
-        EmailAddress(u'"foo ▒ bar"', u'foo@example.com'),
-        '"=?utf-8?b?Zm9vIOKWkiBiYXI=?=" <foo@example.com>')
+        EmailAddress(u'foo ▒ bar', u'foo@example.com'),
+        '=?utf-8?b?Zm9vIOKWkiBiYXI=?= <foo@example.com>')
     run_full_mailbox_test(u'"foo ▲ bar" <foo@example.com>',
-        EmailAddress(u'"foo ▲ bar"', u'foo@example.com'),
-        '"=?utf-8?b?Zm9vIOKWsiBiYXI=?=" <foo@example.com>')
+        EmailAddress(u'foo ▲ bar', u'foo@example.com'),
+        '=?utf-8?b?Zm9vIOKWsiBiYXI=?= <foo@example.com>')
     run_full_mailbox_test(u'"foo ⚔ bar" <foo@example.com>',
-        EmailAddress(u'"foo ⚔ bar"', u'foo@example.com'),
-        '"=?utf-8?b?Zm9vIOKalCBiYXI=?=" <foo@example.com>')
+        EmailAddress(u'foo ⚔ bar', u'foo@example.com'),
+        '=?utf-8?b?Zm9vIOKalCBiYXI=?= <foo@example.com>')
     run_full_mailbox_test(u'"foo ✎ bar" <foo@example.com>',
-        EmailAddress(u'"foo ✎ bar"', u'foo@example.com'),
-        '"=?utf-8?b?Zm9vIOKcjiBiYXI=?=" <foo@example.com>')
+        EmailAddress(u'foo ✎ bar', u'foo@example.com'),
+        '=?utf-8?b?Zm9vIOKcjiBiYXI=?= <foo@example.com>')
     run_full_mailbox_test(u'"foo ⠂ bar" <foo@example.com>',
-        EmailAddress(u'"foo ⠂ bar"', u'foo@example.com'),
-        '"=?utf-8?b?Zm9vIOKggiBiYXI=?=" <foo@example.com>')
+        EmailAddress(u'foo ⠂ bar', u'foo@example.com'),
+        '=?utf-8?b?Zm9vIOKggiBiYXI=?= <foo@example.com>')
     run_full_mailbox_test(u'"foo ⬀ bar" <foo@example.com>',
-        EmailAddress(u'"foo ⬀ bar"', u'foo@example.com'),
-        '"=?utf-8?b?Zm9vIOKsgCBiYXI=?=" <foo@example.com>')
+        EmailAddress(u'foo ⬀ bar', u'foo@example.com'),
+        '=?utf-8?b?Zm9vIOKsgCBiYXI=?= <foo@example.com>')
     run_full_mailbox_test(u'"foo 💩 bar" <foo@example.com>',
-        EmailAddress(u'"foo 💩 bar"', u'foo@example.com'),
-        '"=?utf-8?b?Zm9vIPCfkqkgYmFy?=" <foo@example.com>')
+        EmailAddress(u'foo 💩 bar', u'foo@example.com'),
+        '=?utf-8?b?Zm9vIPCfkqkgYmFy?= <foo@example.com>')
 
     # unicode, language specific punctuation, just test with !
     run_full_mailbox_test(u'fooǃ foo@example.com',
@@ -410,10 +443,9 @@ def test_unicode_special_chars():
         EmailAddress(u'foo᥄', u'foo@example.com'),
         '=?utf-8?b?Zm9v4aWE?= <foo@example.com>')
 
-    # allow the following characters ()[]@\: unquoted because they are used so often
-    run_full_mailbox_test(u'foo ()[]@\: bar <foo@example.com>',
-        EmailAddress(u'foo ()[]@\: bar', u'foo@example.com'),
-        'foo ()[]@\\: bar <foo@example.com>')
+    run_full_mailbox_test(u'foo ()[]@\\ bar <foo@example.com>',
+        EmailAddress(u'foo ()[]@\\ bar', u'foo@example.com'),
+        '"foo ()[]@\\\\ bar" <foo@example.com>')
 
 
 def test_angle_addr():
@@ -475,6 +507,7 @@ def test_local_part():
     # we use a sample in testing, every other for qtext and every fifth for quoted-pair
     sample_qtext = FULL_QTEXT[::2]
     sample_qpair = FULL_QUOTED_PAIR[::5]
+    sample_qpair_without_slashes = sample_qpair[1::2]
 
     # pass dot-atom
     run_mailbox_test('ABCDEFGHIJKLMNOPQRSTUVWXYZ@apple.com', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ@apple.com')
@@ -504,7 +537,7 @@ def test_local_part():
     run_mailbox_test('"{0} "@b'.format(sample_qtext), '"{0} "@b'.format(sample_qtext))
     run_mailbox_test('" {0} "@b'.format(sample_qtext), '" {0} "@b'.format(sample_qtext))
     run_full_mailbox_test('"{0}" "{0}"@b'.format(sample_qtext),
-        EmailAddress('"{0}"'.format(sample_qtext), '"{0}"@b'.format(sample_qtext)))
+        EmailAddress(sample_qtext, '"{0}"@b'.format(sample_qtext)))
 
     # fail qtext
     run_mailbox_test('"{0}""{0}"@b'.format(sample_qtext), None)
@@ -523,7 +556,7 @@ def test_local_part():
     run_mailbox_test('"{0} "@b'.format(sample_qpair), '"{0} "@b'.format(sample_qpair))
     run_mailbox_test('" {0} "@b'.format(sample_qpair), '" {0} "@b'.format(sample_qpair))
     run_full_mailbox_test('"{0}" "{0}"@b'.format(sample_qpair),
-        EmailAddress('"{0}"'.format(sample_qpair), '"{0}"@b'.format(sample_qpair)))
+        EmailAddress(sample_qpair_without_slashes, '"{0}"@b'.format(sample_qpair)))
 
     # fail quoted-pair
     run_mailbox_test('"{0}""{0}"@b'.format(sample_qpair), None)
diff --git a/tests/addresslib/quote_test.py b/tests/addresslib/quote_test.py
new file mode 100644 (file)
index 0000000..cc9e61b
--- /dev/null
@@ -0,0 +1,52 @@
+# coding=utf-8
+from nose.tools import eq_
+from flanker.addresslib.quote import smart_quote, smart_unquote
+
+
+def test_quote():
+    eq_('"foo, bar"', smart_quote('foo, bar'))
+    eq_('"foo; bar"', smart_quote('foo; bar'))
+    eq_('"foo< bar"', smart_quote('foo< bar'))
+    eq_('"foo> bar"', smart_quote('foo> bar'))
+    eq_('"foo\\" bar"', smart_quote('foo" bar'))
+    eq_('"foo. bar"', smart_quote('foo. bar'))
+    eq_('"foo: bar"', smart_quote('foo: bar'))
+
+
+def test_quote__spaces():
+    eq_('foo bar', smart_quote('foo bar'))
+    eq_('" foo bar"', smart_quote(' foo bar'))
+    eq_('"foo bar "', smart_quote('foo bar '))
+    eq_('" foo bar "', smart_quote(' foo bar '))
+    eq_('foo\tbar', smart_quote('foo\tbar'))
+    eq_('"\tfoo\tbar"', smart_quote('\tfoo\tbar'))
+    eq_('"foo\tbar\t"', smart_quote('foo\tbar\t'))
+    eq_('"\tfoo\tbar\t"', smart_quote('\tfoo\tbar\t'))
+
+
+def test_quote__escaping():
+    eq_('"f\\\\o\\"o \\"bar\\""', smart_quote('f\\o"o "bar"'))
+    eq_('"\\"foo\\""', smart_quote('"foo"'))
+    eq_('"\\"foo\\"bar\\""', smart_quote('"foo"bar"'))
+
+
+def test_quote__nothing_to_quote():
+    eq_('', smart_quote(''))
+    eq_('foo bar', smart_quote('foo bar'))
+    eq_("!#$%&'*+-/=?^_`{|}~",
+        smart_quote("!#$%&'*+-/=?^_`{|}~"))
+
+
+def test_unquote():
+    eq_('foo bar "(bazz)" blah oops',
+        smart_unquote('foo "bar \\"(bazz)\\" blah" oops'))
+    eq_('foo;  bar. \\bazz\\', smart_unquote('"foo;"  "bar." "\\\\bazz\\\\"'))
+    eq_('"foo"bar"', smart_unquote('"\\"foo\\"bar\\"'))
+
+
+def test_unquote__nothing_to_unquote():
+    eq_('foo\\.;\tbar', smart_unquote('foo\\.;\tbar'))
+
+
+def test_unquote__unicode():
+    eq_(u'Превед Медвед', smart_unquote(u'Превед Медвед'))