My poorly written tests suggests that the module works as intended. I fear this is to good to be true. I don't known how to write unit tests for this. I'm new to writing tests and I think this module would be hard for a unit test master to test.
#-*-coding:utf8;-*-
#qpy:3
#qpy:console
SINGLETONS = [
'area',
'base',
'br',
'col',
'command',
'embed',
'hr',
'img',
'input',
'keygen',
'link',
'meta',
'param',
'source',
'track',
'wbr'
]
# Constants.
SP = ' '
EMPTY = ''
def is_singleton(tag):
return tag in SINGLETONS
def not_singleton(tag):
return is_singleton(tag) == False
def html_attributes(**kw):
# 'attrs' is the elements attributes.
# Iterate over the keys and values of the kw dict
# and transform them into a string of html
# attributes. Two html attribute keys are
# Python keywords 'class' and 'id' to set
# the id and class of and element use:
# cls for class and '_id' for 'id.'
attrs = EMPTY
n_attrs = len(kw)
for key, value in zip(kw.keys(), kw.values()):
if key == 'cls':
key = 'class'
if key == '_id':
key = 'id'
if n_attrs > 1:
attrs += '{}="{}"{}'.format(key, value, SP)
else:
attrs += '{}="{}"'.format(key, value)
return attrs.rstrip(SP)
def tagify(tagname, data=EMPTY, **kw):
if isinstance(data, str):
data = data.replace('\n', '<br>')
attrs = html_attributes(**kw)
if not attrs:
opentag = '<{}>'.format(tagname)
else:
opentag = '<{}{}{}>'.format(tagname, SP, attrs)
if not_singleton(tagname):
closetag = '</{}>'.format(tagname)
else:
closetag = None
if not closetag:
return '{}'.format(opentag)
if data:
return '{}{}{}'.format(opentag, data, closetag)
else:
return '{}{}'.format(opentag, closetag)
def tag(tagname, **deco_kw):
'''
Decorate a functions output with html by
passing it through tagify.
'''
def deco(func):
def wraps(*args, **kw):
content = func(*args, **kw)
return tagify(tagname, content, **deco_kw)
return wraps
return deco
def tests():
'''
This is a temporary function for
testing the module.
Please dont include this in any reviews.
'''
@tag('li', cls='link', _id='list-item')
def link(name, **kw):
return tagify('a', name, **kw)
@tag('article', cls='main', _id='spam')
def paragraph(content, **kw):
return tagify('p', content, **kw)
print(link(__name__, src=__file__))
print(paragraph(list(range(10)), _id='monty'))
if __name__ == '__main__':
tests()
test() output
<li id="list-item" class="link"><a src="/">__main__</a></li>
<article id="spam" class="main"><p id="monty">[0, 1, 2, 3, 4]</p></article>
lxmlorbuiltinslikehtml.dom. I wanted something simple and pretty. \$\endgroup\$