Python Forum

Full Version: How would you test this module?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
How can I write unit tests for this module. I know very little about writing tests.

#-*-coding:utf8;-*-
#qpy:3
#qpy:console



SINGLETONS = [
    'area',
    'base',
    'br',
    'col',
    'command',
    'embed',
    'hr',
    'img',
    'input',
    'keygen',
    'link',
    'meta',
    'param',
    'source',
    'track',
    'wbr'
]
    
       
def tagify(tagname, data='', **kw):
    attrs = ''
    retval = ''
    for key, value in zip(kw.keys(), kw.values()):
        if key == 'cls':
            key = 'class'
            
        if key == '_id':
            key = 'id'
            
        attrs += '{}="{}"'.format(key, value)
        
    if not attrs:
        opentag = '<{}>'.format(tagname)
    else:
        opentag = '<{} {}>'.format(tagname, attrs)
        
    if not tagname in SINGLETONS:
        closetag = '</{}>'.format(tagname)
    else:
        closetag = None
        
    if not closetag:
        retval = '{}'.format(opentag)
  
    if data:
        retval = '{}{}{}'.format(opentag, data, closetag)
    else:
        retval = '{}{}'.format(opentag, closetag)
    return retval

def tag(tagname, **deco_kw):
    def deco(func):
        def wraps(*args, **kw):
            data = func(*args, **kw)
            return tagify(tagname, data, **deco_kw)
        return wraps
    return deco
In the standard lib, there's unit tests: https://docs.python.org/3/library/unittest.html
and doc tests: https://docs.python.org/3/library/doctest.html

Doc tests are useful if you have a tool that builds documentation for you (such as Sphinx http://www.sphinx-doc.org/en/stable/), so you know your examples are still accurate. Unit tests are probably more useful in general, though.
Here is the starting point of a testing file, assuming the initial file is tagfoo.py
# file testtagfoo.py
import unittest as ut
from tagfoo import tagify, tag

class TestTagify(ut.TestCase):
    def test_simple_image_tag(self):
        rv = tagify('image', 'An Image', src='filename.jpg')
        self.assertEqual(
            rv,
            '<image src="filename.jpg">An Image</image>')
        
if __name__ == '__main__':
    ut.main()
You can add methods test_... to the TestTagify class, and create new classes.