PageRenderTime 54ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/test/test_smtplib.py

https://bitbucket.org/dac_io/pypy
Python | 518 lines | 414 code | 61 blank | 43 comment | 34 complexity | 96ee8d5b42115abe20ab74bc29775e50 MD5 | raw file
  1. import asyncore
  2. import email.utils
  3. import socket
  4. import smtpd
  5. import smtplib
  6. import StringIO
  7. import sys
  8. import time
  9. import select
  10. import unittest
  11. from test import test_support
  12. try:
  13. import threading
  14. except ImportError:
  15. threading = None
  16. HOST = test_support.HOST
  17. def server(evt, buf, serv):
  18. serv.listen(5)
  19. evt.set()
  20. try:
  21. conn, addr = serv.accept()
  22. except socket.timeout:
  23. pass
  24. else:
  25. n = 500
  26. while buf and n > 0:
  27. r, w, e = select.select([], [conn], [])
  28. if w:
  29. sent = conn.send(buf)
  30. buf = buf[sent:]
  31. n -= 1
  32. conn.close()
  33. finally:
  34. serv.close()
  35. evt.set()
  36. @unittest.skipUnless(threading, 'Threading required for this test.')
  37. class GeneralTests(unittest.TestCase):
  38. def setUp(self):
  39. self._threads = test_support.threading_setup()
  40. self.evt = threading.Event()
  41. self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  42. self.sock.settimeout(15)
  43. self.port = test_support.bind_port(self.sock)
  44. servargs = (self.evt, "220 Hola mundo\n", self.sock)
  45. self.thread = threading.Thread(target=server, args=servargs)
  46. self.thread.start()
  47. self.evt.wait()
  48. self.evt.clear()
  49. def tearDown(self):
  50. self.evt.wait()
  51. self.thread.join()
  52. test_support.threading_cleanup(*self._threads)
  53. def testBasic1(self):
  54. # connects
  55. smtp = smtplib.SMTP(HOST, self.port)
  56. smtp.close()
  57. def testBasic2(self):
  58. # connects, include port in host name
  59. smtp = smtplib.SMTP("%s:%s" % (HOST, self.port))
  60. smtp.close()
  61. def testLocalHostName(self):
  62. # check that supplied local_hostname is used
  63. smtp = smtplib.SMTP(HOST, self.port, local_hostname="testhost")
  64. self.assertEqual(smtp.local_hostname, "testhost")
  65. smtp.close()
  66. def testTimeoutDefault(self):
  67. self.assertTrue(socket.getdefaulttimeout() is None)
  68. socket.setdefaulttimeout(30)
  69. try:
  70. smtp = smtplib.SMTP(HOST, self.port)
  71. finally:
  72. socket.setdefaulttimeout(None)
  73. self.assertEqual(smtp.sock.gettimeout(), 30)
  74. smtp.close()
  75. def testTimeoutNone(self):
  76. self.assertTrue(socket.getdefaulttimeout() is None)
  77. socket.setdefaulttimeout(30)
  78. try:
  79. smtp = smtplib.SMTP(HOST, self.port, timeout=None)
  80. finally:
  81. socket.setdefaulttimeout(None)
  82. self.assertTrue(smtp.sock.gettimeout() is None)
  83. smtp.close()
  84. def testTimeoutValue(self):
  85. smtp = smtplib.SMTP(HOST, self.port, timeout=30)
  86. self.assertEqual(smtp.sock.gettimeout(), 30)
  87. smtp.close()
  88. # Test server thread using the specified SMTP server class
  89. def debugging_server(serv, serv_evt, client_evt):
  90. serv_evt.set()
  91. try:
  92. if hasattr(select, 'poll'):
  93. poll_fun = asyncore.poll2
  94. else:
  95. poll_fun = asyncore.poll
  96. n = 1000
  97. while asyncore.socket_map and n > 0:
  98. poll_fun(0.01, asyncore.socket_map)
  99. # when the client conversation is finished, it will
  100. # set client_evt, and it's then ok to kill the server
  101. if client_evt.is_set():
  102. serv.close()
  103. break
  104. n -= 1
  105. except socket.timeout:
  106. pass
  107. finally:
  108. if not client_evt.is_set():
  109. # allow some time for the client to read the result
  110. time.sleep(0.5)
  111. serv.close()
  112. asyncore.close_all()
  113. serv_evt.set()
  114. MSG_BEGIN = '---------- MESSAGE FOLLOWS ----------\n'
  115. MSG_END = '------------ END MESSAGE ------------\n'
  116. # NOTE: Some SMTP objects in the tests below are created with a non-default
  117. # local_hostname argument to the constructor, since (on some systems) the FQDN
  118. # lookup caused by the default local_hostname sometimes takes so long that the
  119. # test server times out, causing the test to fail.
  120. # Test behavior of smtpd.DebuggingServer
  121. @unittest.skipUnless(threading, 'Threading required for this test.')
  122. class DebuggingServerTests(unittest.TestCase):
  123. def setUp(self):
  124. # temporarily replace sys.stdout to capture DebuggingServer output
  125. self.old_stdout = sys.stdout
  126. self.output = StringIO.StringIO()
  127. sys.stdout = self.output
  128. self._threads = test_support.threading_setup()
  129. self.serv_evt = threading.Event()
  130. self.client_evt = threading.Event()
  131. # Pick a random unused port by passing 0 for the port number
  132. self.serv = smtpd.DebuggingServer((HOST, 0), ('nowhere', -1))
  133. # Keep a note of what port was assigned
  134. self.port = self.serv.socket.getsockname()[1]
  135. serv_args = (self.serv, self.serv_evt, self.client_evt)
  136. self.thread = threading.Thread(target=debugging_server, args=serv_args)
  137. self.thread.start()
  138. # wait until server thread has assigned a port number
  139. self.serv_evt.wait()
  140. self.serv_evt.clear()
  141. def tearDown(self):
  142. # indicate that the client is finished
  143. self.client_evt.set()
  144. # wait for the server thread to terminate
  145. self.serv_evt.wait()
  146. self.thread.join()
  147. test_support.threading_cleanup(*self._threads)
  148. # restore sys.stdout
  149. sys.stdout = self.old_stdout
  150. def testBasic(self):
  151. # connect
  152. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
  153. smtp.quit()
  154. def testNOOP(self):
  155. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
  156. expected = (250, 'Ok')
  157. self.assertEqual(smtp.noop(), expected)
  158. smtp.quit()
  159. def testRSET(self):
  160. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
  161. expected = (250, 'Ok')
  162. self.assertEqual(smtp.rset(), expected)
  163. smtp.quit()
  164. def testNotImplemented(self):
  165. # EHLO isn't implemented in DebuggingServer
  166. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
  167. expected = (502, 'Error: command "EHLO" not implemented')
  168. self.assertEqual(smtp.ehlo(), expected)
  169. smtp.quit()
  170. def testVRFY(self):
  171. # VRFY isn't implemented in DebuggingServer
  172. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
  173. expected = (502, 'Error: command "VRFY" not implemented')
  174. self.assertEqual(smtp.vrfy('nobody@nowhere.com'), expected)
  175. self.assertEqual(smtp.verify('nobody@nowhere.com'), expected)
  176. smtp.quit()
  177. def testSecondHELO(self):
  178. # check that a second HELO returns a message that it's a duplicate
  179. # (this behavior is specific to smtpd.SMTPChannel)
  180. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
  181. smtp.helo()
  182. expected = (503, 'Duplicate HELO/EHLO')
  183. self.assertEqual(smtp.helo(), expected)
  184. smtp.quit()
  185. def testHELP(self):
  186. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
  187. self.assertEqual(smtp.help(), 'Error: command "HELP" not implemented')
  188. smtp.quit()
  189. def testSend(self):
  190. # connect and send mail
  191. m = 'A test message'
  192. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=3)
  193. smtp.sendmail('John', 'Sally', m)
  194. # XXX(nnorwitz): this test is flaky and dies with a bad file descriptor
  195. # in asyncore. This sleep might help, but should really be fixed
  196. # properly by using an Event variable.
  197. time.sleep(0.01)
  198. smtp.quit()
  199. self.client_evt.set()
  200. self.serv_evt.wait()
  201. self.output.flush()
  202. mexpect = '%s%s\n%s' % (MSG_BEGIN, m, MSG_END)
  203. self.assertEqual(self.output.getvalue(), mexpect)
  204. class NonConnectingTests(unittest.TestCase):
  205. def testNotConnected(self):
  206. # Test various operations on an unconnected SMTP object that
  207. # should raise exceptions (at present the attempt in SMTP.send
  208. # to reference the nonexistent 'sock' attribute of the SMTP object
  209. # causes an AttributeError)
  210. smtp = smtplib.SMTP()
  211. self.assertRaises(smtplib.SMTPServerDisconnected, smtp.ehlo)
  212. self.assertRaises(smtplib.SMTPServerDisconnected,
  213. smtp.send, 'test msg')
  214. def testNonnumericPort(self):
  215. # check that non-numeric port raises socket.error
  216. self.assertRaises(socket.error, smtplib.SMTP,
  217. "localhost", "bogus")
  218. self.assertRaises(socket.error, smtplib.SMTP,
  219. "localhost:bogus")
  220. # test response of client to a non-successful HELO message
  221. @unittest.skipUnless(threading, 'Threading required for this test.')
  222. class BadHELOServerTests(unittest.TestCase):
  223. def setUp(self):
  224. self.old_stdout = sys.stdout
  225. self.output = StringIO.StringIO()
  226. sys.stdout = self.output
  227. self._threads = test_support.threading_setup()
  228. self.evt = threading.Event()
  229. self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  230. self.sock.settimeout(15)
  231. self.port = test_support.bind_port(self.sock)
  232. servargs = (self.evt, "199 no hello for you!\n", self.sock)
  233. self.thread = threading.Thread(target=server, args=servargs)
  234. self.thread.start()
  235. self.evt.wait()
  236. self.evt.clear()
  237. def tearDown(self):
  238. self.evt.wait()
  239. self.thread.join()
  240. test_support.threading_cleanup(*self._threads)
  241. sys.stdout = self.old_stdout
  242. def testFailingHELO(self):
  243. self.assertRaises(smtplib.SMTPConnectError, smtplib.SMTP,
  244. HOST, self.port, 'localhost', 3)
  245. sim_users = {'Mr.A@somewhere.com':'John A',
  246. 'Ms.B@somewhere.com':'Sally B',
  247. 'Mrs.C@somewhereesle.com':'Ruth C',
  248. }
  249. sim_auth = ('Mr.A@somewhere.com', 'somepassword')
  250. sim_cram_md5_challenge = ('PENCeUxFREJoU0NnbmhNWitOMjNGNn'
  251. 'dAZWx3b29kLmlubm9zb2Z0LmNvbT4=')
  252. sim_auth_credentials = {
  253. 'login': 'TXIuQUBzb21ld2hlcmUuY29t',
  254. 'plain': 'AE1yLkFAc29tZXdoZXJlLmNvbQBzb21lcGFzc3dvcmQ=',
  255. 'cram-md5': ('TXIUQUBZB21LD2HLCMUUY29TIDG4OWQ0MJ'
  256. 'KWZGQ4ODNMNDA4NTGXMDRLZWMYZJDMODG1'),
  257. }
  258. sim_auth_login_password = 'C29TZXBHC3N3B3JK'
  259. sim_lists = {'list-1':['Mr.A@somewhere.com','Mrs.C@somewhereesle.com'],
  260. 'list-2':['Ms.B@somewhere.com',],
  261. }
  262. # Simulated SMTP channel & server
  263. class SimSMTPChannel(smtpd.SMTPChannel):
  264. def __init__(self, extra_features, *args, **kw):
  265. self._extrafeatures = ''.join(
  266. [ "250-{0}\r\n".format(x) for x in extra_features ])
  267. smtpd.SMTPChannel.__init__(self, *args, **kw)
  268. def smtp_EHLO(self, arg):
  269. resp = ('250-testhost\r\n'
  270. '250-EXPN\r\n'
  271. '250-SIZE 20000000\r\n'
  272. '250-STARTTLS\r\n'
  273. '250-DELIVERBY\r\n')
  274. resp = resp + self._extrafeatures + '250 HELP'
  275. self.push(resp)
  276. def smtp_VRFY(self, arg):
  277. raw_addr = email.utils.parseaddr(arg)[1]
  278. quoted_addr = smtplib.quoteaddr(arg)
  279. if raw_addr in sim_users:
  280. self.push('250 %s %s' % (sim_users[raw_addr], quoted_addr))
  281. else:
  282. self.push('550 No such user: %s' % arg)
  283. def smtp_EXPN(self, arg):
  284. list_name = email.utils.parseaddr(arg)[1].lower()
  285. if list_name in sim_lists:
  286. user_list = sim_lists[list_name]
  287. for n, user_email in enumerate(user_list):
  288. quoted_addr = smtplib.quoteaddr(user_email)
  289. if n < len(user_list) - 1:
  290. self.push('250-%s %s' % (sim_users[user_email], quoted_addr))
  291. else:
  292. self.push('250 %s %s' % (sim_users[user_email], quoted_addr))
  293. else:
  294. self.push('550 No access for you!')
  295. def smtp_AUTH(self, arg):
  296. if arg.strip().lower()=='cram-md5':
  297. self.push('334 {0}'.format(sim_cram_md5_challenge))
  298. return
  299. mech, auth = arg.split()
  300. mech = mech.lower()
  301. if mech not in sim_auth_credentials:
  302. self.push('504 auth type unimplemented')
  303. return
  304. if mech == 'plain' and auth==sim_auth_credentials['plain']:
  305. self.push('235 plain auth ok')
  306. elif mech=='login' and auth==sim_auth_credentials['login']:
  307. self.push('334 Password:')
  308. else:
  309. self.push('550 No access for you!')
  310. def handle_error(self):
  311. raise
  312. class SimSMTPServer(smtpd.SMTPServer):
  313. def __init__(self, *args, **kw):
  314. self._extra_features = []
  315. smtpd.SMTPServer.__init__(self, *args, **kw)
  316. def handle_accept(self):
  317. conn, addr = self.accept()
  318. self._SMTPchannel = SimSMTPChannel(self._extra_features,
  319. self, conn, addr)
  320. def process_message(self, peer, mailfrom, rcpttos, data):
  321. pass
  322. def add_feature(self, feature):
  323. self._extra_features.append(feature)
  324. def handle_error(self):
  325. raise
  326. # Test various SMTP & ESMTP commands/behaviors that require a simulated server
  327. # (i.e., something with more features than DebuggingServer)
  328. @unittest.skipUnless(threading, 'Threading required for this test.')
  329. class SMTPSimTests(unittest.TestCase):
  330. def setUp(self):
  331. self._threads = test_support.threading_setup()
  332. self.serv_evt = threading.Event()
  333. self.client_evt = threading.Event()
  334. # Pick a random unused port by passing 0 for the port number
  335. self.serv = SimSMTPServer((HOST, 0), ('nowhere', -1))
  336. # Keep a note of what port was assigned
  337. self.port = self.serv.socket.getsockname()[1]
  338. serv_args = (self.serv, self.serv_evt, self.client_evt)
  339. self.thread = threading.Thread(target=debugging_server, args=serv_args)
  340. self.thread.start()
  341. # wait until server thread has assigned a port number
  342. self.serv_evt.wait()
  343. self.serv_evt.clear()
  344. def tearDown(self):
  345. # indicate that the client is finished
  346. self.client_evt.set()
  347. # wait for the server thread to terminate
  348. self.serv_evt.wait()
  349. self.thread.join()
  350. test_support.threading_cleanup(*self._threads)
  351. def testBasic(self):
  352. # smoke test
  353. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
  354. smtp.quit()
  355. def testEHLO(self):
  356. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
  357. # no features should be present before the EHLO
  358. self.assertEqual(smtp.esmtp_features, {})
  359. # features expected from the test server
  360. expected_features = {'expn':'',
  361. 'size': '20000000',
  362. 'starttls': '',
  363. 'deliverby': '',
  364. 'help': '',
  365. }
  366. smtp.ehlo()
  367. self.assertEqual(smtp.esmtp_features, expected_features)
  368. for k in expected_features:
  369. self.assertTrue(smtp.has_extn(k))
  370. self.assertFalse(smtp.has_extn('unsupported-feature'))
  371. smtp.quit()
  372. def testVRFY(self):
  373. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
  374. for email, name in sim_users.items():
  375. expected_known = (250, '%s %s' % (name, smtplib.quoteaddr(email)))
  376. self.assertEqual(smtp.vrfy(email), expected_known)
  377. u = 'nobody@nowhere.com'
  378. expected_unknown = (550, 'No such user: %s' % smtplib.quoteaddr(u))
  379. self.assertEqual(smtp.vrfy(u), expected_unknown)
  380. smtp.quit()
  381. def testEXPN(self):
  382. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
  383. for listname, members in sim_lists.items():
  384. users = []
  385. for m in members:
  386. users.append('%s %s' % (sim_users[m], smtplib.quoteaddr(m)))
  387. expected_known = (250, '\n'.join(users))
  388. self.assertEqual(smtp.expn(listname), expected_known)
  389. u = 'PSU-Members-List'
  390. expected_unknown = (550, 'No access for you!')
  391. self.assertEqual(smtp.expn(u), expected_unknown)
  392. smtp.quit()
  393. def testAUTH_PLAIN(self):
  394. self.serv.add_feature("AUTH PLAIN")
  395. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
  396. expected_auth_ok = (235, b'plain auth ok')
  397. self.assertEqual(smtp.login(sim_auth[0], sim_auth[1]), expected_auth_ok)
  398. # SimSMTPChannel doesn't fully support LOGIN or CRAM-MD5 auth because they
  399. # require a synchronous read to obtain the credentials...so instead smtpd
  400. # sees the credential sent by smtplib's login method as an unknown command,
  401. # which results in smtplib raising an auth error. Fortunately the error
  402. # message contains the encoded credential, so we can partially check that it
  403. # was generated correctly (partially, because the 'word' is uppercased in
  404. # the error message).
  405. def testAUTH_LOGIN(self):
  406. self.serv.add_feature("AUTH LOGIN")
  407. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
  408. try: smtp.login(sim_auth[0], sim_auth[1])
  409. except smtplib.SMTPAuthenticationError as err:
  410. if sim_auth_login_password not in str(err):
  411. raise "expected encoded password not found in error message"
  412. def testAUTH_CRAM_MD5(self):
  413. self.serv.add_feature("AUTH CRAM-MD5")
  414. smtp = smtplib.SMTP(HOST, self.port, local_hostname='localhost', timeout=15)
  415. try: smtp.login(sim_auth[0], sim_auth[1])
  416. except smtplib.SMTPAuthenticationError as err:
  417. if sim_auth_credentials['cram-md5'] not in str(err):
  418. raise "expected encoded credentials not found in error message"
  419. #TODO: add tests for correct AUTH method fallback now that the
  420. #test infrastructure can support it.
  421. def test_main(verbose=None):
  422. test_support.run_unittest(GeneralTests, DebuggingServerTests,
  423. NonConnectingTests,
  424. BadHELOServerTests, SMTPSimTests)
  425. if __name__ == '__main__':
  426. test_main()