From 7b313971805ca9b53f181f7b97e5376d0b89dc06 Mon Sep 17 00:00:00 2001 From: Romuald Brunet Date: Tue, 9 Oct 2018 16:31:55 +0200 Subject: [PATCH] bpo-32680 add default "sock" on SMTP objects (#5345) By default the smtplib.SMTP objects did not have a sock attribute, it was only created during connect() --- Lib/smtplib.py | 4 +++- Lib/test/test_smtplib.py | 7 +++++++ .../next/Library/2018-10-09-14-25-36.bpo-32680.z2FbOp.rst | 1 + 3 files changed, 11 insertions(+), 1 deletion(-) create mode 100644 Misc/NEWS.d/next/Library/2018-10-09-14-25-36.bpo-32680.z2FbOp.rst diff --git a/Lib/smtplib.py b/Lib/smtplib.py index 5e1bc0b198e..acfc3586e1c 100755 --- a/Lib/smtplib.py +++ b/Lib/smtplib.py @@ -216,6 +216,8 @@ class SMTP: method called 'sendmail' that will do an entire mail transaction. """ debuglevel = 0 + + sock = None file = None helo_resp = None ehlo_msg = "ehlo" @@ -344,7 +346,7 @@ class SMTP: """Send `s' to the server.""" if self.debuglevel > 0: self._print_debug('send:', repr(s)) - if hasattr(self, 'sock') and self.sock: + if self.sock: if isinstance(s, str): # send is used by the 'data' command, where command_encoding # should not be used, but 'data' needs to convert the string to diff --git a/Lib/test/test_smtplib.py b/Lib/test/test_smtplib.py index 0c863ed7e20..07d760bd01f 100644 --- a/Lib/test/test_smtplib.py +++ b/Lib/test/test_smtplib.py @@ -602,6 +602,13 @@ class NonConnectingTests(unittest.TestCase): self.assertRaises(OSError, smtplib.SMTP, "localhost:bogus") + def testSockAttributeExists(self): + # check that sock attribute is present outside of a connect() call + # (regression test, the previous behavior raised an + # AttributeError: 'SMTP' object has no attribute 'sock') + with smtplib.SMTP() as smtp: + self.assertIsNone(smtp.sock) + class DefaultArgumentsTests(unittest.TestCase): diff --git a/Misc/NEWS.d/next/Library/2018-10-09-14-25-36.bpo-32680.z2FbOp.rst b/Misc/NEWS.d/next/Library/2018-10-09-14-25-36.bpo-32680.z2FbOp.rst new file mode 100644 index 00000000000..afe16b627c8 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2018-10-09-14-25-36.bpo-32680.z2FbOp.rst @@ -0,0 +1 @@ +:class:`smtplib.SMTP` objects now always have a `sock` attribute present