aboutsummaryrefslogtreecommitdiffstats
path: root/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/web/test/test_util.py
blob: 42b54b930102aa005b60d47a2078d035df4df2ba (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.

"""
Tests for L{twisted.web.util}.
"""

from twisted.python.failure import Failure
from twisted.trial.unittest import TestCase
from twisted.web import util
from twisted.web.error import FlattenerError
from twisted.web.util import (
    redirectTo, _SourceLineElement,
    _SourceFragmentElement, _FrameElement, _StackElement,
    FailureElement, formatFailure)

from twisted.web.http import FOUND
from twisted.web.server import Request
from twisted.web.template import TagLoader, flattenString, tags

from twisted.web.test.test_web import DummyChannel


class RedirectToTestCase(TestCase):
    """
    Tests for L{redirectTo}.
    """

    def test_headersAndCode(self):
        """
        L{redirectTo} will set the C{Location} and C{Content-Type} headers on
        its request, and set the response code to C{FOUND}, so the browser will
        be redirected.
        """
        request = Request(DummyChannel(), True)
        request.method = 'GET'
        targetURL = "http://target.example.com/4321"
        redirectTo(targetURL, request)
        self.assertEqual(request.code, FOUND)
        self.assertEqual(
            request.responseHeaders.getRawHeaders('location'), [targetURL])
        self.assertEqual(
            request.responseHeaders.getRawHeaders('content-type'),
            ['text/html; charset=utf-8'])


    def test_redirectToUnicodeURL(self) :
        """
        L{redirectTo} will raise TypeError if unicode object is passed in URL
        """
        request = Request(DummyChannel(), True)
        request.method = 'GET'
        targetURL = u'http://target.example.com/4321'
        self.assertRaises(TypeError, redirectTo, targetURL, request)



class FailureElementTests(TestCase):
    """
    Tests for L{FailureElement} and related helpers which can render a
    L{Failure} as an HTML string.
    """
    def setUp(self):
        """
        Create a L{Failure} which can be used by the rendering tests.
        """
        def lineNumberProbeAlsoBroken():
            message = "This is a problem"
            raise Exception(message)
        # Figure out the line number from which the exception will be raised.
        self.base = lineNumberProbeAlsoBroken.func_code.co_firstlineno + 1

        try:
            lineNumberProbeAlsoBroken()
        except:
            self.failure = Failure(captureVars=True)
            self.frame = self.failure.frames[-1]


    def test_sourceLineElement(self):
        """
        L{_SourceLineElement} renders a source line and line number.
        """
        element = _SourceLineElement(
            TagLoader(tags.div(
                    tags.span(render="lineNumber"),
                    tags.span(render="sourceLine"))),
            50, "    print 'hello'")
        d = flattenString(None, element)
        expected = (
            u"<div><span>50</span><span>"
            u" \N{NO-BREAK SPACE} \N{NO-BREAK SPACE}print 'hello'</span></div>")
        d.addCallback(
            self.assertEqual, expected.encode('utf-8'))
        return d


    def test_sourceFragmentElement(self):
        """
        L{_SourceFragmentElement} renders source lines at and around the line
        number indicated by a frame object.
        """
        element = _SourceFragmentElement(
            TagLoader(tags.div(
                    tags.span(render="lineNumber"),
                    tags.span(render="sourceLine"),
                    render="sourceLines")),
            self.frame)

        source = [
            u' \N{NO-BREAK SPACE} \N{NO-BREAK SPACE}message = '
            u'"This is a problem"',

            u' \N{NO-BREAK SPACE} \N{NO-BREAK SPACE}raise Exception(message)',
            u'# Figure out the line number from which the exception will be '
            u'raised.',
        ]
        d = flattenString(None, element)
        d.addCallback(
            self.assertEqual,
            ''.join([
                    '<div class="snippet%sLine"><span>%d</span><span>%s</span>'
                    '</div>' % (
                        ["", "Highlight"][lineNumber == 1],
                        self.base + lineNumber,
                        (u" \N{NO-BREAK SPACE}" * 4 + sourceLine).encode(
                            'utf-8'))
                    for (lineNumber, sourceLine)
                    in enumerate(source)]))
        return d


    def test_frameElementFilename(self):
        """
        The I{filename} renderer of L{_FrameElement} renders the filename
        associated with the frame object used to initialize the
        L{_FrameElement}.
        """
        element = _FrameElement(
            TagLoader(tags.span(render="filename")),
            self.frame)
        d = flattenString(None, element)
        d.addCallback(
            # __file__ differs depending on whether an up-to-date .pyc file
            # already existed.
            self.assertEqual, "<span>" + __file__.rstrip('c') + "</span>")
        return d


    def test_frameElementLineNumber(self):
        """
        The I{lineNumber} renderer of L{_FrameElement} renders the line number
        associated with the frame object used to initialize the
        L{_FrameElement}.
        """
        element = _FrameElement(
            TagLoader(tags.span(render="lineNumber")),
            self.frame)
        d = flattenString(None, element)
        d.addCallback(
            self.assertEqual, "<span>" + str(self.base + 1) + "</span>")
        return d


    def test_frameElementFunction(self):
        """
        The I{function} renderer of L{_FrameElement} renders the line number
        associated with the frame object used to initialize the
        L{_FrameElement}.
        """
        element = _FrameElement(
            TagLoader(tags.span(render="function")),
            self.frame)
        d = flattenString(None, element)
        d.addCallback(
            self.assertEqual, "<span>lineNumberProbeAlsoBroken</span>")
        return d


    def test_frameElementSource(self):
        """
        The I{source} renderer of L{_FrameElement} renders the source code near
        the source filename/line number associated with the frame object used to
        initialize the L{_FrameElement}.
        """
        element = _FrameElement(None, self.frame)
        renderer = element.lookupRenderMethod("source")
        tag = tags.div()
        result = renderer(None, tag)
        self.assertIsInstance(result, _SourceFragmentElement)
        self.assertIdentical(result.frame, self.frame)
        self.assertEqual([tag], result.loader.load())


    def test_stackElement(self):
        """
        The I{frames} renderer of L{_StackElement} renders each stack frame in
        the list of frames used to initialize the L{_StackElement}.
        """
        element = _StackElement(None, self.failure.frames[:2])
        renderer = element.lookupRenderMethod("frames")
        tag = tags.div()
        result = renderer(None, tag)
        self.assertIsInstance(result, list)
        self.assertIsInstance(result[0], _FrameElement)
        self.assertIdentical(result[0].frame, self.failure.frames[0])
        self.assertIsInstance(result[1], _FrameElement)
        self.assertIdentical(result[1].frame, self.failure.frames[1])
        # They must not share the same tag object.
        self.assertNotEqual(result[0].loader.load(), result[1].loader.load())
        self.assertEqual(2, len(result))


    def test_failureElementTraceback(self):
        """
        The I{traceback} renderer of L{FailureElement} renders the failure's
        stack frames using L{_StackElement}.
        """
        element = FailureElement(self.failure)
        renderer = element.lookupRenderMethod("traceback")
        tag = tags.div()
        result = renderer(None, tag)
        self.assertIsInstance(result, _StackElement)
        self.assertIdentical(result.stackFrames, self.failure.frames)
        self.assertEqual([tag], result.loader.load())


    def test_failureElementType(self):
        """
        The I{type} renderer of L{FailureElement} renders the failure's
        exception type.
        """
        element = FailureElement(
            self.failure, TagLoader(tags.span(render="type")))
        d = flattenString(None, element)
        d.addCallback(
            self.assertEqual, "<span>exceptions.Exception</span>")
        return d


    def test_failureElementValue(self):
        """
        The I{value} renderer of L{FailureElement} renders the value's exception
        value.
        """
        element = FailureElement(
            self.failure, TagLoader(tags.span(render="value")))
        d = flattenString(None, element)
        d.addCallback(
            self.assertEqual, '<span>This is a problem</span>')
        return d



class FormatFailureTests(TestCase):
    """
    Tests for L{twisted.web.util.formatFailure} which returns an HTML string
    representing the L{Failure} instance passed to it.
    """
    def test_flattenerError(self):
        """
        If there is an error flattening the L{Failure} instance,
        L{formatFailure} raises L{FlattenerError}.
        """
        self.assertRaises(FlattenerError, formatFailure, object())


    def test_returnsBytes(self):
        """
        The return value of L{formatFailure} is a C{str} instance (not a
        C{unicode} instance) with numeric character references for any non-ASCII
        characters meant to appear in the output.
        """
        try:
            raise Exception("Fake bug")
        except:
            result = formatFailure(Failure())

        self.assertIsInstance(result, str)
        self.assertTrue(all(ord(ch) < 128 for ch in result))
        # Indentation happens to rely on NO-BREAK SPACE
        self.assertIn("&#160;", result)



class DeprecatedHTMLHelpers(TestCase):
    """
    The various HTML generation helper APIs in L{twisted.web.util} are
    deprecated.
    """
    def _htmlHelperDeprecationTest(self, functionName):
        """
        Helper method which asserts that using the name indicated by
        C{functionName} from the L{twisted.web.util} module emits a deprecation
        warning.
        """
        getattr(util, functionName)
        warnings = self.flushWarnings([self._htmlHelperDeprecationTest])
        self.assertEqual(warnings[0]['category'], DeprecationWarning)
        self.assertEqual(
            warnings[0]['message'],
            "twisted.web.util.%s was deprecated in Twisted 12.1.0: "
            "See twisted.web.template." % (functionName,))


    def test_htmlrepr(self):
        """
        L{twisted.web.util.htmlrepr} is deprecated.
        """
        self._htmlHelperDeprecationTest("htmlrepr")


    def test_saferepr(self):
        """
        L{twisted.web.util.saferepr} is deprecated.
        """
        self._htmlHelperDeprecationTest("saferepr")


    def test_htmlUnknown(self):
        """
        L{twisted.web.util.htmlUnknown} is deprecated.
        """
        self._htmlHelperDeprecationTest("htmlUnknown")


    def test_htmlDict(self):
        """
        L{twisted.web.util.htmlDict} is deprecated.
        """
        self._htmlHelperDeprecationTest("htmlDict")


    def test_htmlList(self):
        """
        L{twisted.web.util.htmlList} is deprecated.
        """
        self._htmlHelperDeprecationTest("htmlList")


    def test_htmlInst(self):
        """
        L{twisted.web.util.htmlInst} is deprecated.
        """
        self._htmlHelperDeprecationTest("htmlInst")


    def test_htmlString(self):
        """
        L{twisted.web.util.htmlString} is deprecated.
        """
        self._htmlHelperDeprecationTest("htmlString")


    def test_htmlIndent(self):
        """
        L{twisted.web.util.htmlIndent} is deprecated.
        """
        self._htmlHelperDeprecationTest("htmlIndent")


    def test_htmlFunc(self):
        """
        L{twisted.web.util.htmlFunc} is deprecated.
        """
        self._htmlHelperDeprecationTest("htmlFunc")


    def test_htmlReprTypes(self):
        """
        L{twisted.web.util.htmlReprTypes} is deprecated.
        """
        self._htmlHelperDeprecationTest("htmlReprTypes")


    def test_stylesheet(self):
        """
        L{twisted.web.util.stylesheet} is deprecated.
        """
        self._htmlHelperDeprecationTest("stylesheet")