Skip to content

Commit

Permalink
compoundElements now behave boolean-ly correct under py2
Browse files Browse the repository at this point in the history
  • Loading branch information
staffanm committed Jan 17, 2016
1 parent dac7f2c commit 78c8ee8
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
8 changes: 8 additions & 0 deletions ferenda/elements/elements.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,14 @@ def __new__(cls, arg=[], *args, **kwargs):
def __str__(self):
return self.as_plaintext()

def __nonzero__(self):
# on py2, we've had problems with empty elements (x =
# CompoundElement()) being truthy. Avoid this by defining a
# proper bool criteria using the magic __nonzero__
# method. These problems don't show up on py3, so we don't
# bother to define __bool__
return len(self) != 0

def _cleanstring(self, s):
# valid chars according to the XML spec
def _valid(i):
Expand Down
16 changes: 15 additions & 1 deletion test/testElements.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def test_serialize_roundtrip(self):
ordinal=2,
title="Native types")
])
# roundtrip using the default XML format
# roundtrip using the default XML format
serialized = serialize(tree)
self.assertIsInstance(serialized, str)
newtree = deserialize(serialized, caller_globals=globals())
Expand Down Expand Up @@ -120,6 +120,20 @@ def test_compound(self):
Paragraph(["World"])])]).as_plaintext(),
"Hello World")


def test_empty_compound(self):
# empty elements should be false
x = CompoundElement()
self.assertFalse(bool(x))

# even elements with metadata should be false, if they do not have any actual items
x = CompoundElement(id="42", foo="bar")
self.assertFalse(bool(x))

# but an element with some data should be true
x = CompoundElement(["actual", "data"], id="42", foo="bar")
self.assertTrue(bool(x))

def test_unicode(self):
x = UnicodeElement("Hello world", id="42")
self.assertEqual(b'<unicodeelement xmlns="http://www.w3.org/1999/xhtml" id="42">Hello world</unicodeelement>',
Expand Down

0 comments on commit 78c8ee8

Please sign in to comment.