## Debuging example: make the unittests work" # Code with bugs in... def textToHex(text): """This code should convert ASCII text to the unicode hex""" out = [] for c in text: out.append(ord(c)) return " ".join("{:x}".format(i) for i in out) def runningAverage(data,window): """Take the running average of a set of numbers, with a given window""" out = [0. for i in range(len(data))] for i in range(len(data)): for j in range(i-window,i+window+1): if( j >= 0 and j < len(data) ): out[i] += data[j] out[i] /= (2*window + 1) return out # The unittest suite allows you to write tests that your code must pass # After every change to the code you can test to check the code still works import unittest class ExampleCode(unittest.TestCase): """Example of how to use unittest in Jupyter.""" def testTrue(self): """A simple test that should always pass""" self.assertEqual('foo'.upper(), 'FOO') def testTextToHex(self): """Test the textToHex function above""" self.assertEqual(textToHex("Hello world"), '0x48 0x65 0x6c 0x6c 0x6f 0x20 0x77 0x6f 0x72 0x6c 0x64') def testRunningAverage(self): """Test the running average function with a window of zero""" # some input data data = [1.,2.5,3.7,11.] # a window of one either side of the value for average window = 0 # expected output is the same as the input self.assertEqual(runningAverage(data,window),data) def testRunningAverage(self): """Test the running average function with a window of one""" # some input data data = [1.,2.5,3.7,11.] # a window of one either side of the value for average window = 1 # expected output (note corrections at the ends of the array) rData = [(1.+2.5)/2, (1.+2.5+3.7)/3, (2.5+3.7+11.)/3, (3.7+11.)/2] self.assertEqual(runningAverage(data,window),rData) # if this is not called from another function run the unit tests now if __name__ == '__main__': unittest.main(exit=False)