# toMod5 # consumes: list of integers # produces: same list of integers, but each integer in the list replaced with that integer, mod 5 import sys # new_check_expect checks whether a function produces the expected result # consumes: # check: a string containing the function call we want to test # expect: the value we are expecting (typically a literal value) # msg: True if we should print output, False if we should not # default is True) # produces: # True if test passes, False otherwise # side effect: # prints a message indicating whether the test passed or failed def new_check_expect(check,expect,msg=True): if msg: print "Testing " + check + " :", try: actual = eval(check) result = (actual == expect) if msg: if result: print " Passed!" else: print " Failed! Expected: " + str(expect) + " Got: " + str(actual) return result except: if msg: print " ERROR: Unable to evaluate test: " + str(sys.exc_info()[0]) # consumes: # check: an expression to test, as a string # expectedException: the exception you should get in response # msg: whether or not to print results as a side effect # produces: # boolean: True is the test comes out as expected, i.e. you get the # exception that you think you are going to get # side effect: # if msg is True, then print messages about what happened to the console def check_exception(check,expectedException,msg=True): if msg: print "Testing " + check + " :", try: evalResult = eval(check) gotException = False except: actualException = sys.exc_info()[1] gotException = True gotExpectedException = (str(actualException) == expectedException) if gotException and gotExpectedException: if msg: print " Passed!" return True elif not gotException: if msg: print " Failed! I expected an exception, but instead I got the result: " + \ str(evalResult) return False else: # must be true that (not gotExpectedException) if msg: print " Failed! I expected this Exception: " + \ expectedException + " but instead I got this exception: " + \ str(actualException) return False # toMod5 # consumes: list of integers # produces: same list of integers, but each integer in the list replaced with that integer, mod 5 def toMod5(lst): if len(lst)==0: return [] else: return [lst[0]%5] + toMod5(lst[1:]) new_check_expect("toMod5( [3,7,15,2,4,10])", [3,2,0,2,4,0]) new_check_expect("toMod5( [])", []) new_check_expect("toMod5( [7])", [2])