
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.


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

from cStringIO import StringIO

from zope.interface.verify import verifyObject

from twisted.internet.defer import succeed, gatherResults
from twisted.python.filepath import FilePath
from twisted.trial.unittest import TestCase
from twisted.trial.util import suppress as SUPPRESS
from twisted.web.template import (
    Element, TagLoader, renderer, tags, XMLFile, XMLString)
from twisted.web.iweb import ITemplateLoader

from twisted.web.error import (FlattenerError, MissingTemplateLoader,
    MissingRenderMethod)

from twisted.web.template import renderElement
from twisted.web._element import UnexposedMethodError
from twisted.web.test._util import FlattenTestCase
from twisted.web.test.test_web import DummyRequest
from twisted.web.server import NOT_DONE_YET


_xmlFileSuppress = SUPPRESS(category=DeprecationWarning,
        message="Passing filenames or file objects to XMLFile is "
                "deprecated since Twisted 12.1.  Pass a FilePath instead.")


class TagFactoryTests(TestCase):
    """
    Tests for L{_TagFactory} through the publicly-exposed L{tags} object.
    """
    def test_lookupTag(self):
        """
        HTML tags can be retrieved through C{tags}.
        """
        tag = tags.a
        self.assertEqual(tag.tagName, "a")


    def test_lookupHTML5Tag(self):
        """
        Twisted supports the latest and greatest HTML tags from the HTML5
        specification.
        """
        tag = tags.video
        self.assertEqual(tag.tagName, "video")


    def test_lookupTransparentTag(self):
        """
        To support transparent inclusion in templates, there is a special tag,
        the transparent tag, which has no name of its own but is accessed
        through the "transparent" attribute.
        """
        tag = tags.transparent
        self.assertEqual(tag.tagName, "")


    def test_lookupInvalidTag(self):
        """
        Invalid tags which are not part of HTML cause AttributeErrors when
        accessed through C{tags}.
        """
        self.assertRaises(AttributeError, getattr, tags, "invalid")


    def test_lookupXMP(self):
        """
        As a special case, the <xmp> tag is simply not available through
        C{tags} or any other part of the templating machinery.
        """
        self.assertRaises(AttributeError, getattr, tags, "xmp")



class ElementTests(TestCase):
    """
    Tests for the awesome new L{Element} class.
    """
    def test_missingTemplateLoader(self):
        """
        L{Element.render} raises L{MissingTemplateLoader} if the C{loader}
        attribute is C{None}.
        """
        element = Element()
        err = self.assertRaises(MissingTemplateLoader, element.render, None)
        self.assertIdentical(err.element, element)


    def test_missingTemplateLoaderRepr(self):
        """
        A L{MissingTemplateLoader} instance can be repr()'d without error.
        """
        class PrettyReprElement(Element):
            def __repr__(self):
                return 'Pretty Repr Element'
        self.assertIn('Pretty Repr Element',
                      repr(MissingTemplateLoader(PrettyReprElement())))


    def test_missingRendererMethod(self):
        """
        When called with the name which is not associated with a render method,
        L{Element.lookupRenderMethod} raises L{MissingRenderMethod}.
        """
        element = Element()
        err = self.assertRaises(
            MissingRenderMethod, element.lookupRenderMethod, "foo")
        self.assertIdentical(err.element, element)
        self.assertEqual(err.renderName, "foo")


    def test_missingRenderMethodRepr(self):
        """
        A L{MissingRenderMethod} instance can be repr()'d without error.
        """
        class PrettyReprElement(Element):
            def __repr__(self):
                return 'Pretty Repr Element'
        s = repr(MissingRenderMethod(PrettyReprElement(),
                                     'expectedMethod'))
        self.assertIn('Pretty Repr Element', s)
        self.assertIn('expectedMethod', s)


    def test_definedRenderer(self):
        """
        When called with the name of a defined render method,
        L{Element.lookupRenderMethod} returns that render method.
        """
        class ElementWithRenderMethod(Element):
            @renderer
            def foo(self, request, tag):
                return "bar"
        foo = ElementWithRenderMethod().lookupRenderMethod("foo")
        self.assertEqual(foo(None, None), "bar")


    def test_render(self):
        """
        L{Element.render} loads a document from the C{loader} attribute and
        returns it.
        """
        class TemplateLoader(object):
            def load(self):
                return "result"

        class StubElement(Element):
            loader = TemplateLoader()

        element = StubElement()
        self.assertEqual(element.render(None), "result")


    def test_misuseRenderer(self):
        """
        If the L{renderer} decorator  is called without any arguments, it will
        raise a comprehensible exception.
        """
        te = self.assertRaises(TypeError, renderer)
        self.assertEqual(str(te),
                         "expose() takes at least 1 argument (0 given)")


    def test_renderGetDirectlyError(self):
        """
        Called directly, without a default, L{renderer.get} raises
        L{UnexposedMethodError} when it cannot find a renderer.
        """
        self.assertRaises(UnexposedMethodError, renderer.get, None,
                          "notARenderer")



class XMLFileReprTests(TestCase):
    """
    Tests for L{twisted.web.template.XMLFile}'s C{__repr__}.
    """
    def test_filePath(self):
        """
        An L{XMLFile} with a L{FilePath} returns a useful repr().
        """
        path = FilePath("/tmp/fake.xml")
        self.assertEqual('<XMLFile of %r>' % (path,), repr(XMLFile(path)))


    def test_filename(self):
        """
        An L{XMLFile} with a filename returns a useful repr().
        """
        fname = "/tmp/fake.xml"
        self.assertEqual('<XMLFile of %r>' % (fname,), repr(XMLFile(fname)))
    test_filename.suppress = [_xmlFileSuppress]


    def test_file(self):
        """
        An L{XMLFile} with a file object returns a useful repr().
        """
        fobj = StringIO("not xml")
        self.assertEqual('<XMLFile of %r>' % (fobj,), repr(XMLFile(fobj)))
    test_file.suppress = [_xmlFileSuppress]



class XMLLoaderTestsMixin(object):
    """
    @ivar templateString: Simple template to use to exercise the loaders.