123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- import unittest
- import re
- class SimpleTestCase(unittest.TestCase):
-
- def setUp(self):
- '''
- Init object
- '''
- self.__rightPad = RightPad()
-
- def testConvert(self):
-
- usecases = [
- [ 12, '12.00' ] ,
- [ 12.1, '12.10' ],
- [ 12.11, '12.11' ],
- [ 12.12052, '12.12']
- ]
-
- for usecase in usecases:
- self.assertEqual(self.__rightPad.convert(usecase[0]), usecase[1])
-
- class RightPad(object):
-
- def __init__(self, limit = 2):
- self.__limit = limit
-
- def convert(self, rawValue):
- # turn value into a string
- stringValue = str(rawValue)
- # Apply regex on it
- p = re.compile(r'^(\d+\.\d{%d})$|^(\d+)(\.\d*)?$'%(self.__limit))
- matches = re.search(p, stringValue)
-
- #no treatment required
- if (matches.lastindex == 1) :
- print("A")
- return stringValue
-
- #Only pad an integer
- elif (matches.lastindex == 2) :
- print("B")
- return matches.group(2) + '.' + '0'*self.__limit
- #either pad float value or truncate it to fit limit
- elif (matches.lastindex == 3) :
- print("C")
- group = str(matches.group(3))
-
- #truncate value
- if (len(group) > self.__limit):
- return matches.group(2) + group[:self.__limit + 1]
- #pad value
- else:
- return matches.group(2) + matches.group(3) + "0"*(self.__limit - len(group) + 1)
-
-
- return 'Fly you fool!'
-
- if __name__ == "__main__":
- unittest.main() # run all tests
|