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

File replace-string-module-web-5004-5.patch, 8.2 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..2d33db6 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        return self.headers
    136139
    137140    def setHeader(self, name, value):
    138141        """TODO: make this assert on write() if the header is content-length
    class DummyRequest(object): 
    237240        if isinstance(self.client, IPv4Address):
    238241            return self.client.host
    239242        return None
     243
     244
     245    def getRequestHostname(self):
     246        return self._serverName
     247
     248
     249    def getHost(self):
     250        return DummyChannel.TCP()
     251
     252
     253    def getClient(self):
     254        pass
  • twisted/web/test/test_cgi.py

    diff --git twisted/web/test/test_cgi.py twisted/web/test/test_cgi.py
    index db63211..74040f3 100755
    class CGI(unittest.TestCase): 
    214214        self.assertEqual(res, "readallinput ok%s" % os.linesep)
    215215
    216216
     217class CGIScriptTests(unittest.TestCase):
     218    """
     219    Tests for L{twcgi.CGIScript}.
     220    """
     221
     222
     223    def test_pathInfo(self):
     224        """
     225        L{twcgi.CGIScript.render} sets the process environment I{PATH_INFO} from
     226        the request path.
     227        """
     228        class FakeReactor:
     229            def spawnProcess(self, process, filename, args, env, wdir):
     230                self.process_env = env
     231
     232        _reactor = FakeReactor()
     233        resource = twcgi.CGIScript(self.mktemp(), _reactor=_reactor)
     234        request = DummyRequest(['a', 'b'])
     235        _render(resource, request)
     236
     237        self.assertIn("PATH_INFO", _reactor.process_env)
     238        self.assertEqual(_reactor.process_env["PATH_INFO"],
     239                         "/a/b")
     240
    217241
    218242class CGIDirectoryTests(unittest.TestCase):
    219243    """
  • twisted/web/test/test_util.py

    diff --git twisted/web/test/test_util.py twisted/web/test/test_util.py
    index ac628e7..1ba9d19 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
     427class HtmlIndentTests(TestCase):
     428    """
     429    Tests for L{htmlIndent}
     430    """
     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..8f8613f 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
    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            _reactor = reactor
     60        self._reactor = _reactor
    5961
    6062
    6163    def render(self, request):
    class CGIScript(resource.Resource): 
    6870        @type request: L{twisted.web.http.Request}
    6971        @param request: An HTTP request.
    7072        """
    71         script_name = "/"+string.join(request.prepath, '/')
    72         serverName = string.split(request.getRequestHostname(), ':')[0]
     73        script_name = "/" + "/".join(request.prepath)
     74        serverName = request.getRequestHostname().split(':')[0]
    7375        env = {"SERVER_SOFTWARE":   server.version,
    7476               "SERVER_NAME":       serverName,
    7577               "GATEWAY_INTERFACE": "CGI/1.1",
    class CGIScript(resource.Resource): 
    8991            env['REMOTE_ADDR'] = ip
    9092        pp = request.postpath
    9193        if pp:
    92             env["PATH_INFO"] = "/"+string.join(pp, '/')
     94            env["PATH_INFO"] = "/" + "/".join(pp)
    9395
    9496        if hasattr(request, "content"):
    9597            # request.content is either a StringIO or a TemporaryFile, and
    class CGIScript(resource.Resource): 
    99101            request.content.seek(0,0)
    100102            env['CONTENT_LENGTH'] = str(length)
    101103
    102         qindex = string.find(request.uri, '?')
    103         if qindex != -1:
     104        try:
     105            qindex = request.uri.index('?')
     106        except ValueError: # '?' not found
     107            env['QUERY_STRING'] = ''
     108            qargs = []
     109        else:
    104110            qs = env['QUERY_STRING'] = request.uri[qindex+1:]
    105111            if '=' in qs:
    106112                qargs = []
    107113            else:
    108114                qargs = [urllib.unquote(x) for x in qs.split('+')]
    109         else:
    110             env['QUERY_STRING'] = ''
    111             qargs = []
    112115
    113116        # Propogate HTTP headers
    114117        for title, header in request.getAllHeaders().items():
    115             envname = string.upper(string.replace(title, '-', '_'))
     118            envname = title.replace('-', '_').upper()
    116119            if title not in ('content-type', 'content-length'):
    117120                envname = "HTTP_" + envname
    118121            env[envname] = header
    class CGIScript(resource.Resource): 
    143146            will get spawned.
    144147        """
    145148        p = CGIProcessProtocol(request)
    146         reactor.spawnProcess(p, self.filename, [self.filename] + qargs, env,
    147                              os.path.dirname(self.filename))
     149        self._reactor.spawnProcess(p, self.filename, [self.filename] + qargs,
     150                                   env, os.path.dirname(self.filename))
    148151
    149152
    150153
  • 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