iostream_test.py 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421
  1. from tornado.concurrent import Future
  2. from tornado import gen
  3. from tornado import netutil
  4. from tornado.ioloop import IOLoop
  5. from tornado.iostream import (
  6. IOStream,
  7. SSLIOStream,
  8. PipeIOStream,
  9. StreamClosedError,
  10. _StreamBuffer,
  11. )
  12. from tornado.httpclient import AsyncHTTPClient, HTTPResponse
  13. from tornado.httputil import HTTPHeaders
  14. from tornado.locks import Condition, Event
  15. from tornado.log import gen_log
  16. from tornado.netutil import ssl_options_to_context, ssl_wrap_socket
  17. from tornado.platform.asyncio import AddThreadSelectorEventLoop
  18. from tornado.tcpserver import TCPServer
  19. from tornado.testing import (
  20. AsyncHTTPTestCase,
  21. AsyncHTTPSTestCase,
  22. AsyncTestCase,
  23. bind_unused_port,
  24. ExpectLog,
  25. gen_test,
  26. )
  27. from tornado.test.util import (
  28. skipIfNonUnix,
  29. refusing_port,
  30. ignore_deprecation,
  31. abstract_base_test,
  32. )
  33. from tornado.web import RequestHandler, Application
  34. import asyncio
  35. import errno
  36. import hashlib
  37. import logging
  38. import os
  39. import platform
  40. import random
  41. import socket
  42. import ssl
  43. import typing
  44. from unittest import mock
  45. import unittest
  46. def _server_ssl_options():
  47. return dict(
  48. certfile=os.path.join(os.path.dirname(__file__), "test.crt"),
  49. keyfile=os.path.join(os.path.dirname(__file__), "test.key"),
  50. )
  51. class HelloHandler(RequestHandler):
  52. def get(self):
  53. self.write("Hello")
  54. @abstract_base_test
  55. class TestIOStreamWebMixin(AsyncTestCase):
  56. # We want to run these tests with both AsyncHTTPTestCase and AsyncHTTPSTestCase,
  57. # but this leads to some tricky inheritance situations. We want this class's
  58. # get_app, but the test classes's get_http_port and fetch. There's no way to make
  59. # the method resolution order to do what we want in all cases, so the current
  60. # state is that that AsyncHTTP(S)TestCase must be the first base class of the
  61. # final class, and that class must define a get_app method that calls mixin_get_app.
  62. #
  63. # Alternatives include defining this class in a factory that can change the base class
  64. # or refactoring to use composition instead of inheritance for the http components.
  65. def _make_client_iostream(self):
  66. raise NotImplementedError()
  67. def mixin_get_app(self):
  68. return Application([("/", HelloHandler)])
  69. def get_http_port(self) -> int:
  70. raise NotImplementedError()
  71. def fetch(
  72. self, path: str, raise_error: bool = False, **kwargs: typing.Any
  73. ) -> HTTPResponse:
  74. # To be filled in by mixing in AsyncHTTPTestCase or AsyncHTTPSTestCase
  75. raise NotImplementedError()
  76. def test_connection_closed(self):
  77. # When a server sends a response and then closes the connection,
  78. # the client must be allowed to read the data before the IOStream
  79. # closes itself. Epoll reports closed connections with a separate
  80. # EPOLLRDHUP event delivered at the same time as the read event,
  81. # while kqueue reports them as a second read/write event with an EOF
  82. # flag.
  83. if (
  84. AsyncHTTPClient.configured_class().__name__.endswith("CurlAsyncHTTPClient")
  85. and platform.system() == "Darwin"
  86. ):
  87. # It's possible that this is Tornado's fault, either in AsyncIOLoop or in
  88. # CurlAsyncHTTPClient, but we've also seen this kind of issue in libcurl itself
  89. # (especially a long time ago). The error is tied to the use of Apple's
  90. # SecureTransport instead of OpenSSL.
  91. self.skipTest("libcurl doesn't handle closed connections cleanly on macOS")
  92. response = self.fetch("/", headers={"Connection": "close"})
  93. response.rethrow()
  94. @gen_test
  95. def test_read_until_close(self):
  96. stream = self._make_client_iostream()
  97. yield stream.connect(("127.0.0.1", self.get_http_port()))
  98. stream.write(b"GET / HTTP/1.0\r\n\r\n")
  99. data = yield stream.read_until_close()
  100. self.assertTrue(data.startswith(b"HTTP/1.1 200"))
  101. self.assertTrue(data.endswith(b"Hello"))
  102. @gen_test
  103. def test_read_zero_bytes(self):
  104. self.stream = self._make_client_iostream()
  105. yield self.stream.connect(("127.0.0.1", self.get_http_port()))
  106. self.stream.write(b"GET / HTTP/1.0\r\n\r\n")
  107. # normal read
  108. data = yield self.stream.read_bytes(9)
  109. self.assertEqual(data, b"HTTP/1.1 ")
  110. # zero bytes
  111. data = yield self.stream.read_bytes(0)
  112. self.assertEqual(data, b"")
  113. # another normal read
  114. data = yield self.stream.read_bytes(3)
  115. self.assertEqual(data, b"200")
  116. self.stream.close()
  117. @gen_test
  118. def test_write_while_connecting(self):
  119. stream = self._make_client_iostream()
  120. connect_fut = stream.connect(("127.0.0.1", self.get_http_port()))
  121. # unlike the previous tests, try to write before the connection
  122. # is complete.
  123. write_fut = stream.write(b"GET / HTTP/1.0\r\nConnection: close\r\n\r\n")
  124. self.assertFalse(connect_fut.done())
  125. # connect will always complete before write.
  126. it = gen.WaitIterator(connect_fut, write_fut)
  127. resolved_order = []
  128. while not it.done():
  129. yield it.next()
  130. resolved_order.append(it.current_future)
  131. self.assertEqual(resolved_order, [connect_fut, write_fut])
  132. data = yield stream.read_until_close()
  133. self.assertTrue(data.endswith(b"Hello"))
  134. stream.close()
  135. @gen_test
  136. def test_future_interface(self):
  137. """Basic test of IOStream's ability to return Futures."""
  138. stream = self._make_client_iostream()
  139. connect_result = yield stream.connect(("127.0.0.1", self.get_http_port()))
  140. self.assertIs(connect_result, stream)
  141. yield stream.write(b"GET / HTTP/1.0\r\n\r\n")
  142. first_line = yield stream.read_until(b"\r\n")
  143. self.assertEqual(first_line, b"HTTP/1.1 200 OK\r\n")
  144. # callback=None is equivalent to no callback.
  145. header_data = yield stream.read_until(b"\r\n\r\n")
  146. headers = HTTPHeaders.parse(header_data.decode("latin1"))
  147. content_length = int(headers["Content-Length"])
  148. body = yield stream.read_bytes(content_length)
  149. self.assertEqual(body, b"Hello")
  150. stream.close()
  151. @gen_test
  152. def test_future_close_while_reading(self):
  153. stream = self._make_client_iostream()
  154. yield stream.connect(("127.0.0.1", self.get_http_port()))
  155. yield stream.write(b"GET / HTTP/1.0\r\n\r\n")
  156. with self.assertRaises(StreamClosedError):
  157. yield stream.read_bytes(1024 * 1024)
  158. stream.close()
  159. @gen_test
  160. def test_future_read_until_close(self):
  161. # Ensure that the data comes through before the StreamClosedError.
  162. stream = self._make_client_iostream()
  163. yield stream.connect(("127.0.0.1", self.get_http_port()))
  164. yield stream.write(b"GET / HTTP/1.0\r\nConnection: close\r\n\r\n")
  165. yield stream.read_until(b"\r\n\r\n")
  166. body = yield stream.read_until_close()
  167. self.assertEqual(body, b"Hello")
  168. # Nothing else to read; the error comes immediately without waiting
  169. # for yield.
  170. with self.assertRaises(StreamClosedError):
  171. stream.read_bytes(1)
  172. @abstract_base_test
  173. class TestReadWriteMixin(AsyncTestCase):
  174. # Tests where one stream reads and the other writes.
  175. # These should work for BaseIOStream implementations.
  176. def make_iostream_pair(self, **kwargs):
  177. raise NotImplementedError
  178. def iostream_pair(self, **kwargs):
  179. """Like make_iostream_pair, but called by ``async with``.
  180. In py37 this becomes simpler with contextlib.asynccontextmanager.
  181. """
  182. class IOStreamPairContext:
  183. def __init__(self, test, kwargs):
  184. self.test = test
  185. self.kwargs = kwargs
  186. async def __aenter__(self):
  187. self.pair = await self.test.make_iostream_pair(**self.kwargs)
  188. return self.pair
  189. async def __aexit__(self, typ, value, tb):
  190. for s in self.pair:
  191. s.close()
  192. return IOStreamPairContext(self, kwargs)
  193. @gen_test
  194. def test_write_zero_bytes(self):
  195. # Attempting to write zero bytes should run the callback without
  196. # going into an infinite loop.
  197. rs, ws = yield self.make_iostream_pair()
  198. yield ws.write(b"")
  199. ws.close()
  200. rs.close()
  201. @gen_test
  202. def test_future_delayed_close_callback(self):
  203. # Same as test_delayed_close_callback, but with the future interface.
  204. rs, ws = yield self.make_iostream_pair()
  205. try:
  206. ws.write(b"12")
  207. chunks = []
  208. chunks.append((yield rs.read_bytes(1)))
  209. ws.close()
  210. chunks.append((yield rs.read_bytes(1)))
  211. self.assertEqual(chunks, [b"1", b"2"])
  212. finally:
  213. ws.close()
  214. rs.close()
  215. @gen_test
  216. def test_close_buffered_data(self):
  217. # Similar to the previous test, but with data stored in the OS's
  218. # socket buffers instead of the IOStream's read buffer. Out-of-band
  219. # close notifications must be delayed until all data has been
  220. # drained into the IOStream buffer. (epoll used to use out-of-band
  221. # close events with EPOLLRDHUP, but no longer)
  222. #
  223. # This depends on the read_chunk_size being smaller than the
  224. # OS socket buffer, so make it small.
  225. rs, ws = yield self.make_iostream_pair(read_chunk_size=256)
  226. try:
  227. ws.write(b"A" * 512)
  228. data = yield rs.read_bytes(256)
  229. self.assertEqual(b"A" * 256, data)
  230. ws.close()
  231. # Allow the close to propagate to the `rs` side of the
  232. # connection. Using add_callback instead of add_timeout
  233. # doesn't seem to work, even with multiple iterations
  234. yield gen.sleep(0.01)
  235. data = yield rs.read_bytes(256)
  236. self.assertEqual(b"A" * 256, data)
  237. finally:
  238. ws.close()
  239. rs.close()
  240. @gen_test
  241. def test_read_until_close_after_close(self):
  242. # Similar to test_delayed_close_callback, but read_until_close takes
  243. # a separate code path so test it separately.
  244. rs, ws = yield self.make_iostream_pair()
  245. try:
  246. ws.write(b"1234")
  247. # Read one byte to make sure the client has received the data.
  248. # It won't run the close callback as long as there is more buffered
  249. # data that could satisfy a later read.
  250. data = yield rs.read_bytes(1)
  251. ws.close()
  252. self.assertEqual(data, b"1")
  253. data = yield rs.read_until_close()
  254. self.assertEqual(data, b"234")
  255. finally:
  256. ws.close()
  257. rs.close()
  258. @gen_test
  259. def test_large_read_until(self):
  260. # Performance test: read_until used to have a quadratic component
  261. # so a read_until of 4MB would take 8 seconds; now it takes 0.25
  262. # seconds.
  263. rs, ws = yield self.make_iostream_pair()
  264. try:
  265. # This test fails on pypy with ssl. I think it's because
  266. # pypy's gc defeats moves objects, breaking the
  267. # "frozen write buffer" assumption.
  268. if (
  269. isinstance(rs, SSLIOStream)
  270. and platform.python_implementation() == "PyPy"
  271. ):
  272. raise unittest.SkipTest("pypy gc causes problems with openssl")
  273. NUM_KB = 4096
  274. for i in range(NUM_KB):
  275. ws.write(b"A" * 1024)
  276. ws.write(b"\r\n")
  277. data = yield rs.read_until(b"\r\n")
  278. self.assertEqual(len(data), NUM_KB * 1024 + 2)
  279. finally:
  280. ws.close()
  281. rs.close()
  282. @gen_test
  283. async def test_read_until_with_close_after_second_packet(self):
  284. # This is a regression test for a regression in Tornado 6.0
  285. # (maybe 6.0.3?) reported in
  286. # https://github.com/tornadoweb/tornado/issues/2717
  287. #
  288. # The data arrives in two chunks; the stream is closed at the
  289. # same time that the second chunk is received. If the second
  290. # chunk is larger than the first, it works, but when this bug
  291. # existed it would fail if the second chunk were smaller than
  292. # the first. This is due to the optimization that the
  293. # read_until condition is only checked when the buffer doubles
  294. # in size
  295. async with self.iostream_pair() as (rs, ws):
  296. rf = asyncio.ensure_future(rs.read_until(b"done"))
  297. # We need to wait for the read_until to actually start. On
  298. # windows that's tricky because the selector runs in
  299. # another thread; sleeping is the simplest way.
  300. await asyncio.sleep(0.1)
  301. await ws.write(b"x" * 2048)
  302. ws.write(b"done")
  303. ws.close()
  304. await rf
  305. @gen_test
  306. async def test_read_until_unsatisfied_after_close(self):
  307. # If a stream is closed while reading, it raises
  308. # StreamClosedError instead of UnsatisfiableReadError (the
  309. # latter should only be raised when byte limits are reached).
  310. # The particular scenario tested here comes from #2717.
  311. async with self.iostream_pair() as (rs, ws):
  312. rf = asyncio.ensure_future(rs.read_until(b"done"))
  313. await ws.write(b"x" * 2048)
  314. ws.write(b"foo")
  315. ws.close()
  316. with self.assertRaises(StreamClosedError):
  317. await rf
  318. @gen_test
  319. def test_close_callback_with_pending_read(self):
  320. # Regression test for a bug that was introduced in 2.3
  321. # where the IOStream._close_callback would never be called
  322. # if there were pending reads.
  323. OK = b"OK\r\n"
  324. rs, ws = yield self.make_iostream_pair()
  325. event = Event()
  326. rs.set_close_callback(event.set)
  327. try:
  328. ws.write(OK)
  329. res = yield rs.read_until(b"\r\n")
  330. self.assertEqual(res, OK)
  331. ws.close()
  332. rs.read_until(b"\r\n")
  333. # If _close_callback (self.stop) is not called,
  334. # an AssertionError: Async operation timed out after 5 seconds
  335. # will be raised.
  336. yield event.wait()
  337. finally:
  338. ws.close()
  339. rs.close()
  340. @gen_test
  341. def test_future_close_callback(self):
  342. # Regression test for interaction between the Future read interfaces
  343. # and IOStream._maybe_add_error_listener.
  344. rs, ws = yield self.make_iostream_pair()
  345. closed = [False]
  346. cond = Condition()
  347. def close_callback():
  348. closed[0] = True
  349. cond.notify()
  350. rs.set_close_callback(close_callback)
  351. try:
  352. ws.write(b"a")
  353. res = yield rs.read_bytes(1)
  354. self.assertEqual(res, b"a")
  355. self.assertFalse(closed[0])
  356. ws.close()
  357. yield cond.wait()
  358. self.assertTrue(closed[0])
  359. finally:
  360. rs.close()
  361. ws.close()
  362. @gen_test
  363. def test_write_memoryview(self):
  364. rs, ws = yield self.make_iostream_pair()
  365. try:
  366. fut = rs.read_bytes(4)
  367. ws.write(memoryview(b"hello"))
  368. data = yield fut
  369. self.assertEqual(data, b"hell")
  370. finally:
  371. ws.close()
  372. rs.close()
  373. @gen_test
  374. def test_read_bytes_partial(self):
  375. rs, ws = yield self.make_iostream_pair()
  376. try:
  377. # Ask for more than is available with partial=True
  378. fut = rs.read_bytes(50, partial=True)
  379. ws.write(b"hello")
  380. data = yield fut
  381. self.assertEqual(data, b"hello")
  382. # Ask for less than what is available; num_bytes is still
  383. # respected.
  384. fut = rs.read_bytes(3, partial=True)
  385. ws.write(b"world")
  386. data = yield fut
  387. self.assertEqual(data, b"wor")
  388. # Partial reads won't return an empty string, but read_bytes(0)
  389. # will.
  390. data = yield rs.read_bytes(0, partial=True)
  391. self.assertEqual(data, b"")
  392. finally:
  393. ws.close()
  394. rs.close()
  395. @gen_test
  396. def test_read_until_max_bytes(self):
  397. rs, ws = yield self.make_iostream_pair()
  398. closed = Event()
  399. rs.set_close_callback(closed.set)
  400. try:
  401. # Extra room under the limit
  402. fut = rs.read_until(b"def", max_bytes=50)
  403. ws.write(b"abcdef")
  404. data = yield fut
  405. self.assertEqual(data, b"abcdef")
  406. # Just enough space
  407. fut = rs.read_until(b"def", max_bytes=6)
  408. ws.write(b"abcdef")
  409. data = yield fut
  410. self.assertEqual(data, b"abcdef")
  411. # Not enough space, but we don't know it until all we can do is
  412. # log a warning and close the connection.
  413. with ExpectLog(gen_log, "Unsatisfiable read", level=logging.INFO):
  414. fut = rs.read_until(b"def", max_bytes=5)
  415. ws.write(b"123456")
  416. yield closed.wait()
  417. finally:
  418. ws.close()
  419. rs.close()
  420. @gen_test
  421. def test_read_until_max_bytes_inline(self):
  422. rs, ws = yield self.make_iostream_pair()
  423. closed = Event()
  424. rs.set_close_callback(closed.set)
  425. try:
  426. # Similar to the error case in the previous test, but the
  427. # ws writes first so rs reads are satisfied
  428. # inline. For consistency with the out-of-line case, we
  429. # do not raise the error synchronously.
  430. ws.write(b"123456")
  431. with ExpectLog(gen_log, "Unsatisfiable read", level=logging.INFO):
  432. with self.assertRaises(StreamClosedError):
  433. yield rs.read_until(b"def", max_bytes=5)
  434. yield closed.wait()
  435. finally:
  436. ws.close()
  437. rs.close()
  438. @gen_test
  439. def test_read_until_max_bytes_ignores_extra(self):
  440. rs, ws = yield self.make_iostream_pair()
  441. closed = Event()
  442. rs.set_close_callback(closed.set)
  443. try:
  444. # Even though data that matches arrives the same packet that
  445. # puts us over the limit, we fail the request because it was not
  446. # found within the limit.
  447. ws.write(b"abcdef")
  448. with ExpectLog(gen_log, "Unsatisfiable read", level=logging.INFO):
  449. rs.read_until(b"def", max_bytes=5)
  450. yield closed.wait()
  451. finally:
  452. ws.close()
  453. rs.close()
  454. @gen_test
  455. def test_read_until_regex_max_bytes(self):
  456. rs, ws = yield self.make_iostream_pair()
  457. closed = Event()
  458. rs.set_close_callback(closed.set)
  459. try:
  460. # Extra room under the limit
  461. fut = rs.read_until_regex(b"def", max_bytes=50)
  462. ws.write(b"abcdef")
  463. data = yield fut
  464. self.assertEqual(data, b"abcdef")
  465. # Just enough space
  466. fut = rs.read_until_regex(b"def", max_bytes=6)
  467. ws.write(b"abcdef")
  468. data = yield fut
  469. self.assertEqual(data, b"abcdef")
  470. # Not enough space, but we don't know it until all we can do is
  471. # log a warning and close the connection.
  472. with ExpectLog(gen_log, "Unsatisfiable read", level=logging.INFO):
  473. rs.read_until_regex(b"def", max_bytes=5)
  474. ws.write(b"123456")
  475. yield closed.wait()
  476. finally:
  477. ws.close()
  478. rs.close()
  479. @gen_test
  480. def test_read_until_regex_max_bytes_inline(self):
  481. rs, ws = yield self.make_iostream_pair()
  482. closed = Event()
  483. rs.set_close_callback(closed.set)
  484. try:
  485. # Similar to the error case in the previous test, but the
  486. # ws writes first so rs reads are satisfied
  487. # inline. For consistency with the out-of-line case, we
  488. # do not raise the error synchronously.
  489. ws.write(b"123456")
  490. with ExpectLog(gen_log, "Unsatisfiable read", level=logging.INFO):
  491. rs.read_until_regex(b"def", max_bytes=5)
  492. yield closed.wait()
  493. finally:
  494. ws.close()
  495. rs.close()
  496. @gen_test
  497. def test_read_until_regex_max_bytes_ignores_extra(self):
  498. rs, ws = yield self.make_iostream_pair()
  499. closed = Event()
  500. rs.set_close_callback(closed.set)
  501. try:
  502. # Even though data that matches arrives the same packet that
  503. # puts us over the limit, we fail the request because it was not
  504. # found within the limit.
  505. ws.write(b"abcdef")
  506. with ExpectLog(gen_log, "Unsatisfiable read", level=logging.INFO):
  507. rs.read_until_regex(b"def", max_bytes=5)
  508. yield closed.wait()
  509. finally:
  510. ws.close()
  511. rs.close()
  512. @gen_test
  513. def test_small_reads_from_large_buffer(self):
  514. # 10KB buffer size, 100KB available to read.
  515. # Read 1KB at a time and make sure that the buffer is not eagerly
  516. # filled.
  517. rs, ws = yield self.make_iostream_pair(max_buffer_size=10 * 1024)
  518. try:
  519. ws.write(b"a" * 1024 * 100)
  520. for i in range(100):
  521. data = yield rs.read_bytes(1024)
  522. self.assertEqual(data, b"a" * 1024)
  523. finally:
  524. ws.close()
  525. rs.close()
  526. @gen_test
  527. def test_small_read_untils_from_large_buffer(self):
  528. # 10KB buffer size, 100KB available to read.
  529. # Read 1KB at a time and make sure that the buffer is not eagerly
  530. # filled.
  531. rs, ws = yield self.make_iostream_pair(max_buffer_size=10 * 1024)
  532. try:
  533. ws.write((b"a" * 1023 + b"\n") * 100)
  534. for i in range(100):
  535. data = yield rs.read_until(b"\n", max_bytes=4096)
  536. self.assertEqual(data, b"a" * 1023 + b"\n")
  537. finally:
  538. ws.close()
  539. rs.close()
  540. @gen_test
  541. def test_flow_control(self):
  542. MB = 1024 * 1024
  543. rs, ws = yield self.make_iostream_pair(max_buffer_size=5 * MB)
  544. try:
  545. # Client writes more than the rs will accept.
  546. ws.write(b"a" * 10 * MB)
  547. # The rs pauses while reading.
  548. yield rs.read_bytes(MB)
  549. yield gen.sleep(0.1)
  550. # The ws's writes have been blocked; the rs can
  551. # continue to read gradually.
  552. for i in range(9):
  553. yield rs.read_bytes(MB)
  554. finally:
  555. rs.close()
  556. ws.close()
  557. @gen_test
  558. def test_read_into(self):
  559. rs, ws = yield self.make_iostream_pair()
  560. def sleep_some():
  561. self.io_loop.run_sync(lambda: gen.sleep(0.05))
  562. try:
  563. buf = bytearray(10)
  564. fut = rs.read_into(buf)
  565. ws.write(b"hello")
  566. yield gen.sleep(0.05)
  567. self.assertTrue(rs.reading())
  568. ws.write(b"world!!")
  569. data = yield fut
  570. self.assertFalse(rs.reading())
  571. self.assertEqual(data, 10)
  572. self.assertEqual(bytes(buf), b"helloworld")
  573. # Existing buffer is fed into user buffer
  574. fut = rs.read_into(buf)
  575. yield gen.sleep(0.05)
  576. self.assertTrue(rs.reading())
  577. ws.write(b"1234567890")
  578. data = yield fut
  579. self.assertFalse(rs.reading())
  580. self.assertEqual(data, 10)
  581. self.assertEqual(bytes(buf), b"!!12345678")
  582. # Existing buffer can satisfy read immediately
  583. buf = bytearray(4)
  584. ws.write(b"abcdefghi")
  585. data = yield rs.read_into(buf)
  586. self.assertEqual(data, 4)
  587. self.assertEqual(bytes(buf), b"90ab")
  588. data = yield rs.read_bytes(7)
  589. self.assertEqual(data, b"cdefghi")
  590. finally:
  591. ws.close()
  592. rs.close()
  593. @gen_test
  594. def test_read_into_partial(self):
  595. rs, ws = yield self.make_iostream_pair()
  596. try:
  597. # Partial read
  598. buf = bytearray(10)
  599. fut = rs.read_into(buf, partial=True)
  600. ws.write(b"hello")
  601. data = yield fut
  602. self.assertFalse(rs.reading())
  603. self.assertEqual(data, 5)
  604. self.assertEqual(bytes(buf), b"hello\0\0\0\0\0")
  605. # Full read despite partial=True
  606. ws.write(b"world!1234567890")
  607. data = yield rs.read_into(buf, partial=True)
  608. self.assertEqual(data, 10)
  609. self.assertEqual(bytes(buf), b"world!1234")
  610. # Existing buffer can satisfy read immediately
  611. data = yield rs.read_into(buf, partial=True)
  612. self.assertEqual(data, 6)
  613. self.assertEqual(bytes(buf), b"5678901234")
  614. finally:
  615. ws.close()
  616. rs.close()
  617. @gen_test
  618. def test_read_into_zero_bytes(self):
  619. rs, ws = yield self.make_iostream_pair()
  620. try:
  621. buf = bytearray()
  622. fut = rs.read_into(buf)
  623. self.assertEqual(fut.result(), 0)
  624. finally:
  625. ws.close()
  626. rs.close()
  627. @gen_test
  628. def test_many_mixed_reads(self):
  629. # Stress buffer handling when going back and forth between
  630. # read_bytes() (using an internal buffer) and read_into()
  631. # (using a user-allocated buffer).
  632. r = random.Random(42)
  633. nbytes = 1000000
  634. rs, ws = yield self.make_iostream_pair()
  635. produce_hash = hashlib.sha1()
  636. consume_hash = hashlib.sha1()
  637. @gen.coroutine
  638. def produce():
  639. remaining = nbytes
  640. while remaining > 0:
  641. size = r.randint(1, min(1000, remaining))
  642. data = os.urandom(size)
  643. produce_hash.update(data)
  644. yield ws.write(data)
  645. remaining -= size
  646. assert remaining == 0
  647. @gen.coroutine
  648. def consume():
  649. remaining = nbytes
  650. while remaining > 0:
  651. if r.random() > 0.5:
  652. # read_bytes()
  653. size = r.randint(1, min(1000, remaining))
  654. data = yield rs.read_bytes(size)
  655. consume_hash.update(data)
  656. remaining -= size
  657. else:
  658. # read_into()
  659. size = r.randint(1, min(1000, remaining))
  660. buf = bytearray(size)
  661. n = yield rs.read_into(buf)
  662. assert n == size
  663. consume_hash.update(buf)
  664. remaining -= size
  665. assert remaining == 0
  666. try:
  667. yield [produce(), consume()]
  668. assert produce_hash.hexdigest() == consume_hash.hexdigest()
  669. finally:
  670. ws.close()
  671. rs.close()
  672. @abstract_base_test
  673. class TestIOStreamMixin(TestReadWriteMixin):
  674. def _make_server_iostream(self, connection, **kwargs):
  675. raise NotImplementedError()
  676. def _make_client_iostream(self, connection, **kwargs):
  677. raise NotImplementedError()
  678. @gen.coroutine
  679. def make_iostream_pair(self, **kwargs):
  680. listener, port = bind_unused_port()
  681. server_stream_fut = Future() # type: Future[IOStream]
  682. def accept_callback(connection, address):
  683. server_stream_fut.set_result(
  684. self._make_server_iostream(connection, **kwargs)
  685. )
  686. netutil.add_accept_handler(listener, accept_callback)
  687. client_stream = self._make_client_iostream(socket.socket(), **kwargs)
  688. connect_fut = client_stream.connect(("127.0.0.1", port))
  689. server_stream, client_stream = yield [server_stream_fut, connect_fut]
  690. self.io_loop.remove_handler(listener.fileno())
  691. listener.close()
  692. raise gen.Return((server_stream, client_stream))
  693. @gen_test
  694. def test_connection_refused(self):
  695. # When a connection is refused, the connect callback should not
  696. # be run. (The kqueue IOLoop used to behave differently from the
  697. # epoll IOLoop in this respect)
  698. cleanup_func, port = refusing_port()
  699. self.addCleanup(cleanup_func)
  700. stream = IOStream(socket.socket())
  701. stream.set_close_callback(self.stop)
  702. # log messages vary by platform and ioloop implementation
  703. with ExpectLog(gen_log, ".*", required=False):
  704. with self.assertRaises(StreamClosedError):
  705. yield stream.connect(("127.0.0.1", port))
  706. self.assertTrue(isinstance(stream.error, ConnectionRefusedError), stream.error)
  707. @gen_test
  708. def test_gaierror(self):
  709. # Test that IOStream sets its exc_info on getaddrinfo error.
  710. # It's difficult to reliably trigger a getaddrinfo error;
  711. # some resolvers own't even return errors for malformed names,
  712. # so we mock it instead. If IOStream changes to call a Resolver
  713. # before sock.connect, the mock target will need to change too.
  714. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
  715. stream = IOStream(s)
  716. stream.set_close_callback(self.stop)
  717. with mock.patch(
  718. "socket.socket.connect", side_effect=socket.gaierror(errno.EIO, "boom")
  719. ):
  720. with self.assertRaises(StreamClosedError):
  721. yield stream.connect(("localhost", 80))
  722. self.assertTrue(isinstance(stream.error, socket.gaierror))
  723. @gen_test
  724. def test_read_until_close_with_error(self):
  725. server, client = yield self.make_iostream_pair()
  726. try:
  727. with mock.patch(
  728. "tornado.iostream.BaseIOStream._try_inline_read",
  729. side_effect=IOError("boom"),
  730. ):
  731. with self.assertRaisesRegex(IOError, "boom"):
  732. client.read_until_close()
  733. finally:
  734. server.close()
  735. client.close()
  736. @skipIfNonUnix
  737. @gen_test
  738. def test_inline_read_error(self):
  739. # An error on an inline read is raised without logging (on the
  740. # assumption that it will eventually be noticed or logged further
  741. # up the stack).
  742. #
  743. # This test is posix-only because windows os.close() doesn't work
  744. # on socket FDs, but we can't close the socket object normally
  745. # because we won't get the error we want if the socket knows
  746. # it's closed.
  747. #
  748. # This test is also disabled when the
  749. # AddThreadSelectorEventLoop is used, because a race between
  750. # this thread closing the socket and the selector thread
  751. # calling the select system call can make this test flaky.
  752. # This event loop implementation is normally only used on
  753. # windows, making this check redundant with skipIfNonUnix, but
  754. # we sometimes enable it on other platforms for testing.
  755. io_loop = IOLoop.current()
  756. if isinstance(
  757. io_loop.selector_loop, # type: ignore[attr-defined]
  758. AddThreadSelectorEventLoop,
  759. ):
  760. self.skipTest("AddThreadSelectorEventLoop not supported")
  761. server, client = yield self.make_iostream_pair()
  762. try:
  763. os.close(server.socket.fileno())
  764. with self.assertRaises(socket.error):
  765. server.read_bytes(1)
  766. finally:
  767. server.close()
  768. client.close()
  769. @gen_test
  770. def test_async_read_error_logging(self):
  771. # Socket errors on asynchronous reads should be logged (but only
  772. # once).
  773. server, client = yield self.make_iostream_pair()
  774. closed = Event()
  775. server.set_close_callback(closed.set)
  776. try:
  777. # Start a read that will be fulfilled asynchronously.
  778. server.read_bytes(1)
  779. client.write(b"a")
  780. # Stub out read_from_fd to make it fail.
  781. def fake_read_from_fd():
  782. os.close(server.socket.fileno())
  783. server.__class__.read_from_fd(server)
  784. server.read_from_fd = fake_read_from_fd
  785. # This log message is from _handle_read (not read_from_fd).
  786. with ExpectLog(gen_log, "error on read"):
  787. yield closed.wait()
  788. finally:
  789. server.close()
  790. client.close()
  791. @gen_test
  792. def test_future_write(self):
  793. """
  794. Test that write() Futures are never orphaned.
  795. """
  796. # Run concurrent writers that will write enough bytes so as to
  797. # clog the socket buffer and accumulate bytes in our write buffer.
  798. m, n = 5000, 1000
  799. nproducers = 10
  800. total_bytes = m * n * nproducers
  801. server, client = yield self.make_iostream_pair(max_buffer_size=total_bytes)
  802. @gen.coroutine
  803. def produce():
  804. data = b"x" * m
  805. for i in range(n):
  806. yield server.write(data)
  807. @gen.coroutine
  808. def consume():
  809. nread = 0
  810. while nread < total_bytes:
  811. res = yield client.read_bytes(m)
  812. nread += len(res)
  813. try:
  814. yield [produce() for i in range(nproducers)] + [consume()]
  815. finally:
  816. server.close()
  817. client.close()
  818. class TestIOStreamWebHTTP(AsyncHTTPTestCase, TestIOStreamWebMixin):
  819. def _make_client_iostream(self):
  820. return IOStream(socket.socket())
  821. def get_app(self):
  822. return self.mixin_get_app()
  823. class TestIOStreamWebHTTPS(AsyncHTTPSTestCase, TestIOStreamWebMixin):
  824. def _make_client_iostream(self):
  825. return SSLIOStream(socket.socket(), ssl_options=dict(cert_reqs=ssl.CERT_NONE))
  826. def get_app(self):
  827. return self.mixin_get_app()
  828. class TestIOStream(TestIOStreamMixin):
  829. def _make_server_iostream(self, connection, **kwargs):
  830. return IOStream(connection, **kwargs)
  831. def _make_client_iostream(self, connection, **kwargs):
  832. return IOStream(connection, **kwargs)
  833. class TestIOStreamSSL(TestIOStreamMixin):
  834. def _make_server_iostream(self, connection, **kwargs):
  835. ssl_ctx = ssl_options_to_context(_server_ssl_options(), server_side=True)
  836. connection = ssl_ctx.wrap_socket(
  837. connection,
  838. server_side=True,
  839. do_handshake_on_connect=False,
  840. )
  841. return SSLIOStream(connection, **kwargs)
  842. def _make_client_iostream(self, connection, **kwargs):
  843. return SSLIOStream(
  844. connection, ssl_options=dict(cert_reqs=ssl.CERT_NONE), **kwargs
  845. )
  846. # This will run some tests that are basically redundant but it's the
  847. # simplest way to make sure that it works to pass an SSLContext
  848. # instead of an ssl_options dict to the SSLIOStream constructor.
  849. class TestIOStreamSSLContext(TestIOStreamMixin):
  850. def _make_server_iostream(self, connection, **kwargs):
  851. context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
  852. context.load_cert_chain(
  853. os.path.join(os.path.dirname(__file__), "test.crt"),
  854. os.path.join(os.path.dirname(__file__), "test.key"),
  855. )
  856. connection = ssl_wrap_socket(
  857. connection, context, server_side=True, do_handshake_on_connect=False
  858. )
  859. return SSLIOStream(connection, **kwargs)
  860. def _make_client_iostream(self, connection, **kwargs):
  861. context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
  862. context.check_hostname = False
  863. context.verify_mode = ssl.CERT_NONE
  864. return SSLIOStream(connection, ssl_options=context, **kwargs)
  865. class TestIOStreamStartTLS(AsyncTestCase):
  866. def setUp(self):
  867. try:
  868. super().setUp()
  869. self.listener, self.port = bind_unused_port()
  870. self.server_stream = None
  871. self.server_accepted = Future() # type: Future[None]
  872. netutil.add_accept_handler(self.listener, self.accept)
  873. self.client_stream = IOStream(
  874. socket.socket()
  875. ) # type: typing.Optional[IOStream]
  876. self.io_loop.add_future(
  877. self.client_stream.connect(("127.0.0.1", self.port)), self.stop
  878. )
  879. self.wait()
  880. self.io_loop.add_future(self.server_accepted, self.stop)
  881. self.wait()
  882. except Exception as e:
  883. print(e)
  884. raise
  885. def tearDown(self):
  886. if self.server_stream is not None:
  887. self.server_stream.close()
  888. if self.client_stream is not None:
  889. self.client_stream.close()
  890. self.io_loop.remove_handler(self.listener.fileno())
  891. self.listener.close()
  892. super().tearDown()
  893. def accept(self, connection, address):
  894. if self.server_stream is not None:
  895. self.fail("should only get one connection")
  896. self.server_stream = IOStream(connection)
  897. self.server_accepted.set_result(None)
  898. @gen.coroutine
  899. def client_send_line(self, line):
  900. assert self.client_stream is not None
  901. self.client_stream.write(line)
  902. assert self.server_stream is not None
  903. recv_line = yield self.server_stream.read_until(b"\r\n")
  904. self.assertEqual(line, recv_line)
  905. @gen.coroutine
  906. def server_send_line(self, line):
  907. assert self.server_stream is not None
  908. self.server_stream.write(line)
  909. assert self.client_stream is not None
  910. recv_line = yield self.client_stream.read_until(b"\r\n")
  911. self.assertEqual(line, recv_line)
  912. def client_start_tls(self, ssl_options=None, server_hostname=None):
  913. assert self.client_stream is not None
  914. client_stream = self.client_stream
  915. self.client_stream = None
  916. return client_stream.start_tls(False, ssl_options, server_hostname)
  917. def server_start_tls(self, ssl_options=None):
  918. assert self.server_stream is not None
  919. server_stream = self.server_stream
  920. self.server_stream = None
  921. return server_stream.start_tls(True, ssl_options)
  922. @gen_test
  923. def test_start_tls_smtp(self):
  924. # This flow is simplified from RFC 3207 section 5.
  925. # We don't really need all of this, but it helps to make sure
  926. # that after realistic back-and-forth traffic the buffers end up
  927. # in a sane state.
  928. yield self.server_send_line(b"220 mail.example.com ready\r\n")
  929. yield self.client_send_line(b"EHLO mail.example.com\r\n")
  930. yield self.server_send_line(b"250-mail.example.com welcome\r\n")
  931. yield self.server_send_line(b"250 STARTTLS\r\n")
  932. yield self.client_send_line(b"STARTTLS\r\n")
  933. yield self.server_send_line(b"220 Go ahead\r\n")
  934. client_future = self.client_start_tls(dict(cert_reqs=ssl.CERT_NONE))
  935. server_future = self.server_start_tls(_server_ssl_options())
  936. self.client_stream = yield client_future
  937. self.server_stream = yield server_future
  938. self.assertTrue(isinstance(self.client_stream, SSLIOStream))
  939. self.assertTrue(isinstance(self.server_stream, SSLIOStream))
  940. yield self.client_send_line(b"EHLO mail.example.com\r\n")
  941. yield self.server_send_line(b"250 mail.example.com welcome\r\n")
  942. @gen_test
  943. def test_handshake_fail(self):
  944. server_future = self.server_start_tls(_server_ssl_options())
  945. # Certificates are verified with the default configuration.
  946. with ExpectLog(gen_log, "SSL Error"):
  947. client_future = self.client_start_tls(server_hostname="localhost")
  948. with self.assertRaises(ssl.SSLError):
  949. yield client_future
  950. with self.assertRaises((ssl.SSLError, socket.error)):
  951. yield server_future
  952. @gen_test
  953. def test_check_hostname(self):
  954. # Test that server_hostname parameter to start_tls is being used.
  955. server_future = self.server_start_tls(_server_ssl_options())
  956. with ExpectLog(gen_log, "SSL Error"):
  957. client_future = self.client_start_tls(
  958. ssl.create_default_context(), server_hostname="127.0.0.1"
  959. )
  960. with self.assertRaises(ssl.SSLError):
  961. # The client fails to connect with an SSL error.
  962. yield client_future
  963. with self.assertRaises(Exception):
  964. # The server fails to connect, but the exact error is unspecified.
  965. yield server_future
  966. @gen_test
  967. def test_typed_memoryview(self):
  968. # Test support of memoryviews with an item size greater than 1 byte.
  969. buf = memoryview(bytes(80)).cast("L")
  970. assert self.server_stream is not None
  971. yield self.server_stream.write(buf)
  972. assert self.client_stream is not None
  973. # This will timeout if the calculation of the buffer size is incorrect
  974. recv = yield self.client_stream.read_bytes(buf.nbytes)
  975. self.assertEqual(bytes(recv), bytes(buf))
  976. class WaitForHandshakeTest(AsyncTestCase):
  977. @gen.coroutine
  978. def connect_to_server(self, server_cls):
  979. server = client = None
  980. try:
  981. sock, port = bind_unused_port()
  982. server = server_cls(ssl_options=_server_ssl_options())
  983. server.add_socket(sock)
  984. ssl_ctx = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
  985. ssl_ctx.check_hostname = False
  986. ssl_ctx.verify_mode = ssl.CERT_NONE
  987. # These tests fail with ConnectionAbortedErrors with TLS
  988. # 1.3 on windows python 3.7.4 (which includes an upgrade
  989. # to openssl 1.1.c. Other platforms might be affected with
  990. # newer openssl too). Disable it until we figure out
  991. # what's up.
  992. # Update 2021-12-28: Still happening with Python 3.10 on
  993. # Windows. OP_NO_TLSv1_3 now raises a DeprecationWarning.
  994. with ignore_deprecation():
  995. ssl_ctx.options |= getattr(ssl, "OP_NO_TLSv1_3", 0)
  996. client = SSLIOStream(socket.socket(), ssl_options=ssl_ctx)
  997. yield client.connect(("127.0.0.1", port))
  998. self.assertIsNotNone(client.socket.cipher())
  999. finally:
  1000. if server is not None:
  1001. server.stop()
  1002. if client is not None:
  1003. client.close()
  1004. @gen_test
  1005. def test_wait_for_handshake_future(self):
  1006. test = self
  1007. handshake_future = Future() # type: Future[None]
  1008. class TestServer(TCPServer):
  1009. def handle_stream(self, stream, address):
  1010. test.assertIsNone(stream.socket.cipher())
  1011. test.io_loop.spawn_callback(self.handle_connection, stream)
  1012. @gen.coroutine
  1013. def handle_connection(self, stream):
  1014. yield stream.wait_for_handshake()
  1015. handshake_future.set_result(None)
  1016. yield self.connect_to_server(TestServer)
  1017. yield handshake_future
  1018. @gen_test
  1019. def test_wait_for_handshake_already_waiting_error(self):
  1020. test = self
  1021. handshake_future = Future() # type: Future[None]
  1022. class TestServer(TCPServer):
  1023. @gen.coroutine
  1024. def handle_stream(self, stream, address):
  1025. fut = stream.wait_for_handshake()
  1026. test.assertRaises(RuntimeError, stream.wait_for_handshake)
  1027. yield fut
  1028. handshake_future.set_result(None)
  1029. yield self.connect_to_server(TestServer)
  1030. yield handshake_future
  1031. @gen_test
  1032. def test_wait_for_handshake_already_connected(self):
  1033. handshake_future = Future() # type: Future[None]
  1034. class TestServer(TCPServer):
  1035. @gen.coroutine
  1036. def handle_stream(self, stream, address):
  1037. yield stream.wait_for_handshake()
  1038. yield stream.wait_for_handshake()
  1039. handshake_future.set_result(None)
  1040. yield self.connect_to_server(TestServer)
  1041. yield handshake_future
  1042. class TestIOStreamCheckHostname(AsyncTestCase):
  1043. # This test ensures that hostname checks are working correctly after
  1044. # #3337 revealed that we have no test coverage in this area, and we
  1045. # removed a manual hostname check that was needed only for very old
  1046. # versions of python.
  1047. def setUp(self):
  1048. super().setUp()
  1049. self.listener, self.port = bind_unused_port()
  1050. def accept_callback(connection, address):
  1051. ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
  1052. ssl_ctx.load_cert_chain(
  1053. os.path.join(os.path.dirname(__file__), "test.crt"),
  1054. os.path.join(os.path.dirname(__file__), "test.key"),
  1055. )
  1056. connection = ssl_ctx.wrap_socket(
  1057. connection,
  1058. server_side=True,
  1059. do_handshake_on_connect=False,
  1060. )
  1061. SSLIOStream(connection)
  1062. netutil.add_accept_handler(self.listener, accept_callback)
  1063. # Our self-signed cert is its own CA. We have to pass the CA check before
  1064. # the hostname check will be performed.
  1065. self.client_ssl_ctx = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
  1066. self.client_ssl_ctx.load_verify_locations(
  1067. os.path.join(os.path.dirname(__file__), "test.crt")
  1068. )
  1069. def tearDown(self):
  1070. self.io_loop.remove_handler(self.listener.fileno())
  1071. self.listener.close()
  1072. super().tearDown()
  1073. @gen_test
  1074. async def test_match(self):
  1075. stream = SSLIOStream(socket.socket(), ssl_options=self.client_ssl_ctx)
  1076. await stream.connect(
  1077. ("127.0.0.1", self.port),
  1078. server_hostname="foo.example.com",
  1079. )
  1080. stream.close()
  1081. @gen_test
  1082. async def test_no_match(self):
  1083. stream = SSLIOStream(socket.socket(), ssl_options=self.client_ssl_ctx)
  1084. with ExpectLog(
  1085. gen_log,
  1086. ".*alert bad certificate",
  1087. level=logging.WARNING,
  1088. required=platform.system() != "Windows",
  1089. ):
  1090. with self.assertRaises(ssl.SSLCertVerificationError):
  1091. with ExpectLog(
  1092. gen_log,
  1093. ".*(certificate verify failed: Hostname mismatch)",
  1094. level=logging.WARNING,
  1095. ):
  1096. await stream.connect(
  1097. ("127.0.0.1", self.port),
  1098. server_hostname="bar.example.com",
  1099. )
  1100. # The server logs a warning while cleaning up the failed connection.
  1101. # Unfortunately there's no good hook to wait for this logging.
  1102. # It doesn't seem to happen on windows; I'm not sure why.
  1103. if platform.system() != "Windows":
  1104. await asyncio.sleep(0.1)
  1105. @gen_test
  1106. async def test_check_disabled(self):
  1107. # check_hostname can be set to false and the connection will succeed even though it doesn't
  1108. # have the right hostname.
  1109. self.client_ssl_ctx.check_hostname = False
  1110. stream = SSLIOStream(socket.socket(), ssl_options=self.client_ssl_ctx)
  1111. await stream.connect(
  1112. ("127.0.0.1", self.port),
  1113. server_hostname="bar.example.com",
  1114. )
  1115. @skipIfNonUnix
  1116. class TestPipeIOStream(TestReadWriteMixin, AsyncTestCase):
  1117. @gen.coroutine
  1118. def make_iostream_pair(self, **kwargs):
  1119. r, w = os.pipe()
  1120. return PipeIOStream(r, **kwargs), PipeIOStream(w, **kwargs)
  1121. @gen_test
  1122. def test_pipe_iostream(self):
  1123. rs, ws = yield self.make_iostream_pair()
  1124. ws.write(b"hel")
  1125. ws.write(b"lo world")
  1126. data = yield rs.read_until(b" ")
  1127. self.assertEqual(data, b"hello ")
  1128. data = yield rs.read_bytes(3)
  1129. self.assertEqual(data, b"wor")
  1130. ws.close()
  1131. data = yield rs.read_until_close()
  1132. self.assertEqual(data, b"ld")
  1133. rs.close()
  1134. @gen_test
  1135. def test_pipe_iostream_big_write(self):
  1136. rs, ws = yield self.make_iostream_pair()
  1137. NUM_BYTES = 1048576
  1138. # Write 1MB of data, which should fill the buffer
  1139. ws.write(b"1" * NUM_BYTES)
  1140. data = yield rs.read_bytes(NUM_BYTES)
  1141. self.assertEqual(data, b"1" * NUM_BYTES)
  1142. ws.close()
  1143. rs.close()
  1144. class TestStreamBuffer(unittest.TestCase):
  1145. """
  1146. Unit tests for the private _StreamBuffer class.
  1147. """
  1148. def setUp(self):
  1149. self.random = random.Random(42)
  1150. def to_bytes(self, b):
  1151. if isinstance(b, (bytes, bytearray)):
  1152. return bytes(b)
  1153. elif isinstance(b, memoryview):
  1154. return b.tobytes() # For py2
  1155. else:
  1156. raise TypeError(b)
  1157. def make_streambuffer(self, large_buf_threshold=10):
  1158. buf = _StreamBuffer()
  1159. assert buf._large_buf_threshold
  1160. buf._large_buf_threshold = large_buf_threshold
  1161. return buf
  1162. def check_peek(self, buf, expected):
  1163. size = 1
  1164. while size < 2 * len(expected):
  1165. got = self.to_bytes(buf.peek(size))
  1166. self.assertTrue(got) # Not empty
  1167. self.assertLessEqual(len(got), size)
  1168. self.assertTrue(expected.startswith(got), (expected, got))
  1169. size = (size * 3 + 1) // 2
  1170. def check_append_all_then_skip_all(self, buf, objs, input_type):
  1171. self.assertEqual(len(buf), 0)
  1172. expected = b""
  1173. for o in objs:
  1174. expected += o
  1175. buf.append(input_type(o))
  1176. self.assertEqual(len(buf), len(expected))
  1177. self.check_peek(buf, expected)
  1178. while expected:
  1179. n = self.random.randrange(1, len(expected) + 1)
  1180. expected = expected[n:]
  1181. buf.advance(n)
  1182. self.assertEqual(len(buf), len(expected))
  1183. self.check_peek(buf, expected)
  1184. self.assertEqual(len(buf), 0)
  1185. def test_small(self):
  1186. objs = [b"12", b"345", b"67", b"89a", b"bcde", b"fgh", b"ijklmn"]
  1187. buf = self.make_streambuffer()
  1188. self.check_append_all_then_skip_all(buf, objs, bytes)
  1189. buf = self.make_streambuffer()
  1190. self.check_append_all_then_skip_all(buf, objs, bytearray)
  1191. buf = self.make_streambuffer()
  1192. self.check_append_all_then_skip_all(buf, objs, memoryview)
  1193. # Test internal algorithm
  1194. buf = self.make_streambuffer(10)
  1195. for i in range(9):
  1196. buf.append(b"x")
  1197. self.assertEqual(len(buf._buffers), 1)
  1198. for i in range(9):
  1199. buf.append(b"x")
  1200. self.assertEqual(len(buf._buffers), 2)
  1201. buf.advance(10)
  1202. self.assertEqual(len(buf._buffers), 1)
  1203. buf.advance(8)
  1204. self.assertEqual(len(buf._buffers), 0)
  1205. self.assertEqual(len(buf), 0)
  1206. def test_large(self):
  1207. objs = [
  1208. b"12" * 5,
  1209. b"345" * 2,
  1210. b"67" * 20,
  1211. b"89a" * 12,
  1212. b"bcde" * 1,
  1213. b"fgh" * 7,
  1214. b"ijklmn" * 2,
  1215. ]
  1216. buf = self.make_streambuffer()
  1217. self.check_append_all_then_skip_all(buf, objs, bytes)
  1218. buf = self.make_streambuffer()
  1219. self.check_append_all_then_skip_all(buf, objs, bytearray)
  1220. buf = self.make_streambuffer()
  1221. self.check_append_all_then_skip_all(buf, objs, memoryview)
  1222. # Test internal algorithm
  1223. buf = self.make_streambuffer(10)
  1224. for i in range(3):
  1225. buf.append(b"x" * 11)
  1226. self.assertEqual(len(buf._buffers), 3)
  1227. buf.append(b"y")
  1228. self.assertEqual(len(buf._buffers), 4)
  1229. buf.append(b"z")
  1230. self.assertEqual(len(buf._buffers), 4)
  1231. buf.advance(33)
  1232. self.assertEqual(len(buf._buffers), 1)
  1233. buf.advance(2)
  1234. self.assertEqual(len(buf._buffers), 0)
  1235. self.assertEqual(len(buf), 0)