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

File replace-string-module-web-5004-6.patch, 9.7 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..29d636c 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): 
    213213    def _testReadAllInput_1(self, res):
    214214        self.assertEqual(res, "readallinput ok%s" % os.linesep)
    215215
     216    def test_useReactorArgument(self):
     217        """
     218        L{twcgi.FilteredScript.runProcess} uses the reactor passed as an
     219        argument to the constructor.
     220        """
     221        class FakeReactor:
     222            called = False
     223            def spawnProcess(self, *args, **kwargs):
     224                self.called = True
     225
     226        _fake_reactor = FakeReactor()
     227        request = DummyRequest(['a', 'b'])
     228        resource = twcgi.FilteredScript("dummy-file", reactor=_fake_reactor)
     229        _render(resource, request)
     230
     231        self.assertTrue(_fake_reactor.called)
     232
     233
     234class CGIScriptTests(unittest.TestCase):
     235    """
     236    Tests for L{twcgi.CGIScript}.
     237    """
     238
     239
     240    def test_pathInfo(self):
     241        """
     242        L{twcgi.CGIScript.render} sets the process environment I{PATH_INFO} from
     243        the request path.
     244        """
     245        class FakeReactor:
     246            def spawnProcess(self, process, filename, args, env, wdir):
     247                self.process_env = env
     248
     249        _reactor = FakeReactor()
     250        resource = twcgi.CGIScript(self.mktemp(), reactor=_reactor)
     251        request = DummyRequest(['a', 'b'])
     252        _render(resource, request)
     253
     254        self.assertIn("PATH_INFO", _reactor.process_env)
     255        self.assertEqual(_reactor.process_env["PATH_INFO"],
     256                         "/a/b")
    216257
    217258
    218259class CGIDirectoryTests(unittest.TestCase):
  • 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..dd6c421 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, '?')
     107        qindex = request.uri.find('?')
    103108        if qindex != -1:
    104109            qs = env['QUERY_STRING'] = request.uri[qindex+1:]
    105110            if '=' in qs:
    class CGIScript(resource.Resource): 
    112117
    113118        # Propogate HTTP headers
    114119        for title, header in request.getAllHeaders().items():
    115             envname = string.upper(string.replace(title, '-', '_'))
     120            envname = title.replace('-', '_').upper()
    116121            if title not in ('content-type', 'content-length'):
    117122                envname = "HTTP_" + envname
    118123            env[envname] = header
    class CGIScript(resource.Resource): 
    143148            will get spawned.
    144149        """
    145150        p = CGIProcessProtocol(request)
    146         reactor.spawnProcess(p, self.filename, [self.filename] + qargs, env,
    147                              os.path.dirname(self.filename))
     151        self._reactor.spawnProcess(p, self.filename, [self.filename] + qargs,
     152                                   env, os.path.dirname(self.filename))
    148153
    149154
    150155
    class FilteredScript(CGIScript): 
    185190            will get spawned.
    186191        """
    187192        p = CGIProcessProtocol(request)
    188         reactor.spawnProcess(p, self.filter,
    189                              [self.filter, self.filename] + qargs, env,
    190                              os.path.dirname(self.filename))
     193        self._reactor.spawnProcess(p, self.filter,
     194                                   [self.filter, self.filename] + qargs, env,
     195                                   os.path.dirname(self.filename))
    191196
    192197
    193198
  • 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