simple_httpclient_test.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866
  1. import collections
  2. from contextlib import closing
  3. import errno
  4. import logging
  5. import os
  6. import re
  7. import socket
  8. import ssl
  9. import sys
  10. import typing # noqa: F401
  11. from tornado.escape import to_unicode, utf8
  12. from tornado import gen, version
  13. from tornado.httpclient import AsyncHTTPClient, HTTPResponse
  14. from tornado.httpserver import HTTPServer
  15. from tornado.httputil import HTTPHeaders, ResponseStartLine
  16. from tornado.ioloop import IOLoop
  17. from tornado.iostream import UnsatisfiableReadError
  18. from tornado.locks import Event
  19. from tornado.log import gen_log
  20. from tornado.netutil import Resolver, bind_sockets
  21. from tornado.simple_httpclient import (
  22. SimpleAsyncHTTPClient,
  23. HTTPStreamClosedError,
  24. HTTPTimeoutError,
  25. )
  26. from tornado.test.httpclient_test import (
  27. ChunkHandler,
  28. CountdownHandler,
  29. HelloWorldHandler,
  30. RedirectHandler,
  31. UserAgentHandler,
  32. )
  33. from tornado.test import httpclient_test
  34. from tornado.testing import (
  35. AsyncHTTPTestCase,
  36. AsyncHTTPSTestCase,
  37. AsyncTestCase,
  38. ExpectLog,
  39. gen_test,
  40. )
  41. from tornado.test.util import (
  42. abstract_base_test,
  43. skipIfNoIPv6,
  44. refusing_port,
  45. )
  46. from tornado.web import RequestHandler, Application, url, stream_request_body
  47. class SimpleHTTPClientCommonTestCase(httpclient_test.HTTPClientCommonTestCase):
  48. def get_http_client(self):
  49. client = SimpleAsyncHTTPClient(force_instance=True)
  50. self.assertTrue(isinstance(client, SimpleAsyncHTTPClient))
  51. return client
  52. class TriggerHandler(RequestHandler):
  53. def initialize(self, queue, wake_callback):
  54. self.queue = queue
  55. self.wake_callback = wake_callback
  56. @gen.coroutine
  57. def get(self):
  58. logging.debug("queuing trigger")
  59. event = Event()
  60. self.queue.append(event.set)
  61. if self.get_argument("wake", "true") == "true":
  62. self.wake_callback()
  63. yield event.wait()
  64. class ContentLengthHandler(RequestHandler):
  65. def get(self):
  66. self.stream = self.detach()
  67. IOLoop.current().spawn_callback(self.write_response)
  68. @gen.coroutine
  69. def write_response(self):
  70. yield self.stream.write(
  71. utf8(
  72. "HTTP/1.0 200 OK\r\nContent-Length: %s\r\n\r\nok"
  73. % self.get_argument("value")
  74. )
  75. )
  76. self.stream.close()
  77. class HeadHandler(RequestHandler):
  78. def head(self):
  79. self.set_header("Content-Length", "7")
  80. class OptionsHandler(RequestHandler):
  81. def options(self):
  82. self.set_header("Access-Control-Allow-Origin", "*")
  83. self.write("ok")
  84. class NoContentHandler(RequestHandler):
  85. def get(self):
  86. self.set_status(204)
  87. self.finish()
  88. class SeeOtherPostHandler(RequestHandler):
  89. def post(self):
  90. redirect_code = int(self.request.body)
  91. assert redirect_code in (302, 303), "unexpected body %r" % self.request.body
  92. self.set_header("Location", "/see_other_get")
  93. self.set_status(redirect_code)
  94. class SeeOtherGetHandler(RequestHandler):
  95. def get(self):
  96. if self.request.body:
  97. raise Exception("unexpected body %r" % self.request.body)
  98. self.write("ok")
  99. class HostEchoHandler(RequestHandler):
  100. def get(self):
  101. self.write(self.request.headers["Host"])
  102. class NoContentLengthHandler(RequestHandler):
  103. def get(self):
  104. if self.request.version.startswith("HTTP/1"):
  105. # Emulate the old HTTP/1.0 behavior of returning a body with no
  106. # content-length. Tornado handles content-length at the framework
  107. # level so we have to go around it.
  108. stream = self.detach()
  109. stream.write(b"HTTP/1.0 200 OK\r\n\r\n" b"hello")
  110. stream.close()
  111. else:
  112. self.finish("HTTP/1 required")
  113. class EchoPostHandler(RequestHandler):
  114. def post(self):
  115. self.write(self.request.body)
  116. @stream_request_body
  117. class RespondInPrepareHandler(RequestHandler):
  118. def prepare(self):
  119. self.set_status(403)
  120. self.finish("forbidden")
  121. @abstract_base_test
  122. class SimpleHTTPClientTestMixin(AsyncTestCase):
  123. # See comments on TestIOStreamWebMixin
  124. def get_http_port(self) -> int:
  125. raise NotImplementedError()
  126. def fetch(
  127. self, path: str, raise_error: bool = False, **kwargs: typing.Any
  128. ) -> HTTPResponse:
  129. # To be filled in by mixing in AsyncHTTPTestCase or AsyncHTTPSTestCase
  130. raise NotImplementedError()
  131. def get_url(self, path: str) -> str:
  132. raise NotImplementedError()
  133. def get_protocol(self) -> str:
  134. raise NotImplementedError()
  135. def get_http_server(self) -> HTTPServer:
  136. raise NotImplementedError()
  137. def create_client(self, **kwargs):
  138. raise NotImplementedError()
  139. def mixin_get_app(self):
  140. # callable objects to finish pending /trigger requests
  141. self.triggers = (
  142. collections.deque()
  143. ) # type: typing.Deque[typing.Callable[[], None]]
  144. return Application(
  145. [
  146. url(
  147. "/trigger",
  148. TriggerHandler,
  149. dict(queue=self.triggers, wake_callback=self.stop),
  150. ),
  151. url("/chunk", ChunkHandler),
  152. url("/countdown/([0-9]+)", CountdownHandler, name="countdown"),
  153. url("/hello", HelloWorldHandler),
  154. url("/content_length", ContentLengthHandler),
  155. url("/head", HeadHandler),
  156. url("/options", OptionsHandler),
  157. url("/no_content", NoContentHandler),
  158. url("/see_other_post", SeeOtherPostHandler),
  159. url("/see_other_get", SeeOtherGetHandler),
  160. url("/host_echo", HostEchoHandler),
  161. url("/no_content_length", NoContentLengthHandler),
  162. url("/echo_post", EchoPostHandler),
  163. url("/respond_in_prepare", RespondInPrepareHandler),
  164. url("/redirect", RedirectHandler),
  165. url("/user_agent", UserAgentHandler),
  166. ],
  167. gzip=True,
  168. )
  169. def test_singleton(self):
  170. # Class "constructor" reuses objects on the same IOLoop
  171. self.assertIs(SimpleAsyncHTTPClient(), SimpleAsyncHTTPClient())
  172. # unless force_instance is used
  173. self.assertIsNot(
  174. SimpleAsyncHTTPClient(), SimpleAsyncHTTPClient(force_instance=True)
  175. )
  176. # different IOLoops use different objects
  177. with closing(IOLoop(make_current=False)) as io_loop2:
  178. async def make_client():
  179. await gen.sleep(0)
  180. return SimpleAsyncHTTPClient()
  181. client1 = self.io_loop.run_sync(make_client)
  182. client2 = io_loop2.run_sync(make_client)
  183. self.assertIsNot(client1, client2)
  184. def test_connection_limit(self):
  185. with closing(self.create_client(max_clients=2)) as client:
  186. self.assertEqual(client.max_clients, 2)
  187. seen = []
  188. # Send 4 requests. Two can be sent immediately, while the others
  189. # will be queued
  190. for i in range(4):
  191. def cb(fut, i=i):
  192. seen.append(i)
  193. self.stop()
  194. client.fetch(self.get_url("/trigger")).add_done_callback(cb)
  195. self.wait(condition=lambda: len(self.triggers) == 2)
  196. self.assertEqual(len(client.queue), 2)
  197. # Finish the first two requests and let the next two through
  198. self.triggers.popleft()()
  199. self.triggers.popleft()()
  200. self.wait(condition=lambda: (len(self.triggers) == 2 and len(seen) == 2))
  201. self.assertEqual(set(seen), {0, 1})
  202. self.assertEqual(len(client.queue), 0)
  203. # Finish all the pending requests
  204. self.triggers.popleft()()
  205. self.triggers.popleft()()
  206. self.wait(condition=lambda: len(seen) == 4)
  207. self.assertEqual(set(seen), {0, 1, 2, 3})
  208. self.assertEqual(len(self.triggers), 0)
  209. @gen_test
  210. def test_redirect_connection_limit(self):
  211. # following redirects should not consume additional connections
  212. with closing(self.create_client(max_clients=1)) as client:
  213. response = yield client.fetch(self.get_url("/countdown/3"), max_redirects=3)
  214. response.rethrow()
  215. def test_max_redirects(self):
  216. response = self.fetch("/countdown/5", max_redirects=3)
  217. self.assertEqual(302, response.code)
  218. # We requested 5, followed three redirects for 4, 3, 2, then the last
  219. # unfollowed redirect is to 1.
  220. self.assertTrue(response.request.url.endswith("/countdown/5"))
  221. self.assertTrue(response.effective_url.endswith("/countdown/2"))
  222. self.assertTrue(response.headers["Location"].endswith("/countdown/1"))
  223. def test_header_reuse(self):
  224. # Apps may reuse a headers object if they are only passing in constant
  225. # headers like user-agent. The header object should not be modified.
  226. headers = HTTPHeaders({"User-Agent": "Foo"})
  227. self.fetch("/hello", headers=headers)
  228. self.assertEqual(list(headers.get_all()), [("User-Agent", "Foo")])
  229. def test_default_user_agent(self):
  230. response = self.fetch("/user_agent", method="GET")
  231. self.assertEqual(200, response.code)
  232. self.assertEqual(response.body.decode(), f"Tornado/{version}")
  233. def test_see_other_redirect(self):
  234. for code in (302, 303):
  235. response = self.fetch("/see_other_post", method="POST", body="%d" % code)
  236. self.assertEqual(200, response.code)
  237. self.assertTrue(response.request.url.endswith("/see_other_post"))
  238. self.assertTrue(response.effective_url.endswith("/see_other_get"))
  239. # request is the original request, is a POST still
  240. self.assertEqual("POST", response.request.method)
  241. @gen_test
  242. def test_connect_timeout(self):
  243. timeout = 0.1
  244. cleanup_event = Event()
  245. test = self
  246. class TimeoutResolver(Resolver):
  247. async def resolve(self, *args, **kwargs):
  248. await cleanup_event.wait()
  249. # Return something valid so the test doesn't raise during shutdown.
  250. return [(socket.AF_INET, ("127.0.0.1", test.get_http_port()))]
  251. with closing(self.create_client(resolver=TimeoutResolver())) as client:
  252. with self.assertRaises(HTTPTimeoutError):
  253. yield client.fetch(
  254. self.get_url("/hello"),
  255. connect_timeout=timeout,
  256. request_timeout=3600,
  257. raise_error=True,
  258. )
  259. # Let the hanging coroutine clean up after itself. We need to
  260. # wait more than a single IOLoop iteration for the SSL case,
  261. # which logs errors on unexpected EOF.
  262. cleanup_event.set()
  263. yield gen.sleep(0.2)
  264. def test_request_timeout(self):
  265. timeout = 0.1
  266. if os.name == "nt":
  267. timeout = 0.5
  268. with self.assertRaises(HTTPTimeoutError):
  269. self.fetch("/trigger?wake=false", request_timeout=timeout, raise_error=True)
  270. # trigger the hanging request to let it clean up after itself
  271. self.triggers.popleft()()
  272. self.io_loop.run_sync(lambda: gen.sleep(0))
  273. @skipIfNoIPv6
  274. def test_ipv6(self):
  275. [sock] = bind_sockets(0, "::1", family=socket.AF_INET6)
  276. port = sock.getsockname()[1]
  277. self.get_http_server().add_socket(sock)
  278. url = "%s://[::1]:%d/hello" % (self.get_protocol(), port)
  279. # ipv6 is currently enabled by default but can be disabled
  280. with self.assertRaises(Exception):
  281. self.fetch(url, allow_ipv6=False, raise_error=True)
  282. response = self.fetch(url)
  283. self.assertEqual(response.body, b"Hello world!")
  284. def test_multiple_content_length_accepted(self):
  285. response = self.fetch("/content_length?value=2,2")
  286. self.assertEqual(response.body, b"ok")
  287. response = self.fetch("/content_length?value=2,%202,2")
  288. self.assertEqual(response.body, b"ok")
  289. with ExpectLog(
  290. gen_log, ".*Multiple unequal Content-Lengths", level=logging.INFO
  291. ):
  292. with self.assertRaises(HTTPStreamClosedError):
  293. self.fetch("/content_length?value=2,4", raise_error=True)
  294. with self.assertRaises(HTTPStreamClosedError):
  295. self.fetch("/content_length?value=2,%202,3", raise_error=True)
  296. def test_head_request(self):
  297. response = self.fetch("/head", method="HEAD")
  298. self.assertEqual(response.code, 200)
  299. self.assertEqual(response.headers["content-length"], "7")
  300. self.assertFalse(response.body)
  301. def test_options_request(self):
  302. response = self.fetch("/options", method="OPTIONS")
  303. self.assertEqual(response.code, 200)
  304. self.assertEqual(response.headers["content-length"], "2")
  305. self.assertEqual(response.headers["access-control-allow-origin"], "*")
  306. self.assertEqual(response.body, b"ok")
  307. def test_no_content(self):
  308. response = self.fetch("/no_content")
  309. self.assertEqual(response.code, 204)
  310. # 204 status shouldn't have a content-length
  311. #
  312. # Tests with a content-length header are included below
  313. # in HTTP204NoContentTestCase.
  314. self.assertNotIn("Content-Length", response.headers)
  315. def test_host_header(self):
  316. host_re = re.compile(b"^127.0.0.1:[0-9]+$")
  317. response = self.fetch("/host_echo")
  318. self.assertTrue(host_re.match(response.body))
  319. url = self.get_url("/host_echo").replace("http://", "http://me:secret@")
  320. response = self.fetch(url)
  321. self.assertTrue(host_re.match(response.body), response.body)
  322. def test_connection_refused(self):
  323. cleanup_func, port = refusing_port()
  324. self.addCleanup(cleanup_func)
  325. with ExpectLog(gen_log, ".*", required=False):
  326. with self.assertRaises(socket.error) as cm:
  327. self.fetch("http://127.0.0.1:%d/" % port, raise_error=True)
  328. if sys.platform != "cygwin":
  329. # cygwin returns EPERM instead of ECONNREFUSED here
  330. contains_errno = str(errno.ECONNREFUSED) in str(cm.exception)
  331. if not contains_errno and hasattr(errno, "WSAECONNREFUSED"):
  332. contains_errno = str(errno.WSAECONNREFUSED) in str( # type: ignore
  333. cm.exception
  334. )
  335. self.assertTrue(contains_errno, cm.exception)
  336. # This is usually "Connection refused".
  337. # On windows, strerror is broken and returns "Unknown error".
  338. expected_message = os.strerror(errno.ECONNREFUSED)
  339. self.assertTrue(expected_message in str(cm.exception), cm.exception)
  340. def test_queue_timeout(self):
  341. with closing(self.create_client(max_clients=1)) as client:
  342. # Wait for the trigger request to block, not complete.
  343. fut1 = client.fetch(self.get_url("/trigger"), request_timeout=10)
  344. self.wait()
  345. with self.assertRaises(HTTPTimeoutError) as cm:
  346. self.io_loop.run_sync(
  347. lambda: client.fetch(
  348. self.get_url("/hello"), connect_timeout=0.1, raise_error=True
  349. )
  350. )
  351. self.assertEqual(str(cm.exception), "Timeout in request queue")
  352. self.triggers.popleft()()
  353. self.io_loop.run_sync(lambda: fut1)
  354. def test_no_content_length(self):
  355. response = self.fetch("/no_content_length")
  356. if response.body == b"HTTP/1 required":
  357. self.skipTest("requires HTTP/1.x")
  358. else:
  359. self.assertEqual(b"hello", response.body)
  360. def sync_body_producer(self, write):
  361. write(b"1234")
  362. write(b"5678")
  363. @gen.coroutine
  364. def async_body_producer(self, write):
  365. yield write(b"1234")
  366. yield gen.moment
  367. yield write(b"5678")
  368. def test_sync_body_producer_chunked(self):
  369. response = self.fetch(
  370. "/echo_post", method="POST", body_producer=self.sync_body_producer
  371. )
  372. response.rethrow()
  373. self.assertEqual(response.body, b"12345678")
  374. def test_sync_body_producer_content_length(self):
  375. response = self.fetch(
  376. "/echo_post",
  377. method="POST",
  378. body_producer=self.sync_body_producer,
  379. headers={"Content-Length": "8"},
  380. )
  381. response.rethrow()
  382. self.assertEqual(response.body, b"12345678")
  383. def test_async_body_producer_chunked(self):
  384. response = self.fetch(
  385. "/echo_post", method="POST", body_producer=self.async_body_producer
  386. )
  387. response.rethrow()
  388. self.assertEqual(response.body, b"12345678")
  389. def test_async_body_producer_content_length(self):
  390. response = self.fetch(
  391. "/echo_post",
  392. method="POST",
  393. body_producer=self.async_body_producer,
  394. headers={"Content-Length": "8"},
  395. )
  396. response.rethrow()
  397. self.assertEqual(response.body, b"12345678")
  398. def test_native_body_producer_chunked(self):
  399. async def body_producer(write):
  400. await write(b"1234")
  401. import asyncio
  402. await asyncio.sleep(0)
  403. await write(b"5678")
  404. response = self.fetch("/echo_post", method="POST", body_producer=body_producer)
  405. response.rethrow()
  406. self.assertEqual(response.body, b"12345678")
  407. def test_native_body_producer_content_length(self):
  408. async def body_producer(write):
  409. await write(b"1234")
  410. import asyncio
  411. await asyncio.sleep(0)
  412. await write(b"5678")
  413. response = self.fetch(
  414. "/echo_post",
  415. method="POST",
  416. body_producer=body_producer,
  417. headers={"Content-Length": "8"},
  418. )
  419. response.rethrow()
  420. self.assertEqual(response.body, b"12345678")
  421. def test_100_continue(self):
  422. response = self.fetch(
  423. "/echo_post", method="POST", body=b"1234", expect_100_continue=True
  424. )
  425. self.assertEqual(response.body, b"1234")
  426. def test_100_continue_early_response(self):
  427. def body_producer(write):
  428. raise Exception("should not be called")
  429. response = self.fetch(
  430. "/respond_in_prepare",
  431. method="POST",
  432. body_producer=body_producer,
  433. expect_100_continue=True,
  434. )
  435. self.assertEqual(response.code, 403)
  436. def test_streaming_follow_redirects(self):
  437. # When following redirects, header and streaming callbacks
  438. # should only be called for the final result.
  439. # TODO(bdarnell): this test belongs in httpclient_test instead of
  440. # simple_httpclient_test, but it fails with the version of libcurl
  441. # available on travis-ci. Move it when that has been upgraded
  442. # or we have a better framework to skip tests based on curl version.
  443. headers = [] # type: typing.List[str]
  444. chunk_bytes = [] # type: typing.List[bytes]
  445. self.fetch(
  446. "/redirect?url=/hello",
  447. header_callback=headers.append,
  448. streaming_callback=chunk_bytes.append,
  449. )
  450. chunks = list(map(to_unicode, chunk_bytes))
  451. self.assertEqual(chunks, ["Hello world!"])
  452. # Make sure we only got one set of headers.
  453. num_start_lines = len([h for h in headers if h.startswith("HTTP/")])
  454. self.assertEqual(num_start_lines, 1)
  455. class SimpleHTTPClientTestCase(AsyncHTTPTestCase, SimpleHTTPClientTestMixin):
  456. def setUp(self):
  457. super().setUp()
  458. self.http_client = self.create_client()
  459. def get_app(self):
  460. return self.mixin_get_app()
  461. def create_client(self, **kwargs):
  462. return SimpleAsyncHTTPClient(force_instance=True, **kwargs)
  463. class SimpleHTTPSClientTestCase(AsyncHTTPSTestCase, SimpleHTTPClientTestMixin):
  464. def setUp(self):
  465. super().setUp()
  466. self.http_client = self.create_client()
  467. def get_app(self):
  468. return self.mixin_get_app()
  469. def create_client(self, **kwargs):
  470. return SimpleAsyncHTTPClient(
  471. force_instance=True, defaults=dict(validate_cert=False), **kwargs
  472. )
  473. def test_ssl_options(self):
  474. resp = self.fetch("/hello", ssl_options={"cert_reqs": ssl.CERT_NONE})
  475. self.assertEqual(resp.body, b"Hello world!")
  476. def test_ssl_context(self):
  477. ssl_ctx = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
  478. ssl_ctx.check_hostname = False
  479. ssl_ctx.verify_mode = ssl.CERT_NONE
  480. resp = self.fetch("/hello", ssl_options=ssl_ctx)
  481. self.assertEqual(resp.body, b"Hello world!")
  482. def test_ssl_options_handshake_fail(self):
  483. with ExpectLog(gen_log, "SSL Error|Uncaught exception", required=False):
  484. with self.assertRaises(ssl.SSLError):
  485. self.fetch(
  486. "/hello",
  487. ssl_options=dict(cert_reqs=ssl.CERT_REQUIRED),
  488. raise_error=True,
  489. )
  490. def test_ssl_context_handshake_fail(self):
  491. with ExpectLog(gen_log, "SSL Error|Uncaught exception"):
  492. # CERT_REQUIRED is set by default.
  493. ctx = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
  494. with self.assertRaises(ssl.SSLError):
  495. self.fetch("/hello", ssl_options=ctx, raise_error=True)
  496. def test_error_logging(self):
  497. # No stack traces are logged for SSL errors (in this case,
  498. # failure to validate the testing self-signed cert).
  499. # The SSLError is exposed through ssl.SSLError.
  500. with ExpectLog(gen_log, ".*") as expect_log:
  501. with self.assertRaises(ssl.SSLError):
  502. self.fetch("/", validate_cert=True, raise_error=True)
  503. self.assertFalse(expect_log.logged_stack)
  504. class CreateAsyncHTTPClientTestCase(AsyncTestCase):
  505. def setUp(self):
  506. super().setUp()
  507. self.saved = AsyncHTTPClient._save_configuration()
  508. def tearDown(self):
  509. AsyncHTTPClient._restore_configuration(self.saved)
  510. super().tearDown()
  511. def test_max_clients(self):
  512. AsyncHTTPClient.configure(SimpleAsyncHTTPClient)
  513. with closing(AsyncHTTPClient(force_instance=True)) as client:
  514. self.assertEqual(client.max_clients, 10) # type: ignore
  515. with closing(AsyncHTTPClient(max_clients=11, force_instance=True)) as client:
  516. self.assertEqual(client.max_clients, 11) # type: ignore
  517. # Now configure max_clients statically and try overriding it
  518. # with each way max_clients can be passed
  519. AsyncHTTPClient.configure(SimpleAsyncHTTPClient, max_clients=12)
  520. with closing(AsyncHTTPClient(force_instance=True)) as client:
  521. self.assertEqual(client.max_clients, 12) # type: ignore
  522. with closing(AsyncHTTPClient(max_clients=13, force_instance=True)) as client:
  523. self.assertEqual(client.max_clients, 13) # type: ignore
  524. with closing(AsyncHTTPClient(max_clients=14, force_instance=True)) as client:
  525. self.assertEqual(client.max_clients, 14) # type: ignore
  526. class HTTP100ContinueTestCase(AsyncHTTPTestCase):
  527. def respond_100(self, request):
  528. self.http1 = request.version.startswith("HTTP/1.")
  529. if not self.http1:
  530. request.connection.write_headers(
  531. ResponseStartLine("", 200, "OK"), HTTPHeaders()
  532. )
  533. request.connection.finish()
  534. return
  535. self.request = request
  536. fut = self.request.connection.stream.write(b"HTTP/1.1 100 CONTINUE\r\n\r\n")
  537. fut.add_done_callback(self.respond_200)
  538. def respond_200(self, fut):
  539. fut.result()
  540. fut = self.request.connection.stream.write(
  541. b"HTTP/1.1 200 OK\r\nContent-Length: 1\r\n\r\nA"
  542. )
  543. fut.add_done_callback(lambda f: self.request.connection.stream.close())
  544. def get_app(self):
  545. # Not a full Application, but works as an HTTPServer callback
  546. return self.respond_100
  547. def test_100_continue(self):
  548. res = self.fetch("/")
  549. if not self.http1:
  550. self.skipTest("requires HTTP/1.x")
  551. self.assertEqual(res.body, b"A")
  552. class HTTP204NoContentTestCase(AsyncHTTPTestCase):
  553. def respond_204(self, request):
  554. self.http1 = request.version.startswith("HTTP/1.")
  555. if not self.http1:
  556. # Close the request cleanly in HTTP/2; it will be skipped anyway.
  557. request.connection.write_headers(
  558. ResponseStartLine("", 200, "OK"), HTTPHeaders()
  559. )
  560. request.connection.finish()
  561. return
  562. # A 204 response never has a body, even if doesn't have a content-length
  563. # (which would otherwise mean read-until-close). We simulate here a
  564. # server that sends no content length and does not close the connection.
  565. #
  566. # Tests of a 204 response with no Content-Length header are included
  567. # in SimpleHTTPClientTestMixin.
  568. stream = request.connection.detach()
  569. stream.write(b"HTTP/1.1 204 No content\r\n")
  570. if request.arguments.get("error", [False])[-1]:
  571. stream.write(b"Content-Length: 5\r\n")
  572. else:
  573. stream.write(b"Content-Length: 0\r\n")
  574. stream.write(b"\r\n")
  575. stream.close()
  576. def get_app(self):
  577. return self.respond_204
  578. def test_204_no_content(self):
  579. resp = self.fetch("/")
  580. if not self.http1:
  581. self.skipTest("requires HTTP/1.x")
  582. self.assertEqual(resp.code, 204)
  583. self.assertEqual(resp.body, b"")
  584. def test_204_invalid_content_length(self):
  585. # 204 status with non-zero content length is malformed
  586. with ExpectLog(
  587. gen_log, ".*Response with code 204 should not have body", level=logging.INFO
  588. ):
  589. with self.assertRaises(HTTPStreamClosedError):
  590. self.fetch("/?error=1", raise_error=True)
  591. if not self.http1:
  592. self.skipTest("requires HTTP/1.x")
  593. if self.http_client.configured_class != SimpleAsyncHTTPClient:
  594. self.skipTest("curl client accepts invalid headers")
  595. class HostnameMappingTestCase(AsyncHTTPTestCase):
  596. def setUp(self):
  597. super().setUp()
  598. self.http_client = SimpleAsyncHTTPClient(
  599. hostname_mapping={
  600. "www.example.com": "127.0.0.1",
  601. ("foo.example.com", 8000): ("127.0.0.1", self.get_http_port()),
  602. }
  603. )
  604. def get_app(self):
  605. return Application([url("/hello", HelloWorldHandler)])
  606. def test_hostname_mapping(self):
  607. response = self.fetch("http://www.example.com:%d/hello" % self.get_http_port())
  608. response.rethrow()
  609. self.assertEqual(response.body, b"Hello world!")
  610. def test_port_mapping(self):
  611. response = self.fetch("http://foo.example.com:8000/hello")
  612. response.rethrow()
  613. self.assertEqual(response.body, b"Hello world!")
  614. class ResolveTimeoutTestCase(AsyncHTTPTestCase):
  615. def setUp(self):
  616. self.cleanup_event = Event()
  617. test = self
  618. # Dummy Resolver subclass that never finishes.
  619. class BadResolver(Resolver):
  620. @gen.coroutine
  621. def resolve(self, *args, **kwargs):
  622. yield test.cleanup_event.wait()
  623. # Return something valid so the test doesn't raise during cleanup.
  624. return [(socket.AF_INET, ("127.0.0.1", test.get_http_port()))]
  625. super().setUp()
  626. self.http_client = SimpleAsyncHTTPClient(resolver=BadResolver())
  627. def get_app(self):
  628. return Application([url("/hello", HelloWorldHandler)])
  629. def test_resolve_timeout(self):
  630. with self.assertRaises(HTTPTimeoutError):
  631. self.fetch("/hello", connect_timeout=0.1, raise_error=True)
  632. # Let the hanging coroutine clean up after itself
  633. self.cleanup_event.set()
  634. self.io_loop.run_sync(lambda: gen.sleep(0))
  635. class MaxHeaderSizeTest(AsyncHTTPTestCase):
  636. def get_app(self):
  637. class SmallHeaders(RequestHandler):
  638. def get(self):
  639. self.set_header("X-Filler", "a" * 100)
  640. self.write("ok")
  641. class LargeHeaders(RequestHandler):
  642. def get(self):
  643. self.set_header("X-Filler", "a" * 1000)
  644. self.write("ok")
  645. return Application([("/small", SmallHeaders), ("/large", LargeHeaders)])
  646. def get_http_client(self):
  647. return SimpleAsyncHTTPClient(max_header_size=1024)
  648. def test_small_headers(self):
  649. response = self.fetch("/small")
  650. response.rethrow()
  651. self.assertEqual(response.body, b"ok")
  652. def test_large_headers(self):
  653. with ExpectLog(gen_log, "Unsatisfiable read", level=logging.INFO):
  654. with self.assertRaises(UnsatisfiableReadError):
  655. self.fetch("/large", raise_error=True)
  656. class MaxBodySizeTest(AsyncHTTPTestCase):
  657. def get_app(self):
  658. class SmallBody(RequestHandler):
  659. def get(self):
  660. self.write("a" * 1024 * 64)
  661. class LargeBody(RequestHandler):
  662. def get(self):
  663. self.write("a" * 1024 * 100)
  664. return Application([("/small", SmallBody), ("/large", LargeBody)])
  665. def get_http_client(self):
  666. return SimpleAsyncHTTPClient(max_body_size=1024 * 64)
  667. def test_small_body(self):
  668. response = self.fetch("/small")
  669. response.rethrow()
  670. self.assertEqual(response.body, b"a" * 1024 * 64)
  671. def test_large_body(self):
  672. with ExpectLog(
  673. gen_log,
  674. "Malformed HTTP message from None: Content-Length too long",
  675. level=logging.INFO,
  676. ):
  677. with self.assertRaises(HTTPStreamClosedError):
  678. self.fetch("/large", raise_error=True)
  679. class MaxBufferSizeTest(AsyncHTTPTestCase):
  680. def get_app(self):
  681. class LargeBody(RequestHandler):
  682. def get(self):
  683. self.write("a" * 1024 * 100)
  684. return Application([("/large", LargeBody)])
  685. def get_http_client(self):
  686. # 100KB body with 64KB buffer
  687. return SimpleAsyncHTTPClient(
  688. max_body_size=1024 * 100, max_buffer_size=1024 * 64
  689. )
  690. def test_large_body(self):
  691. response = self.fetch("/large")
  692. response.rethrow()
  693. self.assertEqual(response.body, b"a" * 1024 * 100)
  694. class ChunkedWithContentLengthTest(AsyncHTTPTestCase):
  695. def get_app(self):
  696. class ChunkedWithContentLength(RequestHandler):
  697. def get(self):
  698. # Add an invalid Transfer-Encoding to the response
  699. self.set_header("Transfer-Encoding", "chunked")
  700. self.write("Hello world")
  701. return Application([("/chunkwithcl", ChunkedWithContentLength)])
  702. def get_http_client(self):
  703. return SimpleAsyncHTTPClient()
  704. def test_chunked_with_content_length(self):
  705. # Make sure the invalid headers are detected
  706. with ExpectLog(
  707. gen_log,
  708. (
  709. "Malformed HTTP message from None: Message "
  710. "with both Transfer-Encoding and Content-Length"
  711. ),
  712. level=logging.INFO,
  713. ):
  714. with self.assertRaises(HTTPStreamClosedError):
  715. self.fetch("/chunkwithcl", raise_error=True)