Skip to content

Commit

Permalink
Improve handling of comment nodes
Browse files Browse the repository at this point in the history
  • Loading branch information
amol- committed Apr 16, 2018
1 parent 5426154 commit 0ac5957
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 9 deletions.
24 changes: 19 additions & 5 deletions kajiki/tests/test_xml.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
import kajiki
from kajiki import MockLoader, XMLTemplate, FileLoader, PackageLoader
from kajiki.ir import TranslatableTextNode
from kajiki.xml_template import _Compiler, _Parser, XMLTemplateCompileError
from kajiki.xml_template import _Compiler, _Parser, XMLTemplateCompileError, XMLTemplateParseError

DATA = os.path.join(os.path.dirname(__file__), 'data')

Expand Down Expand Up @@ -1034,11 +1034,25 @@ class TestMultipleChildrenInDOM(TestCase):
def test_ok(self):
XMLTemplate('<xml><!-- a --><x>${1+1}</x></xml>')

def test_raise(self):
def test_comment(self):
res = XMLTemplate('<!-- a --><x>${1+1}</x>')().render()
assert res == '<x>2</x>'

def test_multiple_nodes(self):
try:
XMLTemplate('<!-- a --><x>${1+1}</x>')
except XMLTemplateCompileError as e:
assert 'more than one children' in str(e), e
XMLTemplate('<!-- a --><x>${1+1}</x><y>${1+1}</y>')
except XMLTemplateParseError as e:
assert 'junk after document element' in str(e), e
else:
assert False, 'should have raised'

def test_only_comment(self):
try:
XMLTemplate('<!-- a -->')
except XMLTemplateParseError as e:
assert 'no element found' in str(e), e
else:
assert False, 'should have raised'


class TestSyntaxErrorCallingWithTrailingParenthesis(TestCase):
Expand Down
9 changes: 5 additions & 4 deletions kajiki/xml_template.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@

from . import ir
from . import template
from .template import KajikiSyntaxError
from .ddict import defaultdict
from .doctype import DocumentTypeDeclaration, extract_dtd
from .entities import html5, unescape
Expand Down Expand Up @@ -116,10 +115,12 @@ def compile(self):
registries of the compiler ``compile`` should
never be called twice or might lead to unexpected results.
"""
if len(self.doc.childNodes) != 1:
raise XMLTemplateCompileError('more than one children in document',
templateNodes = [n for n in self.doc.childNodes if not isinstance(n, dom.Comment)]
if len(templateNodes) != 1:
raise XMLTemplateCompileError('expected a single root node in document',
self.doc, self.filename, 0)
body = list(self._compile_node(self.doc.firstChild))

body = list(self._compile_node(templateNodes[0]))
# Never emit doctypes on fragments
if not self.is_fragment and not self.is_child:
if self.doc._dtd:
Expand Down

0 comments on commit 0ac5957

Please sign in to comment.