I've managed to finally deduce what I was doing wrong, and pass one of my trivial unit tests... the code now looks like this:
--Translate01.py
"""Translates internal representation to and from xhtml"""
#define Exceptions
class HtmlError(Exception): pass
class invalidHtmlError(HtmlError): pass
#Define escape mapping
htmlCharMap = [('>', ">"),
('<', "<")]
def toHtml(x):
"""convert x to html string"""
return x
def fromHtml(s):
"""convert html string to internal representation"""
result = ''
index = 0
while index < len(s):
foundat = -1
i = 0
for ascii,html in htmlCharMap:
if (foundat < 0) & (s[index:index+len(html)] == html):
foundat = i
i += 1
if foundat >= 0:
ascii, html = htmlCharMap[foundat]
result += ascii
index += len(html)
else:
result += s[index]
index += 1
return result
Translate01_test.py:
"""Unit test for translate01.py"""
import translate01
import unittest
class KnownValues(unittest.TestCase):
knownValues = ( ( '', ''),
( 'x','x'),
( '>','>'),
( '<','<'),
( 'this is a test','this is a test') )
def testToHtmlKnownValues(self):
"""ToHtml should give known results with known input"""
for s1,s2 in self.knownValues:
result = translate01.toHtml(s1)
self.assertEqual(s2,result)
def testFromHtmlKnownValues(self):
"""FromHtml should give known results with known input"""
for s1,s2 in self.knownValues:
result = translate01.fromHtml(s2)
self.assertEqual(s1,result)
if __name__ == "__main__":
unittest.main()
No comments:
Post a Comment