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

File replace-string-module-web-5004.patch-2, 8.2 KB (added by Jonathan Ballet, 9 years ago)
Line 
1diff --git twisted/web/server.py twisted/web/server.py
2index bc3f07c..2300d77 100644
3--- twisted/web/server.py
4+++ twisted/web/server.py
5@@ -10,8 +10,6 @@ infrastructure.
6 from __future__ import division, absolute_import
7 
8 import warnings
9-import string
10-import types
11 import copy
12 import os
13 try:
14diff --git twisted/web/test/requesthelper.py twisted/web/test/requesthelper.py
15index 88c6e9f..8c16cfb 100644
16--- twisted/web/test/requesthelper.py
17+++ twisted/web/test/requesthelper.py
18@@ -118,7 +118,8 @@ class DummyRequest(object):
19         self.responseCode = None
20         self.headers = {}
21         self._finishedDeferreds = []
22-
23+        self._serverName = b"dummy"
24+        self.clientproto = b"HTTP/1.0"
25 
26     def getHeader(self, name):
27         """
28@@ -133,6 +134,8 @@ class DummyRequest(object):
29         """
30         return self.headers.get(name.lower(), None)
31 
32+    def getAllHeaders(self):
33+        return self.headers
34 
35     def setHeader(self, name, value):
36         """TODO: make this assert on write() if the header is content-length
37@@ -237,3 +240,12 @@ class DummyRequest(object):
38         if isinstance(self.client, IPv4Address):
39             return self.client.host
40         return None
41+
42+    def getRequestHostname(self):
43+        return self._serverName
44+
45+    def getHost(self):
46+        return DummyChannel.TCP()
47+
48+    def getClient(self):
49+        pass
50diff --git twisted/web/test/test_cgi.py twisted/web/test/test_cgi.py
51index db63211..3d7d4ac 100755
52--- twisted/web/test/test_cgi.py
53+++ twisted/web/test/test_cgi.py
54@@ -214,6 +214,29 @@ class CGI(unittest.TestCase):
55         self.assertEqual(res, "readallinput ok%s" % os.linesep)
56 
57 
58+class CGIScriptTests(unittest.TestCase):
59+    """
60+    Tests for L{twcgi.CGIScript}.
61+    """
62+
63+    def test_path_info(self):
64+        """
65+        L{twcgi.CGIScript.render} sets the process environment I{PATH_INFO} from
66+        the request path.
67+        """
68+        class FakeReactor:
69+            def spawnProcess(self, process, filename, args, env, wdir):
70+                self.process_env = env
71+
72+        _reactor = FakeReactor()
73+        resource = twcgi.CGIScript(self.mktemp(), _reactor=_reactor)
74+        request = DummyRequest(['a', 'b'])
75+        _render(resource, request)
76+
77+        self.assertIn("PATH_INFO", _reactor.process_env)
78+        self.assertEqual(_reactor.process_env["PATH_INFO"],
79+                         "/a/b")
80+
81 
82 class CGIDirectoryTests(unittest.TestCase):
83     """
84diff --git twisted/web/test/test_util.py twisted/web/test/test_util.py
85index ac628e7..854002c 100644
86--- twisted/web/test/test_util.py
87+++ twisted/web/test/test_util.py
88@@ -13,7 +13,7 @@ from twisted.web.error import FlattenerError
89 from twisted.web.util import (
90     redirectTo, _SourceLineElement,
91     _SourceFragmentElement, _FrameElement, _StackElement,
92-    FailureElement, formatFailure, DeferredResource)
93+    FailureElement, formatFailure, DeferredResource, htmlIndent)
94 
95 from twisted.web.http import FOUND
96 from twisted.web.server import Request
97@@ -422,3 +422,44 @@ class DeferredResourceTests(TestCase):
98         deferredResource = DeferredResource(defer.succeed(result))
99         deferredResource.render(request)
100         self.assertEqual(rendered, [result])
101+
102+class HtmlIndentTests(TestCase):
103+    """
104+    Tests for L{htmlIndent}
105+    """
106+
107+    def test_simple_input(self):
108+        """
109+        L{htmlIndent} transparently process input with no special cases inside.
110+        """
111+        line = "foo bar"
112+        self.assertEqual(line, htmlIndent(line))
113+
114+    def test_escape_html(self):
115+        """
116+        L{htmlIndent} escapes HTML from its input.
117+        """
118+        line = "<br />"
119+        self.assertEqual("&lt;br /&gt;", htmlIndent(line))
120+
121+    def test_strip_trailing_whitespace(self):
122+        """
123+        L{htmlIndent} removes trailing whitespaces from its input.
124+        """
125+        line = " foo bar  "
126+        self.assertEqual(" foo bar", htmlIndent(line))
127+
128+    def test_force_spacing_from_space_characters(self):
129+        """
130+        If L{htmlIndent} detects consecutive space characters, it forces the
131+        rendering by substituting unbreakable space.
132+        """
133+        line = "  foo  bar"
134+        self.assertEqual("&nbsp;foo&nbsp;bar", htmlIndent(line))
135+
136+    def test_indent_from_tab_characters(self):
137+        """
138+        L{htmlIndent} replaces tab characters by unbreakable spaces.
139+        """
140+        line = "\tfoo"
141+        self.assertEqual("&nbsp; &nbsp; &nbsp; &nbsp; foo", htmlIndent(line))
142diff --git twisted/web/twcgi.py twisted/web/twcgi.py
143index 5ab580d..ffd8ab4 100644
144--- twisted/web/twcgi.py
145+++ twisted/web/twcgi.py
146@@ -8,7 +8,6 @@ I hold resource classes and helper classes that deal with CGI scripts.
147 """
148 
149 # System Imports
150-import string
151 import os
152 import urllib
153 
154@@ -51,11 +50,14 @@ class CGIScript(resource.Resource):
155     IPC with an external process with an unpleasant protocol.
156     """
157     isLeaf = 1
158-    def __init__(self, filename, registry=None):
159+    def __init__(self, filename, registry=None, _reactor=None):
160         """
161         Initialize, with the name of a CGI script file.
162         """
163         self.filename = filename
164+        if _reactor is None:
165+            _reactor = reactor
166+        self._reactor = _reactor
167 
168 
169     def render(self, request):
170@@ -68,8 +70,8 @@ class CGIScript(resource.Resource):
171         @type request: L{twisted.web.http.Request}
172         @param request: An HTTP request.
173         """
174-        script_name = "/"+string.join(request.prepath, '/')
175-        serverName = string.split(request.getRequestHostname(), ':')[0]
176+        script_name = "/" + "/".join(request.prepath)
177+        serverName = request.getRequestHostname().split(':')[0]
178         env = {"SERVER_SOFTWARE":   server.version,
179                "SERVER_NAME":       serverName,
180                "GATEWAY_INTERFACE": "CGI/1.1",
181@@ -89,7 +91,7 @@ class CGIScript(resource.Resource):
182             env['REMOTE_ADDR'] = ip
183         pp = request.postpath
184         if pp:
185-            env["PATH_INFO"] = "/"+string.join(pp, '/')
186+            env["PATH_INFO"] = "/" + "/".join(pp)
187 
188         if hasattr(request, "content"):
189             # request.content is either a StringIO or a TemporaryFile, and
190@@ -99,7 +101,7 @@ class CGIScript(resource.Resource):
191             request.content.seek(0,0)
192             env['CONTENT_LENGTH'] = str(length)
193 
194-        qindex = string.find(request.uri, '?')
195+        qindex = request.uri.find('?')
196         if qindex != -1:
197             qs = env['QUERY_STRING'] = request.uri[qindex+1:]
198             if '=' in qs:
199@@ -112,7 +114,7 @@ class CGIScript(resource.Resource):
200 
201         # Propogate HTTP headers
202         for title, header in request.getAllHeaders().items():
203-            envname = string.upper(string.replace(title, '-', '_'))
204+            envname = title.replace('-', '_').upper()
205             if title not in ('content-type', 'content-length'):
206                 envname = "HTTP_" + envname
207             env[envname] = header
208@@ -143,8 +145,8 @@ class CGIScript(resource.Resource):
209             will get spawned.
210         """
211         p = CGIProcessProtocol(request)
212-        reactor.spawnProcess(p, self.filename, [self.filename] + qargs, env,
213-                             os.path.dirname(self.filename))
214+        self._reactor.spawnProcess(p, self.filename, [self.filename] + qargs,
215+                                   env, os.path.dirname(self.filename))
216 
217 
218 
219diff --git twisted/web/util.py twisted/web/util.py
220index 0c6cdb6..2befc59 100644
221--- twisted/web/util.py
222+++ twisted/web/util.py
223@@ -12,10 +12,8 @@ __all__ = [
224 
225 from cStringIO import StringIO
226 import linecache
227-import string
228 import types
229 
230-from twisted.python.filepath import FilePath
231 from twisted.python.reflect import fullyQualifiedName
232 from twisted.python.deprecate import deprecatedModuleAttribute
233 from twisted.python.versions import Version
234@@ -200,9 +198,9 @@ htmlReprTypes = {types.DictType: htmlDict,
235 
236 
237 def htmlIndent(snippetLine):
238-    ret = string.replace(string.replace(html.escape(string.rstrip(snippetLine)),
239-                                  '  ', '&nbsp;'),
240-                   '\t', '&nbsp; &nbsp; &nbsp; &nbsp; ')
241+    ret = html.escape(snippetLine.rstrip())\
242+            .replace('  ', '&nbsp;')\
243+            .replace('\t', '&nbsp; &nbsp; &nbsp; &nbsp; ')
244     return ret
245 
246