PageRenderTime 55ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/External.LCA_RESTRICTED/Languages/IronPython/27/Lib/test/test_httplib.py

http://github.com/IronLanguages/main
Python | 878 lines | 863 code | 6 blank | 9 comment | 6 complexity | db5e77a3bc62bc0f5df61589c2dae34f MD5 | raw file
Possible License(s): CPL-1.0, BSD-3-Clause, ISC, GPL-2.0, MPL-2.0-no-copyleft-exception
  1. import httplib
  2. import itertools
  3. import array
  4. import StringIO
  5. import socket
  6. import errno
  7. import os
  8. import tempfile
  9. import unittest
  10. TestCase = unittest.TestCase
  11. from test import test_support
  12. here = os.path.dirname(__file__)
  13. # Self-signed cert file for 'localhost'
  14. CERT_localhost = os.path.join(here, 'keycert.pem')
  15. # Self-signed cert file for 'fakehostname'
  16. CERT_fakehostname = os.path.join(here, 'keycert2.pem')
  17. # Self-signed cert file for self-signed.pythontest.net
  18. CERT_selfsigned_pythontestdotnet = os.path.join(here, 'selfsigned_pythontestdotnet.pem')
  19. HOST = test_support.HOST
  20. class FakeSocket:
  21. def __init__(self, text, fileclass=StringIO.StringIO, host=None, port=None):
  22. self.text = text
  23. self.fileclass = fileclass
  24. self.data = ''
  25. self.file_closed = False
  26. self.host = host
  27. self.port = port
  28. def sendall(self, data):
  29. self.data += ''.join(data)
  30. def makefile(self, mode, bufsize=None):
  31. if mode != 'r' and mode != 'rb':
  32. raise httplib.UnimplementedFileMode()
  33. # keep the file around so we can check how much was read from it
  34. self.file = self.fileclass(self.text)
  35. self.file.close = self.file_close #nerf close ()
  36. return self.file
  37. def file_close(self):
  38. self.file_closed = True
  39. def close(self):
  40. pass
  41. class EPipeSocket(FakeSocket):
  42. def __init__(self, text, pipe_trigger):
  43. # When sendall() is called with pipe_trigger, raise EPIPE.
  44. FakeSocket.__init__(self, text)
  45. self.pipe_trigger = pipe_trigger
  46. def sendall(self, data):
  47. if self.pipe_trigger in data:
  48. raise socket.error(errno.EPIPE, "gotcha")
  49. self.data += data
  50. def close(self):
  51. pass
  52. class NoEOFStringIO(StringIO.StringIO):
  53. """Like StringIO, but raises AssertionError on EOF.
  54. This is used below to test that httplib doesn't try to read
  55. more from the underlying file than it should.
  56. """
  57. def read(self, n=-1):
  58. data = StringIO.StringIO.read(self, n)
  59. if data == '':
  60. raise AssertionError('caller tried to read past EOF')
  61. return data
  62. def readline(self, length=None):
  63. data = StringIO.StringIO.readline(self, length)
  64. if data == '':
  65. raise AssertionError('caller tried to read past EOF')
  66. return data
  67. class HeaderTests(TestCase):
  68. def test_auto_headers(self):
  69. # Some headers are added automatically, but should not be added by
  70. # .request() if they are explicitly set.
  71. class HeaderCountingBuffer(list):
  72. def __init__(self):
  73. self.count = {}
  74. def append(self, item):
  75. kv = item.split(':')
  76. if len(kv) > 1:
  77. # item is a 'Key: Value' header string
  78. lcKey = kv[0].lower()
  79. self.count.setdefault(lcKey, 0)
  80. self.count[lcKey] += 1
  81. list.append(self, item)
  82. for explicit_header in True, False:
  83. for header in 'Content-length', 'Host', 'Accept-encoding':
  84. conn = httplib.HTTPConnection('example.com')
  85. conn.sock = FakeSocket('blahblahblah')
  86. conn._buffer = HeaderCountingBuffer()
  87. body = 'spamspamspam'
  88. headers = {}
  89. if explicit_header:
  90. headers[header] = str(len(body))
  91. conn.request('POST', '/', body, headers)
  92. self.assertEqual(conn._buffer.count[header.lower()], 1)
  93. def test_content_length_0(self):
  94. class ContentLengthChecker(list):
  95. def __init__(self):
  96. list.__init__(self)
  97. self.content_length = None
  98. def append(self, item):
  99. kv = item.split(':', 1)
  100. if len(kv) > 1 and kv[0].lower() == 'content-length':
  101. self.content_length = kv[1].strip()
  102. list.append(self, item)
  103. # Here, we're testing that methods expecting a body get a
  104. # content-length set to zero if the body is empty (either None or '')
  105. bodies = (None, '')
  106. methods_with_body = ('PUT', 'POST', 'PATCH')
  107. for method, body in itertools.product(methods_with_body, bodies):
  108. conn = httplib.HTTPConnection('example.com')
  109. conn.sock = FakeSocket(None)
  110. conn._buffer = ContentLengthChecker()
  111. conn.request(method, '/', body)
  112. self.assertEqual(
  113. conn._buffer.content_length, '0',
  114. 'Header Content-Length incorrect on {}'.format(method)
  115. )
  116. # For these methods, we make sure that content-length is not set when
  117. # the body is None because it might cause unexpected behaviour on the
  118. # server.
  119. methods_without_body = (
  120. 'GET', 'CONNECT', 'DELETE', 'HEAD', 'OPTIONS', 'TRACE',
  121. )
  122. for method in methods_without_body:
  123. conn = httplib.HTTPConnection('example.com')
  124. conn.sock = FakeSocket(None)
  125. conn._buffer = ContentLengthChecker()
  126. conn.request(method, '/', None)
  127. self.assertEqual(
  128. conn._buffer.content_length, None,
  129. 'Header Content-Length set for empty body on {}'.format(method)
  130. )
  131. # If the body is set to '', that's considered to be "present but
  132. # empty" rather than "missing", so content length would be set, even
  133. # for methods that don't expect a body.
  134. for method in methods_without_body:
  135. conn = httplib.HTTPConnection('example.com')
  136. conn.sock = FakeSocket(None)
  137. conn._buffer = ContentLengthChecker()
  138. conn.request(method, '/', '')
  139. self.assertEqual(
  140. conn._buffer.content_length, '0',
  141. 'Header Content-Length incorrect on {}'.format(method)
  142. )
  143. # If the body is set, make sure Content-Length is set.
  144. for method in itertools.chain(methods_without_body, methods_with_body):
  145. conn = httplib.HTTPConnection('example.com')
  146. conn.sock = FakeSocket(None)
  147. conn._buffer = ContentLengthChecker()
  148. conn.request(method, '/', ' ')
  149. self.assertEqual(
  150. conn._buffer.content_length, '1',
  151. 'Header Content-Length incorrect on {}'.format(method)
  152. )
  153. def test_putheader(self):
  154. conn = httplib.HTTPConnection('example.com')
  155. conn.sock = FakeSocket(None)
  156. conn.putrequest('GET','/')
  157. conn.putheader('Content-length',42)
  158. self.assertIn('Content-length: 42', conn._buffer)
  159. conn.putheader('Foo', ' bar ')
  160. self.assertIn(b'Foo: bar ', conn._buffer)
  161. conn.putheader('Bar', '\tbaz\t')
  162. self.assertIn(b'Bar: \tbaz\t', conn._buffer)
  163. conn.putheader('Authorization', 'Bearer mytoken')
  164. self.assertIn(b'Authorization: Bearer mytoken', conn._buffer)
  165. conn.putheader('IterHeader', 'IterA', 'IterB')
  166. self.assertIn(b'IterHeader: IterA\r\n\tIterB', conn._buffer)
  167. conn.putheader('LatinHeader', b'\xFF')
  168. self.assertIn(b'LatinHeader: \xFF', conn._buffer)
  169. conn.putheader('Utf8Header', b'\xc3\x80')
  170. self.assertIn(b'Utf8Header: \xc3\x80', conn._buffer)
  171. conn.putheader('C1-Control', b'next\x85line')
  172. self.assertIn(b'C1-Control: next\x85line', conn._buffer)
  173. conn.putheader('Embedded-Fold-Space', 'is\r\n allowed')
  174. self.assertIn(b'Embedded-Fold-Space: is\r\n allowed', conn._buffer)
  175. conn.putheader('Embedded-Fold-Tab', 'is\r\n\tallowed')
  176. self.assertIn(b'Embedded-Fold-Tab: is\r\n\tallowed', conn._buffer)
  177. conn.putheader('Key Space', 'value')
  178. self.assertIn(b'Key Space: value', conn._buffer)
  179. conn.putheader('KeySpace ', 'value')
  180. self.assertIn(b'KeySpace : value', conn._buffer)
  181. conn.putheader(b'Nonbreak\xa0Space', 'value')
  182. self.assertIn(b'Nonbreak\xa0Space: value', conn._buffer)
  183. conn.putheader(b'\xa0NonbreakSpace', 'value')
  184. self.assertIn(b'\xa0NonbreakSpace: value', conn._buffer)
  185. def test_ipv6host_header(self):
  186. # Default host header on IPv6 transaction should be wrapped by [] if
  187. # it is an IPv6 address
  188. expected = 'GET /foo HTTP/1.1\r\nHost: [2001::]:81\r\n' \
  189. 'Accept-Encoding: identity\r\n\r\n'
  190. conn = httplib.HTTPConnection('[2001::]:81')
  191. sock = FakeSocket('')
  192. conn.sock = sock
  193. conn.request('GET', '/foo')
  194. self.assertTrue(sock.data.startswith(expected))
  195. expected = 'GET /foo HTTP/1.1\r\nHost: [2001:102A::]\r\n' \
  196. 'Accept-Encoding: identity\r\n\r\n'
  197. conn = httplib.HTTPConnection('[2001:102A::]')
  198. sock = FakeSocket('')
  199. conn.sock = sock
  200. conn.request('GET', '/foo')
  201. self.assertTrue(sock.data.startswith(expected))
  202. def test_malformed_headers_coped_with(self):
  203. # Issue 19996
  204. body = "HTTP/1.1 200 OK\r\nFirst: val\r\n: nval\r\nSecond: val\r\n\r\n"
  205. sock = FakeSocket(body)
  206. resp = httplib.HTTPResponse(sock)
  207. resp.begin()
  208. self.assertEqual(resp.getheader('First'), 'val')
  209. self.assertEqual(resp.getheader('Second'), 'val')
  210. def test_invalid_headers(self):
  211. conn = httplib.HTTPConnection('example.com')
  212. conn.sock = FakeSocket('')
  213. conn.putrequest('GET', '/')
  214. # http://tools.ietf.org/html/rfc7230#section-3.2.4, whitespace is no
  215. # longer allowed in header names
  216. cases = (
  217. (b'Invalid\r\nName', b'ValidValue'),
  218. (b'Invalid\rName', b'ValidValue'),
  219. (b'Invalid\nName', b'ValidValue'),
  220. (b'\r\nInvalidName', b'ValidValue'),
  221. (b'\rInvalidName', b'ValidValue'),
  222. (b'\nInvalidName', b'ValidValue'),
  223. (b' InvalidName', b'ValidValue'),
  224. (b'\tInvalidName', b'ValidValue'),
  225. (b'Invalid:Name', b'ValidValue'),
  226. (b':InvalidName', b'ValidValue'),
  227. (b'ValidName', b'Invalid\r\nValue'),
  228. (b'ValidName', b'Invalid\rValue'),
  229. (b'ValidName', b'Invalid\nValue'),
  230. (b'ValidName', b'InvalidValue\r\n'),
  231. (b'ValidName', b'InvalidValue\r'),
  232. (b'ValidName', b'InvalidValue\n'),
  233. )
  234. for name, value in cases:
  235. with self.assertRaisesRegexp(ValueError, 'Invalid header'):
  236. conn.putheader(name, value)
  237. class BasicTest(TestCase):
  238. def test_status_lines(self):
  239. # Test HTTP status lines
  240. body = "HTTP/1.1 200 Ok\r\n\r\nText"
  241. sock = FakeSocket(body)
  242. resp = httplib.HTTPResponse(sock)
  243. resp.begin()
  244. self.assertEqual(resp.read(0), '') # Issue #20007
  245. self.assertFalse(resp.isclosed())
  246. self.assertEqual(resp.read(), 'Text')
  247. self.assertTrue(resp.isclosed())
  248. body = "HTTP/1.1 400.100 Not Ok\r\n\r\nText"
  249. sock = FakeSocket(body)
  250. resp = httplib.HTTPResponse(sock)
  251. self.assertRaises(httplib.BadStatusLine, resp.begin)
  252. def test_bad_status_repr(self):
  253. exc = httplib.BadStatusLine('')
  254. self.assertEqual(repr(exc), '''BadStatusLine("\'\'",)''')
  255. def test_partial_reads(self):
  256. # if we have a length, the system knows when to close itself
  257. # same behaviour than when we read the whole thing with read()
  258. body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
  259. sock = FakeSocket(body)
  260. resp = httplib.HTTPResponse(sock)
  261. resp.begin()
  262. self.assertEqual(resp.read(2), 'Te')
  263. self.assertFalse(resp.isclosed())
  264. self.assertEqual(resp.read(2), 'xt')
  265. self.assertTrue(resp.isclosed())
  266. def test_partial_reads_no_content_length(self):
  267. # when no length is present, the socket should be gracefully closed when
  268. # all data was read
  269. body = "HTTP/1.1 200 Ok\r\n\r\nText"
  270. sock = FakeSocket(body)
  271. resp = httplib.HTTPResponse(sock)
  272. resp.begin()
  273. self.assertEqual(resp.read(2), 'Te')
  274. self.assertFalse(resp.isclosed())
  275. self.assertEqual(resp.read(2), 'xt')
  276. self.assertEqual(resp.read(1), '')
  277. self.assertTrue(resp.isclosed())
  278. def test_partial_reads_incomplete_body(self):
  279. # if the server shuts down the connection before the whole
  280. # content-length is delivered, the socket is gracefully closed
  281. body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
  282. sock = FakeSocket(body)
  283. resp = httplib.HTTPResponse(sock)
  284. resp.begin()
  285. self.assertEqual(resp.read(2), 'Te')
  286. self.assertFalse(resp.isclosed())
  287. self.assertEqual(resp.read(2), 'xt')
  288. self.assertEqual(resp.read(1), '')
  289. self.assertTrue(resp.isclosed())
  290. def test_host_port(self):
  291. # Check invalid host_port
  292. # Note that httplib does not accept user:password@ in the host-port.
  293. for hp in ("www.python.org:abc", "user:password@www.python.org"):
  294. self.assertRaises(httplib.InvalidURL, httplib.HTTP, hp)
  295. for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000", "fe80::207:e9ff:fe9b",
  296. 8000),
  297. ("www.python.org:80", "www.python.org", 80),
  298. ("www.python.org", "www.python.org", 80),
  299. ("www.python.org:", "www.python.org", 80),
  300. ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 80)):
  301. http = httplib.HTTP(hp)
  302. c = http._conn
  303. if h != c.host:
  304. self.fail("Host incorrectly parsed: %s != %s" % (h, c.host))
  305. if p != c.port:
  306. self.fail("Port incorrectly parsed: %s != %s" % (p, c.host))
  307. def test_response_headers(self):
  308. # test response with multiple message headers with the same field name.
  309. text = ('HTTP/1.1 200 OK\r\n'
  310. 'Set-Cookie: Customer="WILE_E_COYOTE";'
  311. ' Version="1"; Path="/acme"\r\n'
  312. 'Set-Cookie: Part_Number="Rocket_Launcher_0001"; Version="1";'
  313. ' Path="/acme"\r\n'
  314. '\r\n'
  315. 'No body\r\n')
  316. hdr = ('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"'
  317. ', '
  318. 'Part_Number="Rocket_Launcher_0001"; Version="1"; Path="/acme"')
  319. s = FakeSocket(text)
  320. r = httplib.HTTPResponse(s)
  321. r.begin()
  322. cookies = r.getheader("Set-Cookie")
  323. if cookies != hdr:
  324. self.fail("multiple headers not combined properly")
  325. def test_read_head(self):
  326. # Test that the library doesn't attempt to read any data
  327. # from a HEAD request. (Tickles SF bug #622042.)
  328. sock = FakeSocket(
  329. 'HTTP/1.1 200 OK\r\n'
  330. 'Content-Length: 14432\r\n'
  331. '\r\n',
  332. NoEOFStringIO)
  333. resp = httplib.HTTPResponse(sock, method="HEAD")
  334. resp.begin()
  335. if resp.read() != "":
  336. self.fail("Did not expect response from HEAD request")
  337. def test_too_many_headers(self):
  338. headers = '\r\n'.join('Header%d: foo' % i for i in xrange(200)) + '\r\n'
  339. text = ('HTTP/1.1 200 OK\r\n' + headers)
  340. s = FakeSocket(text)
  341. r = httplib.HTTPResponse(s)
  342. self.assertRaises(httplib.HTTPException, r.begin)
  343. def test_send_file(self):
  344. expected = 'GET /foo HTTP/1.1\r\nHost: example.com\r\n' \
  345. 'Accept-Encoding: identity\r\nContent-Length:'
  346. body = open(__file__, 'rb')
  347. conn = httplib.HTTPConnection('example.com')
  348. sock = FakeSocket(body)
  349. conn.sock = sock
  350. conn.request('GET', '/foo', body)
  351. self.assertTrue(sock.data.startswith(expected))
  352. self.assertIn('def test_send_file', sock.data)
  353. def test_send_tempfile(self):
  354. expected = ('GET /foo HTTP/1.1\r\nHost: example.com\r\n'
  355. 'Accept-Encoding: identity\r\nContent-Length: 9\r\n\r\n'
  356. 'fake\ndata')
  357. with tempfile.TemporaryFile() as body:
  358. body.write('fake\ndata')
  359. body.seek(0)
  360. conn = httplib.HTTPConnection('example.com')
  361. sock = FakeSocket(body)
  362. conn.sock = sock
  363. conn.request('GET', '/foo', body)
  364. self.assertEqual(sock.data, expected)
  365. def test_send(self):
  366. expected = 'this is a test this is only a test'
  367. conn = httplib.HTTPConnection('example.com')
  368. sock = FakeSocket(None)
  369. conn.sock = sock
  370. conn.send(expected)
  371. self.assertEqual(expected, sock.data)
  372. sock.data = ''
  373. conn.send(array.array('c', expected))
  374. self.assertEqual(expected, sock.data)
  375. sock.data = ''
  376. conn.send(StringIO.StringIO(expected))
  377. self.assertEqual(expected, sock.data)
  378. def test_chunked(self):
  379. chunked_start = (
  380. 'HTTP/1.1 200 OK\r\n'
  381. 'Transfer-Encoding: chunked\r\n\r\n'
  382. 'a\r\n'
  383. 'hello worl\r\n'
  384. '1\r\n'
  385. 'd\r\n'
  386. )
  387. sock = FakeSocket(chunked_start + '0\r\n')
  388. resp = httplib.HTTPResponse(sock, method="GET")
  389. resp.begin()
  390. self.assertEqual(resp.read(), 'hello world')
  391. resp.close()
  392. for x in ('', 'foo\r\n'):
  393. sock = FakeSocket(chunked_start + x)
  394. resp = httplib.HTTPResponse(sock, method="GET")
  395. resp.begin()
  396. try:
  397. resp.read()
  398. except httplib.IncompleteRead, i:
  399. self.assertEqual(i.partial, 'hello world')
  400. self.assertEqual(repr(i),'IncompleteRead(11 bytes read)')
  401. self.assertEqual(str(i),'IncompleteRead(11 bytes read)')
  402. else:
  403. self.fail('IncompleteRead expected')
  404. finally:
  405. resp.close()
  406. def test_chunked_head(self):
  407. chunked_start = (
  408. 'HTTP/1.1 200 OK\r\n'
  409. 'Transfer-Encoding: chunked\r\n\r\n'
  410. 'a\r\n'
  411. 'hello world\r\n'
  412. '1\r\n'
  413. 'd\r\n'
  414. )
  415. sock = FakeSocket(chunked_start + '0\r\n')
  416. resp = httplib.HTTPResponse(sock, method="HEAD")
  417. resp.begin()
  418. self.assertEqual(resp.read(), '')
  419. self.assertEqual(resp.status, 200)
  420. self.assertEqual(resp.reason, 'OK')
  421. self.assertTrue(resp.isclosed())
  422. def test_negative_content_length(self):
  423. sock = FakeSocket('HTTP/1.1 200 OK\r\n'
  424. 'Content-Length: -1\r\n\r\nHello\r\n')
  425. resp = httplib.HTTPResponse(sock, method="GET")
  426. resp.begin()
  427. self.assertEqual(resp.read(), 'Hello\r\n')
  428. self.assertTrue(resp.isclosed())
  429. def test_incomplete_read(self):
  430. sock = FakeSocket('HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nHello\r\n')
  431. resp = httplib.HTTPResponse(sock, method="GET")
  432. resp.begin()
  433. try:
  434. resp.read()
  435. except httplib.IncompleteRead as i:
  436. self.assertEqual(i.partial, 'Hello\r\n')
  437. self.assertEqual(repr(i),
  438. "IncompleteRead(7 bytes read, 3 more expected)")
  439. self.assertEqual(str(i),
  440. "IncompleteRead(7 bytes read, 3 more expected)")
  441. self.assertTrue(resp.isclosed())
  442. else:
  443. self.fail('IncompleteRead expected')
  444. def test_epipe(self):
  445. sock = EPipeSocket(
  446. "HTTP/1.0 401 Authorization Required\r\n"
  447. "Content-type: text/html\r\n"
  448. "WWW-Authenticate: Basic realm=\"example\"\r\n",
  449. b"Content-Length")
  450. conn = httplib.HTTPConnection("example.com")
  451. conn.sock = sock
  452. self.assertRaises(socket.error,
  453. lambda: conn.request("PUT", "/url", "body"))
  454. resp = conn.getresponse()
  455. self.assertEqual(401, resp.status)
  456. self.assertEqual("Basic realm=\"example\"",
  457. resp.getheader("www-authenticate"))
  458. def test_filenoattr(self):
  459. # Just test the fileno attribute in the HTTPResponse Object.
  460. body = "HTTP/1.1 200 Ok\r\n\r\nText"
  461. sock = FakeSocket(body)
  462. resp = httplib.HTTPResponse(sock)
  463. self.assertTrue(hasattr(resp,'fileno'),
  464. 'HTTPResponse should expose a fileno attribute')
  465. # Test lines overflowing the max line size (_MAXLINE in http.client)
  466. def test_overflowing_status_line(self):
  467. self.skipTest("disabled for HTTP 0.9 support")
  468. body = "HTTP/1.1 200 Ok" + "k" * 65536 + "\r\n"
  469. resp = httplib.HTTPResponse(FakeSocket(body))
  470. self.assertRaises((httplib.LineTooLong, httplib.BadStatusLine), resp.begin)
  471. def test_overflowing_header_line(self):
  472. body = (
  473. 'HTTP/1.1 200 OK\r\n'
  474. 'X-Foo: bar' + 'r' * 65536 + '\r\n\r\n'
  475. )
  476. resp = httplib.HTTPResponse(FakeSocket(body))
  477. self.assertRaises(httplib.LineTooLong, resp.begin)
  478. def test_overflowing_chunked_line(self):
  479. body = (
  480. 'HTTP/1.1 200 OK\r\n'
  481. 'Transfer-Encoding: chunked\r\n\r\n'
  482. + '0' * 65536 + 'a\r\n'
  483. 'hello world\r\n'
  484. '0\r\n'
  485. )
  486. resp = httplib.HTTPResponse(FakeSocket(body))
  487. resp.begin()
  488. self.assertRaises(httplib.LineTooLong, resp.read)
  489. def test_early_eof(self):
  490. # Test httpresponse with no \r\n termination,
  491. body = "HTTP/1.1 200 Ok"
  492. sock = FakeSocket(body)
  493. resp = httplib.HTTPResponse(sock)
  494. resp.begin()
  495. self.assertEqual(resp.read(), '')
  496. self.assertTrue(resp.isclosed())
  497. def test_error_leak(self):
  498. # Test that the socket is not leaked if getresponse() fails
  499. conn = httplib.HTTPConnection('example.com')
  500. response = []
  501. class Response(httplib.HTTPResponse):
  502. def __init__(self, *pos, **kw):
  503. response.append(self) # Avoid garbage collector closing the socket
  504. httplib.HTTPResponse.__init__(self, *pos, **kw)
  505. conn.response_class = Response
  506. conn.sock = FakeSocket('') # Emulate server dropping connection
  507. conn.request('GET', '/')
  508. self.assertRaises(httplib.BadStatusLine, conn.getresponse)
  509. self.assertTrue(response)
  510. #self.assertTrue(response[0].closed)
  511. self.assertTrue(conn.sock.file_closed)
  512. def test_proxy_tunnel_without_status_line(self):
  513. # Issue 17849: If a proxy tunnel is created that does not return
  514. # a status code, fail.
  515. body = 'hello world'
  516. conn = httplib.HTTPConnection('example.com', strict=False)
  517. conn.set_tunnel('foo')
  518. conn.sock = FakeSocket(body)
  519. with self.assertRaisesRegexp(socket.error, "Invalid response"):
  520. conn._tunnel()
  521. class OfflineTest(TestCase):
  522. def test_responses(self):
  523. self.assertEqual(httplib.responses[httplib.NOT_FOUND], "Not Found")
  524. class TestServerMixin:
  525. """A limited socket server mixin.
  526. This is used by test cases for testing http connection end points.
  527. """
  528. def setUp(self):
  529. self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  530. self.port = test_support.bind_port(self.serv)
  531. self.source_port = test_support.find_unused_port()
  532. self.serv.listen(5)
  533. self.conn = None
  534. def tearDown(self):
  535. if self.conn:
  536. self.conn.close()
  537. self.conn = None
  538. self.serv.close()
  539. self.serv = None
  540. class SourceAddressTest(TestServerMixin, TestCase):
  541. def testHTTPConnectionSourceAddress(self):
  542. self.conn = httplib.HTTPConnection(HOST, self.port,
  543. source_address=('', self.source_port))
  544. self.conn.connect()
  545. self.assertEqual(self.conn.sock.getsockname()[1], self.source_port)
  546. @unittest.skipIf(not hasattr(httplib, 'HTTPSConnection'),
  547. 'httplib.HTTPSConnection not defined')
  548. def testHTTPSConnectionSourceAddress(self):
  549. self.conn = httplib.HTTPSConnection(HOST, self.port,
  550. source_address=('', self.source_port))
  551. # We don't test anything here other the constructor not barfing as
  552. # this code doesn't deal with setting up an active running SSL server
  553. # for an ssl_wrapped connect() to actually return from.
  554. class HTTPTest(TestServerMixin, TestCase):
  555. def testHTTPConnection(self):
  556. self.conn = httplib.HTTP(host=HOST, port=self.port, strict=None)
  557. self.conn.connect()
  558. self.assertEqual(self.conn._conn.host, HOST)
  559. self.assertEqual(self.conn._conn.port, self.port)
  560. def testHTTPWithConnectHostPort(self):
  561. testhost = 'unreachable.test.domain'
  562. testport = '80'
  563. self.conn = httplib.HTTP(host=testhost, port=testport)
  564. self.conn.connect(host=HOST, port=self.port)
  565. self.assertNotEqual(self.conn._conn.host, testhost)
  566. self.assertNotEqual(self.conn._conn.port, testport)
  567. self.assertEqual(self.conn._conn.host, HOST)
  568. self.assertEqual(self.conn._conn.port, self.port)
  569. class TimeoutTest(TestCase):
  570. PORT = None
  571. def setUp(self):
  572. self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  573. TimeoutTest.PORT = test_support.bind_port(self.serv)
  574. self.serv.listen(5)
  575. def tearDown(self):
  576. self.serv.close()
  577. self.serv = None
  578. def testTimeoutAttribute(self):
  579. '''This will prove that the timeout gets through
  580. HTTPConnection and into the socket.
  581. '''
  582. # default -- use global socket timeout
  583. self.assertIsNone(socket.getdefaulttimeout())
  584. socket.setdefaulttimeout(30)
  585. try:
  586. httpConn = httplib.HTTPConnection(HOST, TimeoutTest.PORT)
  587. httpConn.connect()
  588. finally:
  589. socket.setdefaulttimeout(None)
  590. self.assertEqual(httpConn.sock.gettimeout(), 30)
  591. httpConn.close()
  592. # no timeout -- do not use global socket default
  593. self.assertIsNone(socket.getdefaulttimeout())
  594. socket.setdefaulttimeout(30)
  595. try:
  596. httpConn = httplib.HTTPConnection(HOST, TimeoutTest.PORT,
  597. timeout=None)
  598. httpConn.connect()
  599. finally:
  600. socket.setdefaulttimeout(None)
  601. self.assertEqual(httpConn.sock.gettimeout(), None)
  602. httpConn.close()
  603. # a value
  604. httpConn = httplib.HTTPConnection(HOST, TimeoutTest.PORT, timeout=30)
  605. httpConn.connect()
  606. self.assertEqual(httpConn.sock.gettimeout(), 30)
  607. httpConn.close()
  608. class HTTPSTest(TestCase):
  609. def setUp(self):
  610. if not hasattr(httplib, 'HTTPSConnection'):
  611. self.skipTest('ssl support required')
  612. def make_server(self, certfile):
  613. from test.ssl_servers import make_https_server
  614. return make_https_server(self, certfile=certfile)
  615. def test_attributes(self):
  616. # simple test to check it's storing the timeout
  617. h = httplib.HTTPSConnection(HOST, TimeoutTest.PORT, timeout=30)
  618. self.assertEqual(h.timeout, 30)
  619. def test_networked(self):
  620. # Default settings: requires a valid cert from a trusted CA
  621. import ssl
  622. test_support.requires('network')
  623. with test_support.transient_internet('self-signed.pythontest.net'):
  624. h = httplib.HTTPSConnection('self-signed.pythontest.net', 443)
  625. with self.assertRaises(ssl.SSLError) as exc_info:
  626. h.request('GET', '/')
  627. self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
  628. def test_networked_noverification(self):
  629. # Switch off cert verification
  630. import ssl
  631. test_support.requires('network')
  632. with test_support.transient_internet('self-signed.pythontest.net'):
  633. context = ssl._create_stdlib_context()
  634. h = httplib.HTTPSConnection('self-signed.pythontest.net', 443,
  635. context=context)
  636. h.request('GET', '/')
  637. resp = h.getresponse()
  638. self.assertIn('nginx', resp.getheader('server'))
  639. @test_support.system_must_validate_cert
  640. def test_networked_trusted_by_default_cert(self):
  641. # Default settings: requires a valid cert from a trusted CA
  642. test_support.requires('network')
  643. with test_support.transient_internet('www.python.org'):
  644. h = httplib.HTTPSConnection('www.python.org', 443)
  645. h.request('GET', '/')
  646. resp = h.getresponse()
  647. content_type = resp.getheader('content-type')
  648. self.assertIn('text/html', content_type)
  649. def test_networked_good_cert(self):
  650. # We feed the server's cert as a validating cert
  651. import ssl
  652. test_support.requires('network')
  653. with test_support.transient_internet('self-signed.pythontest.net'):
  654. context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
  655. context.verify_mode = ssl.CERT_REQUIRED
  656. context.load_verify_locations(CERT_selfsigned_pythontestdotnet)
  657. h = httplib.HTTPSConnection('self-signed.pythontest.net', 443, context=context)
  658. h.request('GET', '/')
  659. resp = h.getresponse()
  660. server_string = resp.getheader('server')
  661. self.assertIn('nginx', server_string)
  662. def test_networked_bad_cert(self):
  663. # We feed a "CA" cert that is unrelated to the server's cert
  664. import ssl
  665. test_support.requires('network')
  666. with test_support.transient_internet('self-signed.pythontest.net'):
  667. context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
  668. context.verify_mode = ssl.CERT_REQUIRED
  669. context.load_verify_locations(CERT_localhost)
  670. h = httplib.HTTPSConnection('self-signed.pythontest.net', 443, context=context)
  671. with self.assertRaises(ssl.SSLError) as exc_info:
  672. h.request('GET', '/')
  673. self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
  674. def test_local_unknown_cert(self):
  675. # The custom cert isn't known to the default trust bundle
  676. import ssl
  677. server = self.make_server(CERT_localhost)
  678. h = httplib.HTTPSConnection('localhost', server.port)
  679. with self.assertRaises(ssl.SSLError) as exc_info:
  680. h.request('GET', '/')
  681. self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
  682. def test_local_good_hostname(self):
  683. # The (valid) cert validates the HTTP hostname
  684. import ssl
  685. server = self.make_server(CERT_localhost)
  686. context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
  687. context.verify_mode = ssl.CERT_REQUIRED
  688. context.load_verify_locations(CERT_localhost)
  689. h = httplib.HTTPSConnection('localhost', server.port, context=context)
  690. h.request('GET', '/nonexistent')
  691. resp = h.getresponse()
  692. self.assertEqual(resp.status, 404)
  693. def test_local_bad_hostname(self):
  694. # The (valid) cert doesn't validate the HTTP hostname
  695. import ssl
  696. server = self.make_server(CERT_fakehostname)
  697. context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
  698. context.verify_mode = ssl.CERT_REQUIRED
  699. context.check_hostname = True
  700. context.load_verify_locations(CERT_fakehostname)
  701. h = httplib.HTTPSConnection('localhost', server.port, context=context)
  702. with self.assertRaises(ssl.CertificateError):
  703. h.request('GET', '/')
  704. h.close()
  705. # With context.check_hostname=False, the mismatching is ignored
  706. context.check_hostname = False
  707. h = httplib.HTTPSConnection('localhost', server.port, context=context)
  708. h.request('GET', '/nonexistent')
  709. resp = h.getresponse()
  710. self.assertEqual(resp.status, 404)
  711. def test_host_port(self):
  712. # Check invalid host_port
  713. for hp in ("www.python.org:abc", "user:password@www.python.org"):
  714. self.assertRaises(httplib.InvalidURL, httplib.HTTPSConnection, hp)
  715. for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
  716. "fe80::207:e9ff:fe9b", 8000),
  717. ("www.python.org:443", "www.python.org", 443),
  718. ("www.python.org:", "www.python.org", 443),
  719. ("www.python.org", "www.python.org", 443),
  720. ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 443),
  721. ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b",
  722. 443)):
  723. c = httplib.HTTPSConnection(hp)
  724. self.assertEqual(h, c.host)
  725. self.assertEqual(p, c.port)
  726. class TunnelTests(TestCase):
  727. def test_connect(self):
  728. response_text = (
  729. 'HTTP/1.0 200 OK\r\n\r\n' # Reply to CONNECT
  730. 'HTTP/1.1 200 OK\r\n' # Reply to HEAD
  731. 'Content-Length: 42\r\n\r\n'
  732. )
  733. def create_connection(address, timeout=None, source_address=None):
  734. return FakeSocket(response_text, host=address[0], port=address[1])
  735. conn = httplib.HTTPConnection('proxy.com')
  736. conn._create_connection = create_connection
  737. # Once connected, we should not be able to tunnel anymore
  738. conn.connect()
  739. self.assertRaises(RuntimeError, conn.set_tunnel, 'destination.com')
  740. # But if close the connection, we are good.
  741. conn.close()
  742. conn.set_tunnel('destination.com')
  743. conn.request('HEAD', '/', '')
  744. self.assertEqual(conn.sock.host, 'proxy.com')
  745. self.assertEqual(conn.sock.port, 80)
  746. self.assertIn('CONNECT destination.com', conn.sock.data)
  747. # issue22095
  748. self.assertNotIn('Host: destination.com:None', conn.sock.data)
  749. self.assertIn('Host: destination.com', conn.sock.data)
  750. self.assertNotIn('Host: proxy.com', conn.sock.data)
  751. conn.close()
  752. conn.request('PUT', '/', '')
  753. self.assertEqual(conn.sock.host, 'proxy.com')
  754. self.assertEqual(conn.sock.port, 80)
  755. self.assertTrue('CONNECT destination.com' in conn.sock.data)
  756. self.assertTrue('Host: destination.com' in conn.sock.data)
  757. @test_support.reap_threads
  758. def test_main(verbose=None):
  759. test_support.run_unittest(HeaderTests, OfflineTest, BasicTest, TimeoutTest,
  760. HTTPTest, HTTPSTest, SourceAddressTest,
  761. TunnelTests)
  762. if __name__ == '__main__':
  763. test_main()