aboutsummaryrefslogtreecommitdiffstats
path: root/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/web/test/_util.py
blob: 6117b728ed94598fe746c51a8ede394b866eb771 (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
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.

"""
General helpers for L{twisted.web} unit tests.
"""

from twisted.internet.defer import succeed
from twisted.web import server
from twisted.trial.unittest import TestCase
from twisted.python.failure import Failure
from twisted.web._flatten import flattenString
from twisted.web.error import FlattenerError


def _render(resource, request):
    result = resource.render(request)
    if isinstance(result, str):
        request.write(result)
        request.finish()
        return succeed(None)
    elif result is server.NOT_DONE_YET:
        if request.finished:
            return succeed(None)
        else:
            return request.notifyFinish()
    else:
        raise ValueError("Unexpected return value: %r" % (result,))



class FlattenTestCase(TestCase):
    """
    A test case that assists with testing L{twisted.web._flatten}.
    """
    def assertFlattensTo(self, root, target):
        """
        Assert that a root element, when flattened, is equal to a string.
        """
        d = flattenString(None, root)
        d.addCallback(lambda s: self.assertEqual(s, target))
        return d


    def assertFlattensImmediately(self, root, target):
        """
        Assert that a root element, when flattened, is equal to a string, and
        performs no asynchronus Deferred anything.

        This version is more convenient in tests which wish to make multiple
        assertions about flattening, since it can be called multiple times
        without having to add multiple callbacks.
        """
        results = []
        it = self.assertFlattensTo(root, target)
        it.addBoth(results.append)
        # Do our best to clean it up if something goes wrong.
        self.addCleanup(it.cancel)
        if not results:
            self.fail("Rendering did not complete immediately.")
        result = results[0]
        if isinstance(result, Failure):
            result.raiseException()


    def assertFlatteningRaises(self, root, exn):
        """
        Assert flattening a root element raises a particular exception.
        """
        d = self.assertFailure(self.assertFlattensTo(root, ''), FlattenerError)
        d.addCallback(lambda exc: self.assertIsInstance(exc._exception, exn))
        return d