requesthelper.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. """
  4. Helpers related to HTTP requests, used by tests.
  5. """
  6. from __future__ import division, absolute_import
  7. __all__ = ['DummyChannel', 'DummyRequest']
  8. from io import BytesIO
  9. from zope.interface import implementer, verify
  10. from twisted.python.compat import intToBytes
  11. from twisted.python.deprecate import deprecated
  12. from incremental import Version
  13. from twisted.internet.defer import Deferred
  14. from twisted.internet.address import IPv4Address, IPv6Address
  15. from twisted.internet.interfaces import ISSLTransport, IAddress
  16. from twisted.trial import unittest
  17. from twisted.web.http_headers import Headers
  18. from twisted.web.resource import Resource
  19. from twisted.web.server import NOT_DONE_YET, Session, Site
  20. from twisted.web._responses import FOUND
  21. textLinearWhitespaceComponents = [
  22. u"Foo%sbar" % (lw,) for lw in
  23. [u'\r', u'\n', u'\r\n']
  24. ]
  25. sanitizedText = "Foo bar"
  26. bytesLinearWhitespaceComponents = [
  27. component.encode('ascii') for component in
  28. textLinearWhitespaceComponents
  29. ]
  30. sanitizedBytes = sanitizedText.encode('ascii')
  31. @implementer(IAddress)
  32. class NullAddress(object):
  33. """
  34. A null implementation of L{IAddress}.
  35. """
  36. class DummyChannel:
  37. class TCP:
  38. port = 80
  39. disconnected = False
  40. def __init__(self, peer=None):
  41. if peer is None:
  42. peer = IPv4Address("TCP", '192.168.1.1', 12344)
  43. self._peer = peer
  44. self.written = BytesIO()
  45. self.producers = []
  46. def getPeer(self):
  47. return self._peer
  48. def write(self, data):
  49. if not isinstance(data, bytes):
  50. raise TypeError("Can only write bytes to a transport, not %r" % (data,))
  51. self.written.write(data)
  52. def writeSequence(self, iovec):
  53. for data in iovec:
  54. self.write(data)
  55. def getHost(self):
  56. return IPv4Address("TCP", '10.0.0.1', self.port)
  57. def registerProducer(self, producer, streaming):
  58. self.producers.append((producer, streaming))
  59. def unregisterProducer(self):
  60. pass
  61. def loseConnection(self):
  62. self.disconnected = True
  63. @implementer(ISSLTransport)
  64. class SSL(TCP):
  65. pass
  66. site = Site(Resource())
  67. def __init__(self, peer=None):
  68. self.transport = self.TCP(peer)
  69. def requestDone(self, request):
  70. pass
  71. def writeHeaders(self, version, code, reason, headers):
  72. response_line = version + b" " + code + b" " + reason + b"\r\n"
  73. headerSequence = [response_line]
  74. headerSequence.extend(
  75. name + b': ' + value + b"\r\n" for name, value in headers
  76. )
  77. headerSequence.append(b"\r\n")
  78. self.transport.writeSequence(headerSequence)
  79. def getPeer(self):
  80. return self.transport.getPeer()
  81. def getHost(self):
  82. return self.transport.getHost()
  83. def registerProducer(self, producer, streaming):
  84. self.transport.registerProducer(producer, streaming)
  85. def unregisterProducer(self):
  86. self.transport.unregisterProducer()
  87. def write(self, data):
  88. self.transport.write(data)
  89. def writeSequence(self, iovec):
  90. self.transport.writeSequence(iovec)
  91. def loseConnection(self):
  92. self.transport.loseConnection()
  93. def endRequest(self):
  94. pass
  95. def isSecure(self):
  96. return isinstance(self.transport, self.SSL)
  97. class DummyRequest(object):
  98. """
  99. Represents a dummy or fake request. See L{twisted.web.server.Request}.
  100. @ivar _finishedDeferreds: L{None} or a C{list} of L{Deferreds} which will
  101. be called back with L{None} when C{finish} is called or which will be
  102. errbacked if C{processingFailed} is called.
  103. @type requestheaders: C{Headers}
  104. @ivar requestheaders: A Headers instance that stores values for all request
  105. headers.
  106. @type responseHeaders: C{Headers}
  107. @ivar responseHeaders: A Headers instance that stores values for all
  108. response headers.
  109. @type responseCode: C{int}
  110. @ivar responseCode: The response code which was passed to
  111. C{setResponseCode}.
  112. @type written: C{list} of C{bytes}
  113. @ivar written: The bytes which have been written to the request.
  114. """
  115. uri = b'http://dummy/'
  116. method = b'GET'
  117. client = None
  118. def registerProducer(self, prod, s):
  119. """
  120. Call an L{IPullProducer}'s C{resumeProducing} method in a
  121. loop until it unregisters itself.
  122. @param prod: The producer.
  123. @type prod: L{IPullProducer}
  124. @param s: Whether or not the producer is streaming.
  125. """
  126. # XXX: Handle IPushProducers
  127. self.go = 1
  128. while self.go:
  129. prod.resumeProducing()
  130. def unregisterProducer(self):
  131. self.go = 0
  132. def __init__(self, postpath, session=None, client=None):
  133. self.sitepath = []
  134. self.written = []
  135. self.finished = 0
  136. self.postpath = postpath
  137. self.prepath = []
  138. self.session = None
  139. self.protoSession = session or Session(0, self)
  140. self.args = {}
  141. self.requestHeaders = Headers()
  142. self.responseHeaders = Headers()
  143. self.responseCode = None
  144. self._finishedDeferreds = []
  145. self._serverName = b"dummy"
  146. self.clientproto = b"HTTP/1.0"
  147. def getAllHeaders(self):
  148. """
  149. Return dictionary mapping the names of all received headers to the last
  150. value received for each.
  151. Since this method does not return all header information,
  152. C{self.requestHeaders.getAllRawHeaders()} may be preferred.
  153. NOTE: This function is a direct copy of
  154. C{twisted.web.http.Request.getAllRawHeaders}.
  155. """
  156. headers = {}
  157. for k, v in self.requestHeaders.getAllRawHeaders():
  158. headers[k.lower()] = v[-1]
  159. return headers
  160. def getHeader(self, name):
  161. """
  162. Retrieve the value of a request header.
  163. @type name: C{bytes}
  164. @param name: The name of the request header for which to retrieve the
  165. value. Header names are compared case-insensitively.
  166. @rtype: C{bytes} or L{None}
  167. @return: The value of the specified request header.
  168. """
  169. return self.requestHeaders.getRawHeaders(name.lower(), [None])[0]
  170. def setHeader(self, name, value):
  171. """TODO: make this assert on write() if the header is content-length
  172. """
  173. self.responseHeaders.addRawHeader(name, value)
  174. def getSession(self):
  175. if self.session:
  176. return self.session
  177. assert not self.written, "Session cannot be requested after data has been written."
  178. self.session = self.protoSession
  179. return self.session
  180. def render(self, resource):
  181. """
  182. Render the given resource as a response to this request.
  183. This implementation only handles a few of the most common behaviors of
  184. resources. It can handle a render method that returns a string or
  185. C{NOT_DONE_YET}. It doesn't know anything about the semantics of
  186. request methods (eg HEAD) nor how to set any particular headers.
  187. Basically, it's largely broken, but sufficient for some tests at least.
  188. It should B{not} be expanded to do all the same stuff L{Request} does.
  189. Instead, L{DummyRequest} should be phased out and L{Request} (or some
  190. other real code factored in a different way) used.
  191. """
  192. result = resource.render(self)
  193. if result is NOT_DONE_YET:
  194. return
  195. self.write(result)
  196. self.finish()
  197. def write(self, data):
  198. if not isinstance(data, bytes):
  199. raise TypeError("write() only accepts bytes")
  200. self.written.append(data)
  201. def notifyFinish(self):
  202. """
  203. Return a L{Deferred} which is called back with L{None} when the request
  204. is finished. This will probably only work if you haven't called
  205. C{finish} yet.
  206. """
  207. finished = Deferred()
  208. self._finishedDeferreds.append(finished)
  209. return finished
  210. def finish(self):
  211. """
  212. Record that the request is finished and callback and L{Deferred}s
  213. waiting for notification of this.
  214. """
  215. self.finished = self.finished + 1
  216. if self._finishedDeferreds is not None:
  217. observers = self._finishedDeferreds
  218. self._finishedDeferreds = None
  219. for obs in observers:
  220. obs.callback(None)
  221. def processingFailed(self, reason):
  222. """
  223. Errback and L{Deferreds} waiting for finish notification.
  224. """
  225. if self._finishedDeferreds is not None:
  226. observers = self._finishedDeferreds
  227. self._finishedDeferreds = None
  228. for obs in observers:
  229. obs.errback(reason)
  230. def addArg(self, name, value):
  231. self.args[name] = [value]
  232. def setResponseCode(self, code, message=None):
  233. """
  234. Set the HTTP status response code, but takes care that this is called
  235. before any data is written.
  236. """
  237. assert not self.written, "Response code cannot be set after data has been written: %s." % "@@@@".join(self.written)
  238. self.responseCode = code
  239. self.responseMessage = message
  240. def setLastModified(self, when):
  241. assert not self.written, "Last-Modified cannot be set after data has been written: %s." % "@@@@".join(self.written)
  242. def setETag(self, tag):
  243. assert not self.written, "ETag cannot be set after data has been written: %s." % "@@@@".join(self.written)
  244. def getClientIP(self):
  245. """
  246. Return the IPv4 address of the client which made this request, if there
  247. is one, otherwise L{None}.
  248. """
  249. if isinstance(self.client, (IPv4Address, IPv6Address)):
  250. return self.client.host
  251. return None
  252. def getClientAddress(self):
  253. """
  254. Return the L{IAddress} of the client that made this request.
  255. @return: an address.
  256. @rtype: an L{IAddress} provider.
  257. """
  258. if self.client is None:
  259. return NullAddress()
  260. return self.client
  261. def getRequestHostname(self):
  262. """
  263. Get a dummy hostname associated to the HTTP request.
  264. @rtype: C{bytes}
  265. @returns: a dummy hostname
  266. """
  267. return self._serverName
  268. def getHost(self):
  269. """
  270. Get a dummy transport's host.
  271. @rtype: C{IPv4Address}
  272. @returns: a dummy transport's host
  273. """
  274. return IPv4Address('TCP', '127.0.0.1', 80)
  275. def setHost(self, host, port, ssl=0):
  276. """
  277. Change the host and port the request thinks it's using.
  278. @type host: C{bytes}
  279. @param host: The value to which to change the host header.
  280. @type ssl: C{bool}
  281. @param ssl: A flag which, if C{True}, indicates that the request is
  282. considered secure (if C{True}, L{isSecure} will return C{True}).
  283. """
  284. self._forceSSL = ssl # set first so isSecure will work
  285. if self.isSecure():
  286. default = 443
  287. else:
  288. default = 80
  289. if port == default:
  290. hostHeader = host
  291. else:
  292. hostHeader = host + b":" + intToBytes(port)
  293. self.requestHeaders.addRawHeader(b"host", hostHeader)
  294. def redirect(self, url):
  295. """
  296. Utility function that does a redirect.
  297. The request should have finish() called after this.
  298. """
  299. self.setResponseCode(FOUND)
  300. self.setHeader(b"location", url)
  301. DummyRequest.getClientIP = deprecated(
  302. Version('Twisted', 18, 4, 0),
  303. replacement="getClientAddress",
  304. )(DummyRequest.getClientIP)
  305. class DummyRequestTests(unittest.SynchronousTestCase):
  306. """
  307. Tests for L{DummyRequest}.
  308. """
  309. def test_getClientIPDeprecated(self):
  310. """
  311. L{DummyRequest.getClientIP} is deprecated in favor of
  312. L{DummyRequest.getClientAddress}
  313. """
  314. request = DummyRequest([])
  315. request.getClientIP()
  316. warnings = self.flushWarnings(
  317. offendingFunctions=[self.test_getClientIPDeprecated])
  318. self.assertEqual(1, len(warnings))
  319. [warning] = warnings
  320. self.assertEqual(warning.get("category"), DeprecationWarning)
  321. self.assertEqual(
  322. warning.get("message"),
  323. ("twisted.web.test.requesthelper.DummyRequest.getClientIP "
  324. "was deprecated in Twisted 18.4.0; "
  325. "please use getClientAddress instead"),
  326. )
  327. def test_getClientIPSupportsIPv6(self):
  328. """
  329. L{DummyRequest.getClientIP} supports IPv6 addresses, just like
  330. L{twisted.web.http.Request.getClientIP}.
  331. """
  332. request = DummyRequest([])
  333. client = IPv6Address("TCP", "::1", 12345)
  334. request.client = client
  335. self.assertEqual("::1", request.getClientIP())
  336. def test_getClientAddressWithoutClient(self):
  337. """
  338. L{DummyRequest.getClientAddress} returns an L{IAddress}
  339. provider no C{client} has been set.
  340. """
  341. request = DummyRequest([])
  342. null = request.getClientAddress()
  343. verify.verifyObject(IAddress, null)
  344. def test_getClientAddress(self):
  345. """
  346. L{DummyRequest.getClientAddress} returns the C{client}.
  347. """
  348. request = DummyRequest([])
  349. client = IPv4Address("TCP", "127.0.0.1", 12345)
  350. request.client = client
  351. address = request.getClientAddress()
  352. self.assertIs(address, client)