2 # Copyright (c) Twisted Matrix Laboratories.
3 # See LICENSE for details.
6 General helpers for L{twisted.web} unit tests.
9 from twisted.internet.defer import succeed
10 from twisted.web import server
11 from twisted.trial.unittest import TestCase
12 from twisted.python.failure import Failure
13 from twisted.web._flatten import flattenString
14 from twisted.web.error import FlattenerError
17 def _render(resource, request):
18 result = resource.render(request)
19 if isinstance(result, str):
23 elif result is server.NOT_DONE_YET:
27 return request.notifyFinish()
29 raise ValueError("Unexpected return value: %r" % (result,))
33 class FlattenTestCase(TestCase):
35 A test case that assists with testing L{twisted.web._flatten}.
37 def assertFlattensTo(self, root, target):
39 Assert that a root element, when flattened, is equal to a string.
41 d = flattenString(None, root)
42 d.addCallback(lambda s: self.assertEqual(s, target))
46 def assertFlattensImmediately(self, root, target):
48 Assert that a root element, when flattened, is equal to a string, and
49 performs no asynchronus Deferred anything.
51 This version is more convenient in tests which wish to make multiple
52 assertions about flattening, since it can be called multiple times
53 without having to add multiple callbacks.
56 it = self.assertFlattensTo(root, target)
57 it.addBoth(results.append)
58 # Do our best to clean it up if something goes wrong.
59 self.addCleanup(it.cancel)
61 self.fail("Rendering did not complete immediately.")
63 if isinstance(result, Failure):
64 result.raiseException()
67 def assertFlatteningRaises(self, root, exn):
69 Assert flattening a root element raises a particular exception.
71 d = self.assertFailure(self.assertFlattensTo(root, ''), FlattenerError)
72 d.addCallback(lambda exc: self.assertIsInstance(exc._exception, exn))