Ticket #5004: replace-string-module-web-5004-7.patch

File replace-string-module-web-5004-7.patch, 10.5 KB (added by Jonathan Ballet, 8 years ago)
  • twisted/web/test/requesthelper.py

    diff --git twisted/web/test/requesthelper.py twisted/web/test/requesthelper.py
    index 88c6e9f..e1738fd 100644
    class DummyRequest(object): 
    118118        self.responseCode = None
    119119        self.headers = {}
    120120        self._finishedDeferreds = []
    121 
     121        self._serverName = b"dummy"
     122        self.clientproto = b"HTTP/1.0"
    122123
    123124    def getHeader(self, name):
    124125        """
    class DummyRequest(object): 
    133134        """
    134135        return self.headers.get(name.lower(), None)
    135136
     137    def getAllHeaders(self):
     138        """
     139        Retrieve all the values of the request headers as a dictionary.
     140        """
     141        return self.headers
    136142
    137143    def setHeader(self, name, value):
    138144        """TODO: make this assert on write() if the header is content-length
    class DummyRequest(object): 
    237243        if isinstance(self.client, IPv4Address):
    238244            return self.client.host
    239245        return None
     246
     247
     248    def getRequestHostname(self):
     249        """
     250        Get a dummy hostname associated to the HTTP request.
     251
     252        @rtype: C{bytes}
     253        @returns: a dummy hostname
     254        """
     255        return self._serverName
     256
     257
     258    def getHost(self):
     259        """
     260        Get a dummy transport's host.
     261
     262        @rtype: C{IPv4Address}
     263        @returns: a dummy transport's host
     264        """
     265        return IPv4Address('TCP', '127.0.0.1', 80)
     266
     267
     268    def getClient(self):
     269        """
     270        Stub to get the client doing the HTTP request.
     271        This merely just ensures that this method exists here. Feel free to
     272        extend it.
     273        """
     274        pass
  • twisted/web/test/test_cgi.py

    diff --git twisted/web/test/test_cgi.py twisted/web/test/test_cgi.py
    index db63211..a55f617 100755
    class CGI(unittest.TestCase): 
    8787        return self.p.getHost().port
    8888
    8989    def tearDown(self):
    90         if self.p:
     90        if getattr(self, 'p', None):
    9191            return self.p.stopListening()
    9292
    9393
    class CGI(unittest.TestCase): 
    214214        self.assertEqual(res, "readallinput ok%s" % os.linesep)
    215215
    216216
     217    def test_useReactorArgument(self):
     218        """
     219        L{twcgi.FilteredScript.runProcess} uses the reactor passed as an
     220        argument to the constructor.
     221        """
     222        class FakeReactor:
     223            called = False
     224            def spawnProcess(self, *args, **kwargs):
     225                self.called = True
     226
     227        fakeReactor = FakeReactor()
     228        request = DummyRequest(['a', 'b'])
     229        resource = twcgi.FilteredScript("dummy-file", reactor=fakeReactor)
     230        _render(resource, request)
     231
     232        self.assertTrue(fakeReactor.called)
     233
     234
     235
     236class CGIScriptTests(unittest.TestCase):
     237    """
     238    Tests for L{twcgi.CGIScript}.
     239    """
     240
     241    def test_pathInfo(self):
     242        """
     243        L{twcgi.CGIScript.render} sets the process environment I{PATH_INFO} from
     244        the request path.
     245        """
     246        class FakeReactor:
     247            def spawnProcess(self, process, filename, args, env, wdir):
     248                self.process_env = env
     249
     250        _reactor = FakeReactor()
     251        resource = twcgi.CGIScript(self.mktemp(), reactor=_reactor)
     252        request = DummyRequest(['a', 'b'])
     253        _render(resource, request)
     254
     255        self.assertIn("PATH_INFO", _reactor.process_env)
     256        self.assertEqual(_reactor.process_env["PATH_INFO"],
     257                         "/a/b")
     258
     259
    217260
    218261class CGIDirectoryTests(unittest.TestCase):
    219262    """
  • twisted/web/test/test_util.py

    diff --git twisted/web/test/test_util.py twisted/web/test/test_util.py
    index ac628e7..893571b 100644
    from twisted.web.error import FlattenerError 
    1313from twisted.web.util import (
    1414    redirectTo, _SourceLineElement,
    1515    _SourceFragmentElement, _FrameElement, _StackElement,
    16     FailureElement, formatFailure, DeferredResource)
     16    FailureElement, formatFailure, DeferredResource, htmlIndent)
    1717
    1818from twisted.web.http import FOUND
    1919from twisted.web.server import Request
    class DeferredResourceTests(TestCase): 
    422422        deferredResource = DeferredResource(defer.succeed(result))
    423423        deferredResource.render(request)
    424424        self.assertEqual(rendered, [result])
     425
     426
     427
     428class HtmlIndentTests(TestCase):
     429    """
     430    Tests for L{htmlIndent}
     431    """
     432
     433    def test_simpleInput(self):
     434        """
     435        L{htmlIndent} transparently process input with no special cases inside.
     436        """
     437        line = "foo bar"
     438        self.assertEqual(line, htmlIndent(line))
     439
     440
     441    def test_escapeHtml(self):
     442        """
     443        L{htmlIndent} escapes HTML from its input.
     444        """
     445        line = "<br />"
     446        self.assertEqual("&lt;br /&gt;", htmlIndent(line))
     447
     448
     449    def test_stripTrailingWhitespace(self):
     450        """
     451        L{htmlIndent} removes trailing whitespaces from its input.
     452        """
     453        line = " foo bar  "
     454        self.assertEqual(" foo bar", htmlIndent(line))
     455
     456
     457    def test_forceSpacingFromSpaceCharacters(self):
     458        """
     459        If L{htmlIndent} detects consecutive space characters, it forces the
     460        rendering by substituting unbreakable space.
     461        """
     462        line = "  foo  bar"
     463        self.assertEqual("&nbsp;foo&nbsp;bar", htmlIndent(line))
     464
     465
     466    def test_indentFromTabCharacters(self):
     467        """
     468        L{htmlIndent} replaces tab characters by unbreakable spaces.
     469        """
     470        line = "\tfoo"
     471        self.assertEqual("&nbsp; &nbsp; &nbsp; &nbsp; foo", htmlIndent(line))
  • twisted/web/twcgi.py

    diff --git twisted/web/twcgi.py twisted/web/twcgi.py
    index 5ab580d..015e712 100644
    I hold resource classes and helper classes that deal with CGI scripts. 
    88"""
    99
    1010# System Imports
    11 import string
    1211import os
    1312import urllib
    1413
    1514# Twisted Imports
    1615from twisted.web import http
    17 from twisted.internet import reactor, protocol
     16from twisted.internet import protocol
    1817from twisted.spread import pb
    1918from twisted.python import log, filepath
    2019from twisted.web import resource, server, static
    class CGIScript(resource.Resource): 
    5150    IPC with an external process with an unpleasant protocol.
    5251    """
    5352    isLeaf = 1
    54     def __init__(self, filename, registry=None):
     53    def __init__(self, filename, registry=None, reactor=None):
    5554        """
    5655        Initialize, with the name of a CGI script file.
    5756        """
    5857        self.filename = filename
     58        if reactor is None:
     59            # This installs a default reactor, if None was installed before.
     60            # We do a late import here, so that importing the current module
     61            # won't directly trigger installing a default reactor.
     62            from twisted.internet import reactor
     63        self._reactor = reactor
    5964
    6065
    6166    def render(self, request):
    class CGIScript(resource.Resource): 
    6873        @type request: L{twisted.web.http.Request}
    6974        @param request: An HTTP request.
    7075        """
    71         script_name = "/"+string.join(request.prepath, '/')
    72         serverName = string.split(request.getRequestHostname(), ':')[0]
     76        script_name = "/" + "/".join(request.prepath)
     77        serverName = request.getRequestHostname().split(':')[0]
    7378        env = {"SERVER_SOFTWARE":   server.version,
    7479               "SERVER_NAME":       serverName,
    7580               "GATEWAY_INTERFACE": "CGI/1.1",
    class CGIScript(resource.Resource): 
    8994            env['REMOTE_ADDR'] = ip
    9095        pp = request.postpath
    9196        if pp:
    92             env["PATH_INFO"] = "/"+string.join(pp, '/')
     97            env["PATH_INFO"] = "/" + "/".join(pp)
    9398
    9499        if hasattr(request, "content"):
    95100            # request.content is either a StringIO or a TemporaryFile, and
    class CGIScript(resource.Resource): 
    99104            request.content.seek(0,0)
    100105            env['CONTENT_LENGTH'] = str(length)
    101106
    102         qindex = string.find(request.uri, '?')
    103         if qindex != -1:
     107        try:
     108            qindex = request.uri.index('?')
     109        except ValueError: # '?' not found
     110            env['QUERY_STRING'] = ''
     111            qargs = []
     112        else:
    104113            qs = env['QUERY_STRING'] = request.uri[qindex+1:]
    105114            if '=' in qs:
    106115                qargs = []
    107116            else:
    108117                qargs = [urllib.unquote(x) for x in qs.split('+')]
    109         else:
    110             env['QUERY_STRING'] = ''
    111             qargs = []
    112118
    113119        # Propogate HTTP headers
    114120        for title, header in request.getAllHeaders().items():
    115             envname = string.upper(string.replace(title, '-', '_'))
     121            envname = title.replace('-', '_').upper()
    116122            if title not in ('content-type', 'content-length'):
    117123                envname = "HTTP_" + envname
    118124            env[envname] = header
    class CGIScript(resource.Resource): 
    143149            will get spawned.
    144150        """
    145151        p = CGIProcessProtocol(request)
    146         reactor.spawnProcess(p, self.filename, [self.filename] + qargs, env,
    147                              os.path.dirname(self.filename))
     152        self._reactor.spawnProcess(p, self.filename, [self.filename] + qargs,
     153                                   env, os.path.dirname(self.filename))
    148154
    149155
    150156
    class FilteredScript(CGIScript): 
    185191            will get spawned.
    186192        """
    187193        p = CGIProcessProtocol(request)
    188         reactor.spawnProcess(p, self.filter,
    189                              [self.filter, self.filename] + qargs, env,
    190                              os.path.dirname(self.filename))
     194        self._reactor.spawnProcess(p, self.filter,
     195                                   [self.filter, self.filename] + qargs, env,
     196                                   os.path.dirname(self.filename))
    191197
    192198
    193199
  • twisted/web/util.py

    diff --git twisted/web/util.py twisted/web/util.py
    index 0c6cdb6..2befc59 100644
    __all__ = [ 
    1212
    1313from cStringIO import StringIO
    1414import linecache
    15 import string
    1615import types
    1716
    18 from twisted.python.filepath import FilePath
    1917from twisted.python.reflect import fullyQualifiedName
    2018from twisted.python.deprecate import deprecatedModuleAttribute
    2119from twisted.python.versions import Version
    htmlReprTypes = {types.DictType: htmlDict, 
    200198
    201199
    202200def htmlIndent(snippetLine):
    203     ret = string.replace(string.replace(html.escape(string.rstrip(snippetLine)),
    204                                   '  ', '&nbsp;'),
    205                    '\t', '&nbsp; &nbsp; &nbsp; &nbsp; ')
     201    ret = html.escape(snippetLine.rstrip())\
     202            .replace('  ', '&nbsp;')\
     203            .replace('\t', '&nbsp; &nbsp; &nbsp; &nbsp; ')
    206204    return ret
    207205
    208206