Milestone 2: Unit testing

18 February 2019   PDF version

For this milestone, you will write some unit tests in Python for a function that I provide. There are several significant bugs in the function, so try to expose and characterize them!

Save the following file as numberfmt.py in your cs164 folder, and commit it to gitlab. Also write comments in the file characterizing any bugs that you find. (You do not have to fix the bugs.)

import unittest

# Format an integer by separating chunks with the SEP
# string (defaults to comma), where each chunk is SIZE
# digits (defaults to 3).
#
# Examples:
#
# >>> formatInt(32767)
# '32,767'
# >>> formatInt(1948576, size=4)
# '194,8576'
# >>> formatInt(1948576, sep="::")
# '1::948::576'
def formatInt(num, sep=",", size=3):
    # Preconditions: violating these doesn't indicate a test failure.
    assert type(num) == int
    assert type(sep) == str
    assert type(size) == int and size >= 0
    # Implementation
    chunk = 10 ** size
    groups = [str(num % chunk)]
    num = num // chunk           # integer division
    while num > 0:
        groups.insert(0, str(num % chunk)) # prepend
        num = num // chunk
    return sep.join(groups)

class FormatTests(unittest.TestCase):
    def testFiveDigitWithDefaults(self):
        self.assertEqual(formatInt(32767), "32,767")

    # Add more test methods here!

if __name__ == "__main__":
    unittest.main()