def theTests(path_to_code_to_check=""): """Run the tests.""" print("\nWelcome to week {}!".format(WEEK_NUMBER)) print("May the odds be ever in your favour.\n") testResults = [] # stack the tests here testResults.append( test(test_flake8("week{}/exercise1.py".format(WEEK_NUMBER)), "Exercise 1: pass the linter")) message = '{"message": "Python and requests are working!"}' testResults.append( test(exercise1.success_is_relative() == message, "Exercise 1: read a file using a relative path")) testDict = {'lastName': u'hoogmoed', 'password': u'jokers', 'postcodePlusID': 4311240} testResults.append( test(exercise1.get_some_details() == testDict, "Exercise 1: get some data out of a JSON file")) lengths = [3, 5, 7, 9, 11, 13, 15, 17, 19, 20, 18, 16, 14, 12, 10, 8, 6, 4] testResults.append( test([len(w) for w in exercise1.wordy_pyramid()] == lengths, "Exercise 1: request some simple data from the internet")) weather_results = {'latitude': u'-33.924206', 'state': u'NSW', 'longitude': u'151.187912', 'local_tz_offset': u'+1100'} testResults.append( test(process_wunderground(exercise1.wunderground()) == process_wunderground(weather_results), "Exercise 1: get some data from the weather underground.")) if os.path.isfile(LOCAL + "/lasers.pew"): testResults.append( test(open(LOCAL + "/lasers.pew").read() == "6", "Exercise 1: count the lasers.")) else: testResults.append(False) print("can't find lasers.pew, did you make it?" " Does it have exactly that file name?") print("{0}/{1} (passed/attempted)".format(sum(testResults), len(testResults))) if sum(testResults) == len(testResults): nyan_cat() message = "Rad, you've got all the tests passing!" completion_message(message, len(message) + 2) return {"of_total": len(testResults), "mark": sum(testResults)}
def theTests(path_to_code_to_check="."): """Run the tests.""" print("\nWelcome to week {}!".format(WEEK_NUMBER)) print("May the odds be ever in your favour.\n") path = "{}/week{}/exercise1.py".format(path_to_code_to_check, WEEK_NUMBER) print(path) exercise1 = imp.load_source("exercise1", path) testResults = [] # stack the tests below here print("Linter test:", path) testResults.append(test(test_flake8(path), "Exercise 1: pass the linter")) print("tr ", testResults) message = '{"message": "Python and requests are working!"}' testResults.append( test(exercise1.success_is_relative() == message, "Exercise 1: read a file using a relative path")) testDict = { 'lastName': u'hoogmoed', 'password': u'jokers', 'postcodePlusID': 4311240 } testResults.append( test(exercise1.get_some_details() == testDict, "Exercise 1: get some data out of a JSON file")) lengths = [3, 5, 7, 9, 11, 13, 15, 17, 19, 20, 18, 16, 14, 12, 10, 8, 6, 4] try: testResults.append( test([len(w) for w in exercise1.wordy_pyramid()] == lengths, "Exercise 1: request some simple data from the internet")) except Exception as e: testResults.append(0) print("Exercise 1: request some simple data from the internet", e) weather_results = { 'latitude': u'-33.924206', 'state': u'NSW', 'longitude': u'151.187912', 'local_tz_offset': u'+{}00'.format(int(tzOffset())) } try: ex_name = "Exercise 1: get some data from the weather underground." theirs = process_wunderground(exercise1.wunderground()) mine = process_wunderground(weather_results) print("you gave:", theirs) print("expected:", mine) testResults.append(test(theirs == mine, ex_name)) except Exception as e: testResults.append(0) print(ex_name, e) testResults.append( test(find_lasers(path_to_code_to_check), "Exercise 1: count the lasers.")) print("{0}/{1} (passed/attempted)".format(sum(testResults), len(testResults))) if sum(testResults) == len(testResults): nyan_cat() message = "Rad, you've got all the tests passing!" completion_message(message, len(message) + 2) treat() return { "of_total": len(testResults), "mark": sum(testResults), "results": testResults }
def theTests(path_to_code_to_check="."): """Run the tests.""" print("\nWelcome to week {}!".format(WEEK_NUMBER)) print("May the odds be ever in your favour.\n") testResults = [] # Tests from here: path = "exercise0.py" if ex_runs(path_to_code_to_check, exNumber=0, weekNumber=WEEK_NUMBER): exercise0 = imp.load_source("exercise0", path) testResults.append( test( exercise0.add_5(55) == 60, "Exercise 0: add_5 - 55 + 5 = 60?")) testResults.append( test(exercise0.add_5(-5) == 0, "Exercise 0: add_5 - -5 + 5 = 0?")) testResults.append( test( exercise0.add_5(0.1) == 5.1, "Exercise 0: add_5 - 0.1 + 5 = 5.1?")) testResults.append( test( exercise0.adder(5, 5) == 10, "Exercise 0: adder - 5 + 5 = 10?")) testResults.append( test( exercise0.adder(-5, -5) == -10, "Exercise 0: adder - -5 + -5 = -10?")) testResults.append( test( exercise0.adder(0.1, 0.9) == 1, "Exercise 0: adder - 0.1 + 0.9 = 1?")) testResults.append( test( exercise0.shout("you've") == "YOU'VE", "Exercise 0: shout - you've => YOU'VE?")) testResults.append( test( exercise0.shout("got") == "GOT", "Exercise 0: shout - got => GOT?")) testResults.append( test( exercise0.shout("to") == "TO", "Exercise 0: shout - to => TO?")) testResults.append( test( exercise0.really_shout("fight") == "FIGHT!", "Exercise 0: really_shout - fight => FIGHT!?")) testResults.append( test( exercise0.shout("for") == "FOR", "Exercise 0: shout - for => FOR?")) testResults.append( test( exercise0.shout("your") == "YOUR", "Exercise 0: shout - your => YOUR?")) testResults.append( test( exercise0.really_shout("right") == "RIGHT!", "Exercise 0: really_shout - right => RIGHT!?")) testResults.append( test( exercise0.shout("to") == "TO", "Exercise 0: shout - to => TO?")) testResults.append( test( exercise0.really_shout("PARTY") == "PARTY!", "Exercise 0: really_shout - PARTY => PARTY!?")) testResults.append( test( exercise0.shout_with_a_number("hi", 1) == "HI 1", "Exercise 0: shout_with_a_number - hi, 1 => HI 1?")) path = "exercise1.py".format(path_to_code_to_check, WEEK_NUMBER) path = "exercise2.py".format(path_to_code_to_check, WEEK_NUMBER) testResults.append( test(ex2runs(path_to_code_to_check), "Exercise 2: debug the file")) path = "exercise3.py".format(path_to_code_to_check, WEEK_NUMBER) if ex3runs(path_to_code_to_check): exercise3 = imp.load_source("exercise3", path) # is odd testResults.append( test( exercise3.is_odd(2) is False, "Exercise 3: is_odd - is 2 odd?")) testResults.append( test(exercise3.is_odd(5), "Exercise 3: is_odd - is 5 odd?")) # fix it testResults.append( test( exercise3.fix_it(True, True) == "No Problem", "Exercise 3: fix_it - it moves, and it should")) testResults.append( test( exercise3.fix_it(False, True) == "WD-40", "Exercise 3: fix_it - it doesn't move, and it should")) testResults.append( test( exercise3.fix_it(True, False) == "Duct Tape", "Exercise 3: fix_it - it moves, and it shouldn't")) testResults.append( test( exercise3.fix_it(False, False) == "No Problem", "Exercise 3: fix_it - it doesn't move, and it shouldn't")) # loops tenStars = ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*'] testResults.append( test(exercise3.loops_1a() == tenStars, "Exercise 3: loops_1a - 1d for loop")) testResults.append( test( exercise3.loops_1c(3, ":)") == [':)', ':)', ':)'], "Exercise 3: loops_1c - 1d with arguments")) ten_by_ten_stars = [ ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*'], ] testResults.append( test(exercise3.loops_2() == ten_by_ten_stars, "Exercise 3: loops_2 - 10×10 stars")) ten_matching_numbers = [ ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0'], ['1', '1', '1', '1', '1', '1', '1', '1', '1', '1'], ['2', '2', '2', '2', '2', '2', '2', '2', '2', '2'], ['3', '3', '3', '3', '3', '3', '3', '3', '3', '3'], ['4', '4', '4', '4', '4', '4', '4', '4', '4', '4'], ['5', '5', '5', '5', '5', '5', '5', '5', '5', '5'], ['6', '6', '6', '6', '6', '6', '6', '6', '6', '6'], ['7', '7', '7', '7', '7', '7', '7', '7', '7', '7'], ['8', '8', '8', '8', '8', '8', '8', '8', '8', '8'], ['9', '9', '9', '9', '9', '9', '9', '9', '9', '9'] ] testResults.append( test(exercise3.loops_3() == ten_matching_numbers, "Exercise 3: loops_3 - 10 matching lists")) ten_rising_lists = [['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']] testResults.append( test(exercise3.loops_4() == ten_rising_lists, "Exercise 3: loops_4 - ten rising lists")) coords = [['(i0, j0)', '(i0, j1)', '(i0, j2)', '(i0, j3)', '(i0, j4)'], ['(i1, j0)', '(i1, j1)', '(i1, j2)', '(i1, j3)', '(i1, j4)'], ['(i2, j0)', '(i2, j1)', '(i2, j2)', '(i2, j3)', '(i2, j4)'], ['(i3, j0)', '(i3, j1)', '(i3, j2)', '(i3, j3)', '(i3, j4)'], ['(i4, j0)', '(i4, j1)', '(i4, j2)', '(i4, j3)', '(i4, j4)'], ['(i5, j0)', '(i5, j1)', '(i5, j2)', '(i5, j3)', '(i5, j4)'], ['(i6, j0)', '(i6, j1)', '(i6, j2)', '(i6, j3)', '(i6, j4)'], ['(i7, j0)', '(i7, j1)', '(i7, j2)', '(i7, j3)', '(i7, j4)'], ['(i8, j0)', '(i8, j1)', '(i8, j2)', '(i8, j3)', '(i8, j4)'], ['(i9, j0)', '(i9, j1)', '(i9, j2)', '(i9, j3)', '(i9, j4)']] testResults.append( test(exercise3.loops_5() == coords, "Exercise 3: loops_5 - write the coords")) wedge = [['0'], ['0', '1'], ['0', '1', '2'], ['0', '1', '2', '3'], ['0', '1', '2', '3', '4'], ['0', '1', '2', '3', '4', '5'], ['0', '1', '2', '3', '4', '5', '6'], ['0', '1', '2', '3', '4', '5', '6', '7'], ['0', '1', '2', '3', '4', '5', '6', '7', '8'], ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']] testResults.append( test(exercise3.loops_6() == wedge, "Exercise 3: loops_6 - make a wedge")) pyramid = [[' ', ' ', ' ', ' ', '*', ' ', ' ', ' ', ' '], [' ', ' ', ' ', '*', '*', '*', ' ', ' ', ' '], [' ', ' ', '*', '*', '*', '*', '*', ' ', ' '], [' ', '*', '*', '*', '*', '*', '*', '*', ' '], ['*', '*', '*', '*', '*', '*', '*', '*', '*']] testResults.append( test(exercise3.loops_7() == pyramid, "Exercise 3: loops_7 - pyramid of stars")) testResults.append( test(lab_book_entry_completed(), "Lab book entry completed")) print("{0}/{1} (passed/attempted)".format(sum(testResults), len(testResults))) if sum(testResults) == len(testResults): print(nyan_cat()) message = "Rad, you've got all the tests passing!" completion_message(message, len(message) + 2) return { "of_total": len(testResults), "mark": sum(testResults), "results": testResults }
def theTests(path_to_code_to_check="."): """Run the tests.""" print("\nWelcome to week {}!".format(WEEK_NUMBER)) print("May the odds be ever in your favour.\n") path = "{}/week{}/exercise1.py".format(path_to_code_to_check, WEEK_NUMBER) print(path) exercise1 = loadExerciseFile( path_to_code_to_check, weekNumber=WEEK_NUMBER, exerciseNumber=1 ) testResults = [] # stack the tests below here testDict = {"lastName": "hoogmoed", "password": "******", "postcodePlusID": 4311240} testResults.append( test( exercise1.get_some_details() == testDict, "Exercise 1: get some data out of a JSON file", ) ) lengths = [3, 5, 7, 9, 11, 13, 15, 17, 19, 20, 18, 16, 14, 12, 10, 8, 6, 4] testName = "Exercise 1: request some words from the internet" try: pyramid = exercise1.wordy_pyramid() p_lengths = [len(w) for w in pyramid] if pyramid is not None: testResults.append(test(p_lengths == lengths, testName)) if p_lengths != lengths: print( pyramid, "Read the next line as (your word length, test word length)", list(zip(p_lengths, lengths)), p_lengths == lengths, sep="\n", ) else: testResults.append(test(False, testName)) print( "The tests didn't get anything back from your code, " "are you doing a return?" ) except Exception as e: testResults.append(test(False, testName)) print(testName, e) ex_name = "Exercise 1: Consult the Pokedex." poke_tries = [ { "args": (70, 80), "result": {"name": "victreebel", "weight": 155, "height": 17}, "gift": pokeball(), }, { "args": (9, 15), "result": {"name": "blastoise", "weight": 855, "height": 16}, "gift": tiny_pikachu(), }, { "args": (55, 57), "result": {"name": "golduck", "weight": 766, "height": 17}, "gift": squirtle(), }, { "args": (0, 3), "result": {"name": "ivysaur", "weight": 130, "height": 10}, "gift": pikachu(), }, ] for p in poke_tries: try: r = func_timeout( TIMEOUT_IN_SECONDS, exercise1.pokedex, args=list(p["args"]) ) if r == p["result"]: print(p["gift"]) else: print("expecting", p["result"], "got", r) testResults.append(test(r == p["result"], ex_name)) except FunctionTimedOut as ftoe: print( ex_name, ftoe, "check your numbers/ algorithm efficiency,", "or maybe just your internet speed.", "This shouldn't be taking so long", ) except Exception as e: testResults.append(0) print(ex_name, e) testResults.append( test(find_lasers(path_to_code_to_check), "Exercise 1: count the lasers.") ) message = "Rad, you've got all the tests passing!" return finish_up(testResults, message, nyan_cat())
] testResults.append( test(exercise3.loops_6() == wedge, "Exercise 3: loops_6 - make a wedge")) pyramid = [ [' ', ' ', ' ', ' ', '*', ' ', ' ', ' ', ' '], [' ', ' ', ' ', '*', '*', '*', ' ', ' ', ' '], [' ', ' ', '*', '*', '*', '*', '*', ' ', ' '], [' ', '*', '*', '*', '*', '*', '*', '*', ' '], ['*', '*', '*', '*', '*', '*', '*', '*', '*'] ] testResults.append( test(exercise3.loops_7() == pyramid, "Exercise 3: loops_7 - pyramid of stars")) testResults.append(test(lab_book_entry_completed(), "Lab book entry completed")) print("{0}/{1} (passed/attempted)".format(sum(testResults), len(testResults))) if sum(testResults) == len(testResults): print(nyan_cat()) message = "Rad, you've got all the tests passing!" completion_message(message, len(message) + 2) return {"of_total": len(testResults), "mark": sum(testResults), "results": testResults} if __name__ == "__main__": theTests() # no arg, runs tests on local code
def theTests(path_to_code_to_check: str = "../me"): """Run all the tests.""" print(f"\nWelcome to week {WEEK_NUMBER}!") print("May the odds be ever in your favour.\n") testResults = [] # Give each person 10 seconds to complete all tests. if ex_runs(path_to_code_to_check, exerciseNumber=1, weekNumber=WEEK_NUMBER): exercise1 = loadExerciseFile(path_to_code_to_check, weekNumber=WEEK_NUMBER, exerciseNumber=1) testResults.append( test( exercise1.loop_ranger(3, 8, 1) == [3, 4, 5, 6, 7], "Exercise 1: Loop ranger (3, 8, 1)", )) testResults.append( test( exercise1.loop_ranger(100, 104, 2) == [100, 102], "Exercise 1: Loop ranger (100, 104, 2)", )) testResults.append( test( exercise1.lone_ranger(3, 8, 1) == [3, 4, 5, 6, 7], "Exercise 1: Lone ranger (3, 8, 1)", )) testResults.append( test( exercise1.lone_ranger(100, 104, 2) == [100, 102], "Exercise 1: Lone ranger (100, 104, 2)", )) testResults.append( test( exercise1.two_step_ranger(100, 104) == [100, 102], "Exercise 1: Two step ranger (100, 104)", )) testResults.append( test( exercise1.two_step_ranger(0, 10) == [0, 2, 4, 6, 8], "Exercise 1: Two step ranger (100, 104)", )) # testResults.append( # test(exercise1.gene_krupa_range(0, 10, 2, 1) == # [0, 2, 3, 5, 6, 8, 9], # "Exercise 1: gene_krupa_range(0, 10, 2, 1)")) # testResults.append( # test(exercise1.gene_krupa_range(0, 100, 30, 7) == # [0, 30, 37, 67, 74], # "Exercise 1: gene_krupa_range(0, 100, 30, 7)")) testResults.append( test( test_stubborn_asker(path_to_code_to_check, 50, 60), "Exercise 1: Stubborn asker", )) testResults.append( test( test_stubborn_asker(path_to_code_to_check, 10, 20), "Exercise 1: Stubborn asker", )) testResults.append( test( test_not_number_rejector(path_to_code_to_check), "Exercise 1: not_number_rejector", )) testResults.append( test( test_super_asker(path_to_code_to_check, 50, 60), "Exercise 1: test_super_asker", )) testResults.append( test( test_example_guessingGame(path_to_code_to_check), "Exercise 2: example guessing game", )) if ex_runs(path_to_code_to_check, exerciseNumber=3, weekNumber=WEEK_NUMBER): exercise1 = loadExerciseFile(path_to_code_to_check, weekNumber=WEEK_NUMBER, exerciseNumber=3) lowerBound = 10 upperBound = 15 guesses = list(range(lowerBound, upperBound + 1)) mockInputs = [lowerBound] + [upperBound] + guesses testResults.append( test( test_advanced_guessingGame(path_to_code_to_check, mockInputs), "Exercise 3: guessing game, U&L", )) mockInputs = ["ten", lowerBound, upperBound, "cats"] + guesses testResults.append( test( test_advanced_guessingGame(path_to_code_to_check, mockInputs), "Exercise 3: guessing game, polite failures", )) secondGuess = 25 guesses = list(range(lowerBound, secondGuess + 1)) mockInputs = [lowerBound] + [upperBound] + [secondGuess] + guesses testResults.append( test( test_advanced_guessingGame(path_to_code_to_check, mockInputs), "Exercise 3: guessing game, lowerBound " "bigger than upperBound", )) lowerBound = 10 upperBound = 11 secondGuess = 15 guesses = list(range(lowerBound, secondGuess + 1)) mockInputs = [lowerBound] + [upperBound] + [secondGuess] + guesses testResults.append( test( test_advanced_guessingGame(path_to_code_to_check, mockInputs), "Exercise 3: guessing game, no " + "range to guess in (delta 1)", )) lowerBound = 10 upperBound = 10 secondGuess = 15 guesses = list(range(lowerBound, secondGuess + 1)) mockInputs = [lowerBound] + [upperBound] + [secondGuess] + guesses testResults.append( test( test_advanced_guessingGame(path_to_code_to_check, mockInputs), "Exercise 3: guessing game, no " + "range to guess in (equal)", )) if ex_runs(path_to_code_to_check, exerciseNumber=4, weekNumber=WEEK_NUMBER): exercise1 = loadExerciseFile(path_to_code_to_check, weekNumber=WEEK_NUMBER, exerciseNumber=4) try_these = [ (1, 100, 5, "Look low"), (1, 100, 6, "Look low"), (1, 100, 95, "Look high"), (1, 51, 5, "Look low"), (1, 50, 5, "Look low"), ] for _ in range(10): try_these.append( (0, 100, random.randint(1, 99), "randomly generated test value")) for test_vals in try_these: test_name = "Exercise 4: binary_search" test_desc = "(low: {}, high: {}, target: {}) {}".format(*test_vals) try: # *test_vals unpacks this tuple ----------------------- vvvvvvvvvv test_result = test_binary_search(path_to_code_to_check, *test_vals) message = f"{test_name} {test_desc}" testResults.append(test( test_result, message, )) except Exception: print("********\n\nfailed:", test_desc) print("tv failure", Exception) testResults.append(0) # if the binary search is working, show a graph of guess numbers if test(test_binary_search(path_to_code_to_check, 1, 10, 5, ""), ""): # If you aren't Ben, then show the histogram # if os.uname()[1] != "um": # um is ben's computer print("binary search works!") message = "Rad, you've got all the tests passing!" return finish_up(testResults, message, nyan_cat())
def theTests(path_to_code_to_check="../me"): """Run all the tests.""" print("\nWelcome to the exam!") print("May the odds be ever in your favour.\nEspecially today!") if ex_runs(path_to_code_to_check, exerciseNumber=1, weekNumber=WEEK_NUMBER): exam = loadExerciseFile( path_to_code_to_check, weekNumber=WEEK_NUMBER, exerciseNumber=1 ) # testResults.append(test(test_flake8(ex1path), "pass the linter")) exam_test("Hello the Queen", ["the Queen"], exam.greet) exam_test("Hello Pr♂nc♀♂", ["Pr♂nc♀♂"], exam.greet) exam_test(4, [[3, 3, 3, 3, 1]], exam.three_counter) exam_test(0, [[0, 1, 2, 5, -9]], exam.three_counter) # fmt: off fizza = [ 1, 2, "Fizz", 4, "Buzz", "Fizz", 7, 8, "Fizz", "Buzz", 11, "Fizz", 13, 14, "FizzBuzz", 16, 17, "Fizz", 19, "Buzz", "Fizz", 22, 23, "Fizz", "Buzz", 26, "Fizz", 28, 29, "FizzBuzz", 31, 32, "Fizz", 34, "Buzz", "Fizz", 37, 38, "Fizz", "Buzz", 41, "Fizz", 43, 44, "FizzBuzz", 46, 47, "Fizz", 49, "Buzz", "Fizz", 52, 53, "Fizz", "Buzz", 56, "Fizz", 58, 59, "FizzBuzz", 61, 62, "Fizz", 64, "Buzz", "Fizz", 67, 68, "Fizz", "Buzz", 71, "Fizz", 73, 74, "FizzBuzz", 76, 77, "Fizz", 79, "Buzz", "Fizz", 82, 83, "Fizz", "Buzz", 86, "Fizz", 88, 89, "FizzBuzz", 91, 92, "Fizz", 94, "Buzz", "Fizz", 97, 98, "Fizz", "Buzz", ] # fmt: on exam_test(fizza, [], exam.fizz_buzz) exam_test( "|a| |s|e|r|i|a|l| |k|i|l|l|e|r|", ["a serial killer"], exam.put_behind_bars ) exam_test("|a| |b|a|r|t|e|n|d|e|r|", ["a bartender"], exam.put_behind_bars) exam_test(["red fox"], ["x"], exam.pet_filter) exam_test([], ["q"], exam.pet_filter) exam_test( ["pig", "sheep", "guinea pig", "pigeon", "alpaca", "guppy"], ["p"], exam.pet_filter, ) exam_test("e", [], exam.best_letter_for_pets) word_lengths = [[3, 3, 3], [4, 4, 4], [5, 5, 5], [6, 6, 6], [7, 7, 7]] exam_test( word_lengths, [], exam.make_filler_text_dictionary, lambda x: [[len(w) for w in x[k]] for k in x.keys()], ) exam_test( True, [50], exam.random_filler_text, lambda x: len(x.split(" ")) == 50 and len(x) > 3 * 50, ) exam_test( True, [1000], exam.random_filler_text, lambda x: len(x.split(" ")) == 1000 and len(x) > 3 * 1000, ) clean_out_old_env() exam_test( True, [100], exam.fast_filler, lambda x: len(x.split(" ")) == 100 and len(x) > 3 * 100, # chdir=True, # NFI what this does :( ) # exam_test(True, ["./week8/dict_racey.json"], os.path.exists) exam_test( True, [10], exam.fast_filler, lambda x: x[0] in string.ascii_uppercase and x[1] in string.ascii_lowercase, "Test if fast_filler is capitalised", ) exam_test( True, [10], exam.fast_filler, lambda x: x[-1] == ".", "Test if fast_filler finishes with a .", ) print( "The point of saving the dictionary is that it's fast!", "The pattern of saving a value locally so that you don't", "need to go and get it is called caching.", "This test runs fast_filler 10 times, and if it manages it in less", "than a second, then you're good to go!", sep="\n", ) try: TIMEOUT_IN_SECONDS = 1 func_timeout( TIMEOUT_IN_SECONDS, lambda: [exam.fast_filler(1000) for _ in range(10)], args=[], ) testResults.append(test(True, "subsequent fast_filler")) except FunctionTimedOut as t: m = ( "Timed out trying to run fast filler 10 times in 1 second, " "subsequent fast_filler probably wasn't fast enough" ) print(m, str(t)) testResults.append(test(False, m + str(t))) except Exception as e: testResults.append(test(False, "subsequent fast_filler failed: " + str(e))) message = ( "Cowabunga! You've got all the tests passing!\n" "Well done, that's all the exercises for this term out of the way!" ) print(testResults) return finish_up(testResults, message, nyan_cat())
def theTests(path_to_code_to_check="."): """Run all the tests.""" print("\nWelcome to the exam!") print("May the odds be ever in your favour.\nEspecially today!") testResults = [] ex1path = "{}/week{}/exercise1.py".format(path_to_code_to_check, WEEK_NUMBER) if ex_runs(path_to_code_to_check, exNumber=1, weekNumber=WEEK_NUMBER): exam = imp.load_source("exercise1", ex1path) testResults.append( test(test_flake8(ex1path), "Pass the linter")) testResults.append( test(exam.greet("the Queen") == "Hello the Queen", "greet the Queen")) testResults.append( test(exam.greet("Pr♂nc♀♂") == "Hello Pr♂nc♀♂", "greet Pr♂nc♀♂")) testResults.append( test(exam.three_counter([3, 3, 3, 3, 1]) == 4, "three_counter [3, 3, 3, 3, 1]")) testResults.append( test(exam.three_counter([0, 1, 2, 5, -9]) == 0, "three_counter [0, 1, 2, 5, -9]")) fizza = [1, 2, 'Fizz', 4, 'Buzz', 'Fizz', 7, 8, 'Fizz', 'Buzz', 11, 'Fizz', 13, 14, 'FizzBuzz', 16, 17, 'Fizz', 19, 'Buzz', 'Fizz', 22, 23, 'Fizz', 'Buzz', 26, 'Fizz', 28, 29, 'FizzBuzz', 31, 32, 'Fizz', 34, 'Buzz', 'Fizz', 37, 38, 'Fizz', 'Buzz', 41, 'Fizz', 43, 44, 'FizzBuzz', 46, 47, 'Fizz', 49, 'Buzz', 'Fizz', 52, 53, 'Fizz', 'Buzz', 56, 'Fizz', 58, 59, 'FizzBuzz', 61, 62, 'Fizz', 64, 'Buzz', 'Fizz', 67, 68, 'Fizz', 'Buzz', 71, 'Fizz', 73, 74, 'FizzBuzz', 76, 77, 'Fizz', 79, 'Buzz', 'Fizz', 82, 83, 'Fizz', 'Buzz', 86, 'Fizz', 88, 89, 'FizzBuzz', 91, 92, 'Fizz', 94, 'Buzz', 'Fizz', 97, 98, 'Fizz', 'Buzz'] testResults.append( test(exam.fizz_buzz() == fizza, "fizz_buzz")) a = exam.put_behind_bars("a serial killer") testResults.append( test(a == "|a| |s|e|r|i|a|l| |k|i|l|l|e|r|", "put_behind_bars")) a = exam.put_behind_bars("a bartender") testResults.append( test(a == "|a| |b|a|r|t|e|n|d|e|r|", "put_behind_bars")) testResults.append( test(exam.pet_filter("x") == ['red fox'], "pet_filter")) testResults.append( test(exam.pet_filter("q") == [], "pet_filter")) testResults.append( test(exam.pet_filter("p") == ['pig', 'sheep', 'guinea pig', 'pigeon', 'alpaca', 'guppy'], "pet_filter")) testResults.append( test(exam.best_letter_for_pets() == "e", "best_letter_for_pets")) testResults.append( test(len(str(exam.make_filler_text_dictionary())) == 175, "make_filler_text_dictionary")) filler1 = exam.random_filler_text(50) testResults.append( test(len(filler1.split(" ")) == 50 and len(filler1) > 3*50, "random_filler_text")) filler2 = exam.fast_filler(1000) testResults.append( test(len(filler2.split(" ")) == 1000 and len(filler2) > 3*1000, "first fast_filler")) testResults.append( test(exam.fast_filler(10)[0] in string.uppercase and exam.fast_filler(10)[1] in string.lowercase, "first fast_filler has a starting capital")) testResults.append( test(exam.fast_filler(10)[-1] == ".", "first fast_filler ends with a .")) try: with Timeout(1): for _ in range(10): exam.fast_filler(1000) testResults.append( test(True, "subsiquent fast_filler")) except Exception as e: print(e) testResults.append( test(False, "subsiquent fast_filler wasn't fast enough")) print("{0}/{1} (passed/attempted)".format(sum(testResults), len(testResults))) if sum(testResults) == len(testResults): print(nyan_cat()) message = "Cowabunga! You've got all the tests passing!" completion_message(message, len(message) + 2) return {"of_total": len(testResults), "mark": sum(testResults), "results": testResults}
def theTests(path_to_code_to_check=".") -> dict: """Run the tests.""" print(f"\nWelcome to week {WEEK_NUMBER}!") print("May the odds be ever in your favour.\n") testResults = [] # stack the tests below here path = f"{path_to_code_to_check}/week{WEEK_NUMBER}/exercise1.py" print(path) exercise1 = loadExerciseFile(path_to_code_to_check, weekNumber=WEEK_NUMBER, exerciseNumber=1) # Linter test # print("Linter test:", path) # testResults.append( # test(test_flake8(path), # "Exercise 1: pass the linter")) # pydocstyle test # print("Docstyle test:", path) # testResults.append( # test(test_pydocstyle(path), # "Exercise 1: pass the pydocstyle test")) # countdown test book_of_counts = [ { "expect": """let's get ready to rumble 8 let's get ready to rumble 7 let's get ready to rumble 6 let's get ready to rumble 5 let's get ready to rumble 4 let's get ready to rumble 3 let's get ready to rumble 2 let's get ready to rumble 1 *rumbling sound* """, "input": { "message": "let's get ready to rumble", "start": 8, "stop": 1, "completion_message": "*rumbling sound*", }, }, { "expect": """prepare to die in this many ways: 4 prepare to die in this many ways: 3 prepare to die in this many ways: 2 or not, I guess """, "input": { "message": "prepare to die in this many ways:", "start": 5, "stop": 2, "completion_message": "or not, I guess", }, }, { "expect": """Getting ready to start in 9 Getting ready to start in 8 Getting ready to start in 7 Getting ready to start in 6 Getting ready to start in 5 Getting ready to start in 4 Getting ready to start in 3 Getting ready to start in 2 Getting ready to start in 1 Let's go! """, "input": { "message": "Getting ready to start in", "start": 9, "stop": 1, "completion_message": "Let's go!", }, }, ] for countdown in book_of_counts: try: # https://stackoverflow.com/a/34738440/1835727 capturedOutput = io.StringIO() # Create StringIO object sys.stdout = capturedOutput # and redirect stdout. exercise1.countdown(**countdown["input"]) # Call function. sys.stdout = sys.__stdout__ # Reset redirect. if capturedOutput.getvalue() != countdown["expect"]: print("Captured:\n" + capturedOutput.getvalue()) # Now works as before. print("Expected:\n" + countdown["expect"]) testResults.append( test( capturedOutput.getvalue() == countdown["expect"], "Exercise 1: countdown!! Output check", )) except Exception as e: sys.stdout = sys.__stdout__ # Reset redirect. print("countdown test failed", e) testResults.append( test(False, "Exercise 1: countdown!! Output check")) function_text = inspect.getsource(exercise1.countdown) countdown_function_body = "".join(function_text) testResults.append( test( countdown_function_body.count("print") <= 2, "Exercise 1: countdown!! rewrite content - fewer print calls", )) if countdown_function_body.count("print") > 2: print(function_text) print( "do you really need all those calls to print?", "Could you get by with only 2?", ) triangles = [ { "area": 6.0, "aspect": "tall", "base": 3, "height": 4, "hypotenuse": 5.0, "perimeter": 12.0, "units": "mm", }, { "area": 15, "aspect": "wide", "base": 10, "height": 3, "hypotenuse": 10.44030650891055, "perimeter": 23.440306508910552, "units": "mm", }, { "area": 60.0, "aspect": "tall", "base": 8, "height": 15, "hypotenuse": 17.0, "perimeter": 40.0, "units": "mm", }, { "area": 12.5, "aspect": "equal", "base": 5, "height": 5, "hypotenuse": 7.0710678118654755, "perimeter": 17.071067811865476, "units": "mm", }, { "area": 180.0, "aspect": "tall", "base": 9, "height": 40, "hypotenuse": 41.0, "perimeter": 90.0, "units": "mm", }, ] pattern = "Exercise {}: {}: {}×{}⇨{}" for t in triangles: hyp = exercise1.calculate_hypotenuse(t["base"], t["height"]) testResults.append( test( hyp == t["hypotenuse"], pattern.format(1, "calculate_hypotenuse", t["base"], t["height"], t["hypotenuse"]), )) if hyp != t["hypotenuse"]: print(f"You said that a b{t['base']}×h{t['height']} " f"right triangle has a hyp of ⇨ {hyp}") area = exercise1.calculate_area(t["base"], t["height"]) testResults.append( test( area == t["area"], pattern.format(1, "calculate_area", t["base"], t["height"], t["area"]), )) if area != t["area"]: print(f"You said that a b{t['base']}×h{t['height']} " f"right triangle has n area of ⇨ {area}") aspect = exercise1.calculate_aspect(t["base"], t["height"]) testResults.append( test( aspect == t["aspect"], pattern.format(1, "calculate_aspect", t["base"], t["height"], t["aspect"]), )) perimeter = exercise1.calculate_perimeter(t["base"], t["height"]) testResults.append( test( perimeter == t["perimeter"], pattern.format(1, "calculate_perimeter", t["base"], t["height"], t["perimeter"]), )) facts = exercise1.get_triangle_facts(t["base"], t["height"]) testResults.append( test( facts == t, pattern.format(1, "get_triangle_facts", t["base"], t["height"], t), )) facts = exercise1.get_triangle_facts(t["base"], t["height"]) diagram = exercise1.tell_me_about_this_right_triangle(facts) testName = "exercise 1: draw a diagram\n" + str(diagram) testResults.append( test(test_diagrams(diagram=diagram, expected=facts["aspect"]), testName)) ff = exercise1.triangle_master(base=5, height=5, return_diagram=False, return_dictionary=False) testResults.append( test(ff is None, "exercise 1: triangle_master diagram: False, dictionary: False")) tf = exercise1.triangle_master(base=5, height=5, return_diagram=True, return_dictionary=False) testResults.append( test( type(tf) is str, "exercise 1: triangle_master diagram: True, dictionary: False", )) ft = exercise1.triangle_master(base=5, height=5, return_diagram=False, return_dictionary=True) testResults.append( test( type(ft) is dict, "exercise 1: triangle_master diagram: False, dictionary: True" " -- type(ft) is dict", )) try: testResults.append( test( "units" in ft, "exercise 1: triangle_master diagram: False, dictionary: True" ' -- "units" in ft["facts"]', )) except Exception as e: testResults.append( test( False, "exercise 1: triangle_master diagram: False, dictionary: True" ' -- "units" in ft["facts"]', )) tt = exercise1.triangle_master(base=5, height=5, return_diagram=True, return_dictionary=True) try: testResults.append( test( type(tt) is dict and type(tt["diagram"]) is str, "exercise 1: triangle_master diagram: T, dictionary: T", )) except Exception as e: print(e) testResults.append( test(False, "exercise 1: triangle_master diagram: T, dictionary: T")) pattern = "Exercise 1: get_triangle_facts uses {}" for function_name in [ "calculate_hypotenuse", "calculate_area", "calculate_perimeter", "calculate_aspect", ]: testResults.append( test( function_name in exercise1.get_triangle_facts.__code__.co_names, pattern.format(function_name), )) for length in zip([5, 8, 4, 0, "a"], [5, 8, 4, None, None]): try: word = exercise1.get_a_word_of_length_n(length[0]) testResults.append( test( test_word_length(word=word, requested_length=length[0], expected_length=length[1]), f"exercise 1: get_a_word_of_length_n {word}", )) except Exception as e: print(e) testResults.append( test(False, f"exercise 1: get_a_word_of_length_n {length}")) some_lengths = [[4, 5, 6], [4, 18, 4]] for lengths in some_lengths: try: words = exercise1.list_of_words_with_lengths(lengths) if words is not None: checks = [len(x[0]) == x[1] for x in zip(words, lengths)] else: checks = [False] print(words, lengths, checks) testResults.append( test( all(checks), "exercise 1: list_of_words_with_lengths {word}", )) except Exception as e: print(e) testResults.append( test(False, f"exercise 1: list_of_words_with_lengths {lengths}")) try: testResults.append( test( "list_of_words_with_lengths" in exercise1.wordy_pyramid.__code__.co_names, "exercise 1: wordy_pyramid has been refactored", # write a better error message )) except Exception as e: testResults.append( test(False, "exercise 1: wordy_pyramid has been refactored")) lengths = [3, 5, 7, 9, 11, 13, 15, 17, 19, 20, 18, 16, 14, 12, 10, 8, 6, 4] works = None try: words = exercise1.wordy_pyramid() expected = [len(w) for w in words] works = expected == lengths print("expected ", expected, "\ngiven lengths", lengths) [print(w + " " + str(len(w))) for w in words] except Exception as e: works = False print("Exercise 1: wordy_pyramid is broken", e) testResults.append(test(works, "Exercise 1: wordy_pyramid still works")) # EXERCISE 2 tests path = f"{path_to_code_to_check}/week{WEEK_NUMBER}/exercise2.py" print(path) e2 = loadExerciseFile(path_to_code_to_check, weekNumber=WEEK_NUMBER, exerciseNumber=2) # Linter test # print("Linter test:", path) # testResults.append( # test(test_flake8(path), # "Exercise 2: pass the linter")) # pydocstyle test # print("Docstyle test:", path) # testResults.append( # test(test_pydocstyle(path), # "Exercise 2: pass the pydocstyle test")) source = ["baaab", "b", "roof", "hell"] result = [ "bbaoaaobaobaobbbaaobaobbbaaobaobbbabbaoaaob", "bbaoaaob", "roabbaoabbaf", "hell", ] for source, result in zip(source, result): try: testResults.append( test( e2.abba(source, 2) == result, f"exercise 2: abba {source}⇨{result}")) except Exception as e: testResults.append( test(False, f"exercise 2: abba {source}⇨{result}")) testResults.append( test( e2.draw_square(2) == "2100000100000100000100000100000", "exercise 2: Koch _|-|_", )) testResults.append( test( e2.draw_pointy(2) == "210000100001000010000", "exercise 2: Koch _^_")) # CLEANUP AND FINISH message = "Rad, you've got all the tests passing!" return finish_up(testResults, message, nyan_cat())
def theTests(path_to_code_to_check="."): """Run the tests.""" print("\nWelcome to week {}!".format(WEEK_NUMBER)) print("May the odds be ever in your favour.\n") testResults = [] path = "{}/week{}/exercise1.py".format(path_to_code_to_check, WEEK_NUMBER) testResults.append( test(test_flake8(path), "Exercise 1: pass the linter")) path = "{}/week{}/exercise2.py".format(path_to_code_to_check, WEEK_NUMBER) testResults.append( test(test_flake8(path), "Exercise 2: pass the linter")) testResults.append( test(ex2runs(path_to_code_to_check), "Exercise 2: debug the file")) path = "{}/week{}/exercise3.py".format(path_to_code_to_check, WEEK_NUMBER) testResults.append( test(test_flake8(path), "Exercise 3: pass the linter")) if ex3runs(path_to_code_to_check): exercise3 = imp.load_source("exercise3", path) # is odd testResults.append( test(exercise3.is_odd(2) is False, "Exercise 3: is_odd - is 2 odd?")) testResults.append( test(exercise3.is_odd(5), "Exercise 3: is_odd - is 5 odd?")) # fix it testResults.append( test(exercise3.fix_it(True, True) == "No Problem", "Exercise 3: fix_it - it moves, and it should")) testResults.append( test(exercise3.fix_it(False, True) == "WD-40", "Exercise 3: fix_it - it doesn't move, and it should")) testResults.append( test(exercise3.fix_it(True, False) == "Duct Tape", "Exercise 3: fix_it - it moves, and it shouldn't")) testResults.append( test(exercise3.fix_it(False, False) == "No Problem", "Exercise 3: fix_it - it doesn't move, and it shouldn't")) # loops tenStars = ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*'] testResults.append( test(exercise3.loops_1a() == tenStars, "Exercise 3: loops_1a - 1d for loop")) bang_star = ["!", "*", "!", "*", "!", "*", "!", "*", "!", "*"] testResults.append( test('map' in exercise3.star_map.func_code.co_names and exercise3.star_map() == bang_star, "Exercise 3: loops_1b - 1d map")) testResults.append( test(exercise3.loops_1c(3, ":)") == [':)', ':)', ':)'], "Exercise 3: loops_1c - 1d with arguments")) ten_by_ten_stars = [ ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*'], ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*'], ] testResults.append( test(exercise3.loops_2() == ten_by_ten_stars, "Exercise 3: loops_2 - 10×10 stars")) ten_matching_numbers = [ ['0', '0', '0', '0', '0', '0', '0', '0', '0', '0'], ['1', '1', '1', '1', '1', '1', '1', '1', '1', '1'], ['2', '2', '2', '2', '2', '2', '2', '2', '2', '2'], ['3', '3', '3', '3', '3', '3', '3', '3', '3', '3'], ['4', '4', '4', '4', '4', '4', '4', '4', '4', '4'], ['5', '5', '5', '5', '5', '5', '5', '5', '5', '5'], ['6', '6', '6', '6', '6', '6', '6', '6', '6', '6'], ['7', '7', '7', '7', '7', '7', '7', '7', '7', '7'], ['8', '8', '8', '8', '8', '8', '8', '8', '8', '8'], ['9', '9', '9', '9', '9', '9', '9', '9', '9', '9'] ] testResults.append( test(exercise3.loops_3() == ten_matching_numbers, "Exercise 3: loops_3 - 10 matching lists")) ten_rising_lists = [ ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] ] testResults.append( test(exercise3.loops_4() == ten_rising_lists, "Exercise 3: loops_4 - ten rising lists")) coords = [ ['(i0, j0)', '(i0, j1)', '(i0, j2)', '(i0, j3)', '(i0, j4)'], ['(i1, j0)', '(i1, j1)', '(i1, j2)', '(i1, j3)', '(i1, j4)'], ['(i2, j0)', '(i2, j1)', '(i2, j2)', '(i2, j3)', '(i2, j4)'], ['(i3, j0)', '(i3, j1)', '(i3, j2)', '(i3, j3)', '(i3, j4)'], ['(i4, j0)', '(i4, j1)', '(i4, j2)', '(i4, j3)', '(i4, j4)'], ['(i5, j0)', '(i5, j1)', '(i5, j2)', '(i5, j3)', '(i5, j4)'], ['(i6, j0)', '(i6, j1)', '(i6, j2)', '(i6, j3)', '(i6, j4)'], ['(i7, j0)', '(i7, j1)', '(i7, j2)', '(i7, j3)', '(i7, j4)'], ['(i8, j0)', '(i8, j1)', '(i8, j2)', '(i8, j3)', '(i8, j4)'], ['(i9, j0)', '(i9, j1)', '(i9, j2)', '(i9, j3)', '(i9, j4)'] ] testResults.append( test(exercise3.loops_5() == coords, "Exercise 3: loops_5 - write the coords")) wedge = [ ['0'], ['0', '1'], ['0', '1', '2'], ['0', '1', '2', '3'], ['0', '1', '2', '3', '4'], ['0', '1', '2', '3', '4', '5'], ['0', '1', '2', '3', '4', '5', '6'], ['0', '1', '2', '3', '4', '5', '6', '7'], ['0', '1', '2', '3', '4', '5', '6', '7', '8'], ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] ] testResults.append( test(exercise3.loops_6() == wedge, "Exercise 3: loops_6 - make a wedge")) pyramid = [ [' ', ' ', ' ', ' ', '*', ' ', ' ', ' ', ' '], [' ', ' ', ' ', '*', '*', '*', ' ', ' ', ' '], [' ', ' ', '*', '*', '*', '*', '*', ' ', ' '], [' ', '*', '*', '*', '*', '*', '*', '*', ' '], ['*', '*', '*', '*', '*', '*', '*', '*', '*'] ] testResults.append( test(exercise3.loops_7() == pyramid, "Exercise 3: loops_7 - pyramid of stars")) print("{0}/{1} (passed/attempted)".format(sum(testResults), len(testResults))) if sum(testResults) == len(testResults): print(nyan_cat()) message = "Rad, you've got all the tests passing!" completion_message(message, len(message) + 2) return {"of_total": len(testResults), "mark": sum(testResults), "results": testResults}
def theTests(path_to_code_to_check="."): """Run the tests.""" print("\nWelcome to week {}!".format(WEEK_NUMBER)) print("May the odds be ever in your favour.\n") testResults = [] # stack the tests below here path = "{}/week{}/exercise1.py".format(path_to_code_to_check, WEEK_NUMBER) print(path) e1 = imp.load_source("exercise1", path) # Linter test # print("Linter test:", path) # testResults.append( # test(test_flake8(path), # "Exercise 1: pass the linter")) # pydocstyle test # print("Docstyle test:", path) # testResults.append( # test(test_pydocstyle(path), # "Exercise 1: pass the pydocstyle test")) # countdown test book_of_counts = [{ "message": "let's get ready to rumble", "start": 8, "stop": 1, "completion_message": "*rumbling sound*" }, { "message": "prepare to die in this many ways:", "start": 0, "stop": 15, "completion_message": "or not, I guess" }] for countdown in book_of_counts: try: the_countdown = e1.countdown(**countdown) if (len(the_countdown) > 0): [print(x) for x in the_countdown] else: print("Nothing to see here yet") expected = abs(countdown["start"] - countdown["stop"]) + 1 testResults.append( test( len(the_countdown) == expected, "Exercise 1: countdown!!")) except Exception as e: print("countdown test failed", e) testResults.append(FAIL) triangles = [{ 'area': 6.0, 'aspect': 'tall', 'base': 3, 'height': 4, 'hypotenuse': 5.0, 'perimeter': 12.0, 'units': 'mm' }, { 'area': 15, 'aspect': 'wide', 'base': 10, 'height': 3, 'hypotenuse': 10.44030650891055, 'perimeter': 23.440306508910552, 'units': 'mm' }, { 'area': 60.0, 'aspect': 'tall', 'base': 8, 'height': 15, 'hypotenuse': 17.0, 'perimeter': 40.0, 'units': 'mm' }, { 'area': 12.5, 'aspect': 'equal', 'base': 5, 'height': 5, 'hypotenuse': 7.0710678118654755, 'perimeter': 17.071067811865476, 'units': 'mm' }, { 'area': 180.0, 'aspect': 'tall', 'base': 9, 'height': 40, 'hypotenuse': 41.0, 'perimeter': 90.0, 'units': 'mm' }] pattern = "Exercise {}: {}: {}×{}⇨{}" for t in triangles: hyp = e1.calculate_hypotenuse(t["base"], t["height"]) testResults.append( test( hyp == t["hypotenuse"], pattern.format(1, "calculate_hypotenuse", t["base"], t["height"], t["hypotenuse"]))) area = e1.calculate_area(t["base"], t["height"]) testResults.append( test( area == t["area"], pattern.format(1, "calculate_area", t["base"], t["height"], t["area"]))) aspect = e1.calculate_aspect(t["base"], t["height"]) testResults.append( test( aspect == t["aspect"], pattern.format(1, "calculate_aspect", t["base"], t["height"], t["aspect"]))) perimeter = e1.calculate_perimeter(t["base"], t["height"]) testResults.append( test( perimeter == t["perimeter"], pattern.format(1, "calculate_perimeter", t["base"], t["height"], t["perimeter"]))) facts = e1.get_triangle_facts(t["base"], t["height"]) testResults.append( test( facts == t, pattern.format(1, "get_triangle_facts", t["base"], t["height"], t))) facts = e1.get_triangle_facts(t["base"], t["height"]) diagram = e1.tell_me_about_this_right_triangle(facts) testResults.append( test(test_diagrams(diagram=diagram, expected=facts["aspect"]), "exercise 1: draw a diagram\n" + diagram)) ff = e1.triangle_master(base=5, height=5, return_diagram=False, return_dictionary=False) tf = e1.triangle_master(base=5, height=5, return_diagram=True, return_dictionary=False) ft = e1.triangle_master(base=5, height=5, return_diagram=False, return_dictionary=True) tt = e1.triangle_master(base=5, height=5, return_diagram=True, return_dictionary=True) testResults.append( test(ff is None, "exercise 1: triangle_master diagram: F, dictionary: F")) testResults.append( test( type(tf) is str, "exercise 1: triangle_master diagram: T, dictionary: F")) testResults.append( test( type(ft) is dict and "units" in ft["facts"] and type(ft["facts"]) is dict, "exercise 1: triangle_master diagram: F, dictionary: T")) testResults.append( test( type(tt) is dict and type(tt["diagram"]) is str, "exercise 1: triangle_master diagram: T, dictionary: T")) pattern = "Exercise 1: get_triangle_facts uses {}" for function_name in [ "calculate_hypotenuse", "calculate_area", "calculate_perimeter", "calculate_aspect" ]: testResults.append( test(function_name in e1.get_triangle_facts.__code__.co_names, pattern.format(function_name))) for length in zip([5, 8, 4, 0, "a"], [5, 8, 4, None, None]): word = e1.get_a_word_of_length_n(length[0]) print(word, length) testResults.append( test( test_word_length(word=word, requested_length=length[0], expected_length=length[1]), "exercise 1: get_a_word_of_length_n {}".format(word))) some_lengths = [[4, 5, 6], [4, 18, 4]] for lengths in some_lengths: words = e1.list_of_words_with_lengths(lengths) checks = [len(x[0]) == x[1] for x in zip(words, lengths)] print(words, lengths, checks) testResults.append( test(all(checks), "exercise 1: list_of_words_with_lengths {}".format(word))) testResults.append( test( "list_of_words_with_lengths" in e1.wordy_pyramid.__code__.co_names, "exercise 1: wordy_pyramid has been refactored")) lengths = [3, 5, 7, 9, 11, 13, 15, 17, 19, 20, 18, 16, 14, 12, 10, 8, 6, 4] works = None try: words = e1.wordy_pyramid() expected = [len(w) for w in words] works = expected == lengths print("expected ", expected, "\ngiven lengths", lengths) [print(w + " " + str(len(w))) for w in words] except Exception as e: works = False print("Exercise 1: wordy_pyramid is broken", e) testResults.append(test(works, "Exercise 1: wordy_pyramid still works")) # EXERCISE 2 tests path = "{}/week{}/exercise2.py".format(path_to_code_to_check, WEEK_NUMBER) print(path) e2 = imp.load_source("exercise2", path) # Linter test # print("Linter test:", path) # testResults.append( # test(test_flake8(path), # "Exercise 2: pass the linter")) # pydocstyle test # print("Docstyle test:", path) # testResults.append( # test(test_pydocstyle(path), # "Exercise 2: pass the pydocstyle test")) source = ["baaab", "b", "roof", "hell"] result = [ "bbaoaaobaobaobbbaaobaobbbaaobaobbbabbaoaaob", "bbaoaaob", "roabbaoabbaf", "hell" ] for source, result in zip(source, result): testResults.append( test( e2.abba(source, 2) == result, "exercise 2: abba {}⇨{}".format(source, result))) testResults.append( test( e2.draw_square(2) == "2100000100000100000100000100000", "exercise 2: Koch _|-|_")) testResults.append( test( e2.draw_pointy(2) == "210000100001000010000", "exercise 2: Koch _^_")) # CLEANUP AND FINISH print("{0}/{1} (passed/attempted)".format(sum(testResults), len(testResults))) if sum(testResults) == len(testResults): nyan_cat() message = "Rad, you've got all the tests passing!" completion_message(message, len(message) + 2) # treat() return { "of_total": len(testResults), "mark": sum(testResults), "results": testResults }
def theTests(path_to_code_to_check="../me"): """Run the tests.""" print("\nWelcome to week {}!".format(WEEK_NUMBER)) print("May the odds be ever in your favour.\n") testResults = [] # Tests from here: if ex_runs(path_to_code_to_check, exerciseNumber=0, weekNumber=WEEK_NUMBER): exercise0 = loadExerciseFile(path_to_code_to_check, weekNumber=WEEK_NUMBER, exerciseNumber=0) testResults.append( test(exercise0.add_1(55) == 56, "Exercise 0: add_1 - 55 + 1 = 56")) testResults.append( test(exercise0.add_1(-5) == -4, "Exercise 0: add_1 - -5 + 1 = -4")) testResults.append( test( exercise0.add_1(0.1) == 1.1, "Exercise 0: add_1 - 0.1 + 1 = 1.1")) testResults.append( test(exercise0.add_5(55) == 60, "Exercise 0: add_5 - 55 + 5 = 60")) testResults.append( test(exercise0.add_5(-5) == 0, "Exercise 0: add_5 - -5 + 5 = 0")) testResults.append( test( exercise0.add_5(0.1) == 5.1, "Exercise 0: add_5 - 0.1 + 5 = 5.1")) testResults.append( test( exercise0.adder(5, 5) == 10, "Exercise 0: adder - 5 + 5 = 10")) testResults.append( test( exercise0.adder(-5, -5) == -10, "Exercise 0: adder - -5 + -5 = -10")) testResults.append( test( exercise0.adder(0.1, 0.9) == 1, "Exercise 0: adder - 0.1 + 0.9 = 1")) testResults.append( test( exercise0.shout("you've") == "YOU'VE", "Exercise 0: shout - you've => YOU'VE", )) testResults.append( test( exercise0.shout("got") == "GOT", "Exercise 0: shout - got => GOT")) testResults.append( test( exercise0.shout("to") == "TO", "Exercise 0: shout - to => TO")) testResults.append( test( exercise0.really_shout("fight") == "FIGHT!", "Exercise 0: really_shout - fight => FIGHT!", )) testResults.append( test( exercise0.shout("for") == "FOR", "Exercise 0: shout - for => FOR")) testResults.append( test( exercise0.shout("your") == "YOUR", "Exercise 0: shout - your => YOUR")) testResults.append( test( exercise0.really_shout("right") == "RIGHT!", "Exercise 0: really_shout - right => RIGHT!", )) testResults.append( test( exercise0.shout("to") == "TO", "Exercise 0: shout - to => TO")) testResults.append( test( exercise0.really_shout("PARTY") == "PARTY!", "Exercise 0: really_shout - PARTY => PARTY!", )) testResults.append( test( exercise0.shout_with_a_number("hi", 1) == "HI 1", "Exercise 0: shout_with_a_number - hi, 1 => HI 1", )) ex2_runs = ex_runs(path_to_code_to_check, exerciseNumber=2, weekNumber=WEEK_NUMBER) if not ex2_runs: print( "Don't worry, exercise 2 comes with errors. It's your job to fix them!" ) testResults.append(test(ex2_runs, "Exercise 2: debug the file")) if ex_runs(path_to_code_to_check, exerciseNumber=3, weekNumber=WEEK_NUMBER): exercise3 = loadExerciseFile(path_to_code_to_check, weekNumber=2, exerciseNumber=3) # is odd testResults.append( test( exercise3.is_odd(2) is False, "Exercise 3: is_odd - is 2 odd")) testResults.append( test(exercise3.is_odd(5), "Exercise 3: is_odd - is 5 odd")) # fix it testResults.append( test( exercise3.fix_it(True, True) == "No Problem", "Exercise 3: fix_it - it moves, and it should", )) testResults.append( test( exercise3.fix_it(False, True) == "WD-40", "Exercise 3: fix_it - it doesn't move, and it should", )) testResults.append( test( exercise3.fix_it(True, False) == "Duct Tape", "Exercise 3: fix_it - it moves, and it shouldn't", )) testResults.append( test( exercise3.fix_it(False, False) == "No Problem", "Exercise 3: fix_it - it doesn't move, and it shouldn't", )) # loops tenStars = ["*", "*", "*", "*", "*", "*", "*", "*", "*", "*"] result = exercise3.loops_1a() == tenStars testResults.append(test(result, "Exercise 3: loops_1a - 1d for loop")) if not result: fail = exercise3.loops_1a() print(("{norm}You're returning {em}{f}{norm}. " "We're looking for {em}{p}{norm}").format(f=fail, p=tenStars, em=EM, norm=NORM)) if fail == None: print(( "{norm}Do you have a line that says " "{em}return the_answer{norm}?\n" "Or maybe you have a line that says {em}return None{norm}?" "Or you are returning a variable that has the value {em}return None{norm}?\n" "You need to return the computed value, so either assign " "it to a variable and return that, or return it directly." ).format(em=EM, norm=NORM)) if fail == "**********": print("remember that we're looking for a list") # TODO: write more failure modes as they come up in testing. testResults.append( test( exercise3.loops_1c(3, ":)") == [":)", ":)", ":)"], "Exercise 3: loops_1c - 1d with arguments", )) ten_by_ten_stars = [ ["*", "*", "*", "*", "*", "*", "*", "*", "*", "*"], ["*", "*", "*", "*", "*", "*", "*", "*", "*", "*"], ["*", "*", "*", "*", "*", "*", "*", "*", "*", "*"], ["*", "*", "*", "*", "*", "*", "*", "*", "*", "*"], ["*", "*", "*", "*", "*", "*", "*", "*", "*", "*"], ["*", "*", "*", "*", "*", "*", "*", "*", "*", "*"], ["*", "*", "*", "*", "*", "*", "*", "*", "*", "*"], ["*", "*", "*", "*", "*", "*", "*", "*", "*", "*"], ["*", "*", "*", "*", "*", "*", "*", "*", "*", "*"], ["*", "*", "*", "*", "*", "*", "*", "*", "*", "*"], ] testResults.append( test( exercise3.loops_2() == ten_by_ten_stars, "Exercise 3: loops_2 - 10×10 stars", )) ten_matching_numbers = [ ["0", "0", "0", "0", "0", "0", "0", "0", "0", "0"], ["1", "1", "1", "1", "1", "1", "1", "1", "1", "1"], ["2", "2", "2", "2", "2", "2", "2", "2", "2", "2"], ["3", "3", "3", "3", "3", "3", "3", "3", "3", "3"], ["4", "4", "4", "4", "4", "4", "4", "4", "4", "4"], ["5", "5", "5", "5", "5", "5", "5", "5", "5", "5"], ["6", "6", "6", "6", "6", "6", "6", "6", "6", "6"], ["7", "7", "7", "7", "7", "7", "7", "7", "7", "7"], ["8", "8", "8", "8", "8", "8", "8", "8", "8", "8"], ["9", "9", "9", "9", "9", "9", "9", "9", "9", "9"], ] testResults.append( test( exercise3.loops_3() == ten_matching_numbers, "Exercise 3: loops_3 - 10 matching lists", )) ten_rising_lists = [ ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], ] testResults.append( test( exercise3.loops_4() == ten_rising_lists, "Exercise 3: loops_4 - ten rising lists", )) coords = [ ["(i0, j0)", "(i0, j1)", "(i0, j2)", "(i0, j3)", "(i0, j4)"], ["(i1, j0)", "(i1, j1)", "(i1, j2)", "(i1, j3)", "(i1, j4)"], ["(i2, j0)", "(i2, j1)", "(i2, j2)", "(i2, j3)", "(i2, j4)"], ["(i3, j0)", "(i3, j1)", "(i3, j2)", "(i3, j3)", "(i3, j4)"], ["(i4, j0)", "(i4, j1)", "(i4, j2)", "(i4, j3)", "(i4, j4)"], ["(i5, j0)", "(i5, j1)", "(i5, j2)", "(i5, j3)", "(i5, j4)"], ["(i6, j0)", "(i6, j1)", "(i6, j2)", "(i6, j3)", "(i6, j4)"], ["(i7, j0)", "(i7, j1)", "(i7, j2)", "(i7, j3)", "(i7, j4)"], ["(i8, j0)", "(i8, j1)", "(i8, j2)", "(i8, j3)", "(i8, j4)"], ["(i9, j0)", "(i9, j1)", "(i9, j2)", "(i9, j3)", "(i9, j4)"], ] testResults.append( test(exercise3.loops_5() == coords, "Exercise 3: loops_5 - write the coords")) wedge = [ ["0"], ["0", "1"], ["0", "1", "2"], ["0", "1", "2", "3"], ["0", "1", "2", "3", "4"], ["0", "1", "2", "3", "4", "5"], ["0", "1", "2", "3", "4", "5", "6"], ["0", "1", "2", "3", "4", "5", "6", "7"], ["0", "1", "2", "3", "4", "5", "6", "7", "8"], ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], ] testResults.append( test(exercise3.loops_6() == wedge, "Exercise 3: loops_6 - make a wedge")) pyramid = [ [" ", " ", " ", " ", "*", " ", " ", " ", " "], [" ", " ", " ", "*", "*", "*", " ", " ", " "], [" ", " ", "*", "*", "*", "*", "*", " ", " "], [" ", "*", "*", "*", "*", "*", "*", "*", " "], ["*", "*", "*", "*", "*", "*", "*", "*", "*"], ] testResults.append( test(exercise3.loops_7() == pyramid, "Exercise 3: loops_7 - pyramid of stars")) testResults.append( test( lab_book_entry_completed(WEEK_NUMBER, path_to_code_to_check), "Lab book entry completed", )) message = "Rad, you've got all the tests passing!" return finish_up(testResults, message, nyan_cat())
def theTests(path_to_code_to_check=""): """Run all the tests.""" print("\nWelcome to week {}!".format(WEEK_NUMBER)) print("May the odds be ever in your favour.\n") testResults = [] testResults.append( test(test_flake8("week{}/exercise1.py".format(WEEK_NUMBER)), "Exercise 1: pass the linter")) if ex1runs(): import exercise1 testResults.append( test( exercise1.loop_ranger(3, 8, 1) == [3, 4, 5, 6, 7], "Exercise 1: Loop ranger (3, 8, 1)")) testResults.append( test( exercise1.loop_ranger(100, 104, 2) == [100, 102], "Exercise 1: Loop ranger (100, 104, 2)")) testResults.append( test( exercise1.lone_ranger(3, 8, 1) == [3, 4, 5, 6, 7], "Exercise 1: Lone ranger (3, 8, 1)")) testResults.append( test( exercise1.lone_ranger(100, 104, 2) == [100, 102], "Exercise 1: Lone ranger (100, 104, 2)")) testResults.append( test( exercise1.two_step_ranger(100, 104) == [100, 102], "Exercise 1: Two step ranger (100, 104)")) testResults.append( test( exercise1.two_step_ranger(0, 10) == [0, 2, 4, 6, 8], "Exercise 1: Two step ranger (100, 104)")) testResults.append( test( exercise1.gene_krupa_range(0, 10, 2, 1) == [0, 2, 3, 5, 6, 8, 9], "Exercise 1: gene_krupa_range (0, 10, 2, 1)")) testResults.append( test( exercise1.gene_krupa_range(0, 100, 30, 7) == [0, 30, 37, 67, 74], "Exercise 1: gene_krupa_range (0, 10, 2, 1)")) testResults.append( test(test_stubborn_asker(50, 60), "Exercise 1: Stubborn asker")) testResults.append( test(test_stubborn_asker(10, 20), "Exercise 1: Stubborn asker")) testResults.append( test(test_not_number_rejector(), "Exercise 1: not_number_rejector")) testResults.append( test(test_super_asker(50, 60), "Exercise 1: test_super_asker")) testResults.append( test(test_flake8("week{}/exercise2.py".format(WEEK_NUMBER)), "Exercise 2: pass the linter")) testResults.append( test(test_example_guessingGame(), "Exercise 2: example guessing game")) if ex3runs(): import exercise3 testResults.append( test(test_flake8("week{}/exercise3.py".format(WEEK_NUMBER)), "Exercise 3: pass the linter")) lowerBound = 10 upperBound = 15 guesses = range(lowerBound, upperBound + 1) mockInputs = [lowerBound] + [upperBound] + guesses testResults.append( test(test_advanced_guessingGame(mockInputs), "Exercise 3: guessing game, U&L")) mockInputs = ["ten"] + [lowerBound] + [upperBound] + ["cats"] + guesses testResults.append( test(test_advanced_guessingGame(mockInputs), "Exercise 3: guessing game, polite failures")) lowerBound = 15 upperBound = 10 secondGuess = 25 guesses = range(lowerBound, secondGuess + 1) mockInputs = [lowerBound] + [upperBound] + [secondGuess] + guesses testResults.append( test( test_advanced_guessingGame(mockInputs), "Exercise 3: guessing game, lowerBound " "bigger than upperBound")) lowerBound = 10 upperBound = 11 secondGuess = 15 guesses = range(lowerBound, secondGuess + 1) mockInputs = [lowerBound] + [upperBound] + [secondGuess] + guesses testResults.append( test(test_advanced_guessingGame(mockInputs), "Exercise 3: guessing game, no range to guess in (delta 1)")) lowerBound = 10 upperBound = 10 secondGuess = 15 guesses = range(lowerBound, secondGuess + 1) mockInputs = [lowerBound] + [upperBound] + [secondGuess] + guesses testResults.append( test(test_advanced_guessingGame(mockInputs), "Exercise 3: guessing game, no range to guess in (equal)")) if ex4runs(): import exercise4 testResults.append( test(test_flake8("week{}/exercise4.py".format(WEEK_NUMBER)), "Exercise 4: pass the linter")) try_these = [(1, 100, 5), (1, 100, 6), (1, 100, 95), (1, 51, 5), (1, 50, 5)] for i in range(10): try_these.append((0, 100, random.randint(1, 99))) for tv in try_these: try: testResults.append( test( test_binary_search(*tv), # *tv unpacks the tuple "Exercise 4: binary_search({}, {}, {})".format(*tv))) except Exception: print("********\n\nfailed:", tv) print(Exception) raise ValueError("********\n\nfailed: {}".format(tv)) # if the binary search is working, show a graph of guess numbers if test(test_binary_search(1, 10, 5), ""): vis_binary_search_performance() print("{0}/{1} (passed/attempted)".format(sum(testResults), len(testResults))) if sum(testResults) == len(testResults): print(nyan_cat()) message = "Cowabunga! You've got all the tests passing!" completion_message(message, len(message) + 2) return {"of_total": len(testResults), "mark": sum(testResults)}
def theTests(path_to_code_to_check="."): """Run all the tests.""" print("\nWelcome to week {}!".format(path_to_code_to_check, WEEK_NUMBER)) print("May the odds be ever in your favour.\n") testResults = [] # Give each person 10 seconds to complete all tests. ex1path = "exercise1.py" if ex_runs(path_to_code_to_check, exNumber=1, weekNumber=WEEK_NUMBER): exercise1 = imp.load_source("exercise1", ex1path) testResults.append( test( exercise1.loop_ranger(3, 8, 1) == [3, 4, 5, 6, 7], "Exercise 1: Loop ranger (3, 8, 1)")) testResults.append( test( exercise1.loop_ranger(100, 104, 2) == [100, 102], "Exercise 1: Loop ranger (100, 104, 2)")) testResults.append( test( exercise1.lone_ranger(3, 8, 1) == [3, 4, 5, 6, 7], "Exercise 1: Lone ranger (3, 8, 1)")) testResults.append( test( exercise1.lone_ranger(100, 104, 2) == [100, 102], "Exercise 1: Lone ranger (100, 104, 2)")) testResults.append( test( exercise1.two_step_ranger(100, 104) == [100, 102], "Exercise 1: Two step ranger (100, 104)")) testResults.append( test( exercise1.two_step_ranger(0, 10) == [0, 2, 4, 6, 8], "Exercise 1: Two step ranger (100, 104)")) # testResults.append( # test(exercise1.gene_krupa_range(0, 10, 2, 1) == # [0, 2, 3, 5, 6, 8, 9], # "Exercise 1: gene_krupa_range(0, 10, 2, 1)")) # testResults.append( # test(exercise1.gene_krupa_range(0, 100, 30, 7) == # [0, 30, 37, 67, 74], # "Exercise 1: gene_krupa_range(0, 100, 30, 7)")) testResults.append( test(test_stubborn_asker(path_to_code_to_check, 50, 60), "Exercise 1: Stubborn asker")) testResults.append( test(test_stubborn_asker(path_to_code_to_check, 10, 20), "Exercise 1: Stubborn asker")) testResults.append( test(test_not_number_rejector(path_to_code_to_check), "Exercise 1: not_number_rejector")) testResults.append( test(test_super_asker(path_to_code_to_check, 50, 60), "Exercise 1: test_super_asker")) local_path = "exercise2.py" testResults.append( test(test_example_guessingGame(path_to_code_to_check), "Exercise 2: example guessing game")) if ex_runs(path_to_code_to_check, exNumber=3, weekNumber=WEEK_NUMBER): imp.load_source("exercise3", "exercise3.py") lowerBound = 10 upperBound = 15 guesses = list(range(lowerBound, upperBound + 1)) mockInputs = [lowerBound] + [upperBound] + guesses testResults.append( test(test_advanced_guessingGame(path_to_code_to_check, mockInputs), "Exercise 3: guessing game, U&L")) mockInputs = ["ten"] + [lowerBound] + [upperBound] + \ ["cats"] + guesses testResults.append( test(test_advanced_guessingGame(path_to_code_to_check, mockInputs), "Exercise 3: guessing game, polite failures")) lowerBound = 15 upperBound = 10 secondGuess = 25 guesses = list(range(lowerBound, secondGuess + 1)) mockInputs = [lowerBound] + [upperBound] + [secondGuess] + guesses testResults.append( test( test_advanced_guessingGame(path_to_code_to_check, mockInputs), "Exercise 3: guessing game, lowerBound " "bigger than upperBound")) lowerBound = 10 upperBound = 11 secondGuess = 15 guesses = list(range(lowerBound, secondGuess + 1)) mockInputs = [lowerBound] + [upperBound] + [secondGuess] + guesses testResults.append( test( test_advanced_guessingGame(path_to_code_to_check, mockInputs), "Exercise 3: guessing game, no " + "range to guess in (delta 1)")) lowerBound = 10 upperBound = 10 secondGuess = 15 guesses = list(range(lowerBound, secondGuess + 1)) mockInputs = [lowerBound] + [upperBound] + [secondGuess] + guesses testResults.append( test( test_advanced_guessingGame(path_to_code_to_check, mockInputs), "Exercise 3: guessing game, no " + "range to guess in (equal)")) if ex_runs(path_to_code_to_check, exNumber=4, weekNumber=WEEK_NUMBER): path = "exercise4.py" imp.load_source("exercise4", path) try_these = [(1, 100, 5), (1, 100, 6), (1, 100, 95), (1, 51, 5), (1, 50, 5)] for i in range(10): try_these.append((0, 100, random.randint(1, 99))) for tv in try_these: print(tv) try: testResults.append( # *tv unpacks this tuple ------v test( test_binary_search(path_to_code_to_check, *tv), "Exercise 4: binary_search" + "({}, {}, {})".format(*tv))) except Exception: print("********\n\nfailed:", tv) print("tv failure", Exception) # raise ValueError("********\n\nfailed: {}".format(tv)) testResults.append(0) # if the binary search is working, show a graph of guess numbers if test(test_binary_search(path_to_code_to_check, 1, 10, 5), ""): # If you aren't Ben, then show the histogram # if os.uname()[1] != "um": # um is ben's computer print("binary search works!") print("{0}/{1} (passed/attempted)".format(sum(testResults), len(testResults))) if sum(testResults) == len(testResults): print(nyan_cat()) message = "Cowabunga! You've got all the tests passing!" completion_message(message, len(message) + 2) return { "of_total": len(testResults), "mark": sum(testResults), "results": testResults }
def theTests(path_to_code_to_check="."): """Run the tests.""" print("\nWelcome to week {}!".format(WEEK_NUMBER)) print("May the odds be ever in your favour.\n") path = "{}/week{}/exercise1.py".format(path_to_code_to_check, WEEK_NUMBER) print(path) exercise1 = loadExerciseFile(weekNumber=WEEK_NUMBER, exerciseNumber=1) testResults = [] # stack the tests below here testDict = { "lastName": "hoogmoed", "password": "******", "postcodePlusID": 4311240 } testResults.append( test( exercise1.get_some_details() == testDict, "Exercise 1: get some data out of a JSON file", )) lengths = [3, 5, 7, 9, 11, 13, 15, 17, 19, 20, 18, 16, 14, 12, 10, 8, 6, 4] testName = "Exercise 1: request some simple data from the internet" try: pyramid = exercise1.wordy_pyramid() if pyramid is not None: testResults.append( test([len(w) for w in pyramid] == lengths, testName)) else: testResults.append(test(False, testName)) except Exception as e: testResults.append(0) print(testName, e) weather_results = { "latitude": "-33.924206", "state": "NSW", "longitude": "151.187912", "local_tz_offset": "+{}00".format(int(tzOffset())), } try: ex_name = "Exercise 1: get some data from the weather underground." theirs = exercise1.wunderground() mine = weather_results if theirs["latitude"] and theirs["longitude"]: theirs = process_wunderground(theirs) if mine["latitude"] and mine["longitude"]: mine = process_wunderground(mine) print("you gave:", theirs) print("expected:", mine) testResults.append(test(theirs == mine, ex_name)) except Exception as e: testResults.append(0) print(ex_name, e) testResults.append( test(find_lasers(path_to_code_to_check), "Exercise 1: count the lasers.")) print("{0}/{1} (passed/attempted)".format(sum(testResults), len(testResults))) if sum(testResults) == len(testResults): nyan_cat() message = "Rad, you've got all the tests passing!" completion_message(message, len(message) + 2) # treat() return { "of_total": len(testResults), "mark": sum(testResults), "results": testResults, }
def theTests(path_to_code_to_check="."): """Run all the tests.""" print("\nWelcome to the exam!") print("May the odds be ever in your favour.\nEspecially today!") ex1path = "{}/week{}/exercise1.py".format(path_to_code_to_check, WEEK_NUMBER) if ex_runs(path_to_code_to_check, exNumber=1, weekNumber=WEEK_NUMBER): exam = imp.load_source("exercise1", ex1path) testResults.append(test(test_flake8(ex1path), "pass the linter")) exam_test("Hello the Queen", ["the Queen"], exam.greet) exam_test("Hello Pr♂nc♀♂", ["Pr♂nc♀♂"], exam.greet) exam_test(4, [[3, 3, 3, 3, 1]], exam.three_counter) exam_test(0, [[0, 1, 2, 5, -9]], exam.three_counter) fizza = [ 1, 2, 'Fizz', 4, 'Buzz', 'Fizz', 7, 8, 'Fizz', 'Buzz', 11, 'Fizz', 13, 14, 'FizzBuzz', 16, 17, 'Fizz', 19, 'Buzz', 'Fizz', 22, 23, 'Fizz', 'Buzz', 26, 'Fizz', 28, 29, 'FizzBuzz', 31, 32, 'Fizz', 34, 'Buzz', 'Fizz', 37, 38, 'Fizz', 'Buzz', 41, 'Fizz', 43, 44, 'FizzBuzz', 46, 47, 'Fizz', 49, 'Buzz', 'Fizz', 52, 53, 'Fizz', 'Buzz', 56, 'Fizz', 58, 59, 'FizzBuzz', 61, 62, 'Fizz', 64, 'Buzz', 'Fizz', 67, 68, 'Fizz', 'Buzz', 71, 'Fizz', 73, 74, 'FizzBuzz', 76, 77, 'Fizz', 79, 'Buzz', 'Fizz', 82, 83, 'Fizz', 'Buzz', 86, 'Fizz', 88, 89, 'FizzBuzz', 91, 92, 'Fizz', 94, 'Buzz', 'Fizz', 97, 98, 'Fizz', 'Buzz' ] exam_test(fizza, [], exam.fizz_buzz) exam_test("|a| |s|e|r|i|a|l| |k|i|l|l|e|r|", ["a serial killer"], exam.put_behind_bars) exam_test("|a| |b|a|r|t|e|n|d|e|r|", ["a bartender"], exam.put_behind_bars) exam_test(['red fox'], ["x"], exam.pet_filter) exam_test([], ["q"], exam.pet_filter) exam_test(['pig', 'sheep', 'guinea pig', 'pigeon', 'alpaca', 'guppy'], ["p"], exam.pet_filter) exam_test("e", [], exam.best_letter_for_pets) exam_test(175, [], exam.make_filler_text_dictionary, lambda x: len(str(x))) exam_test(True, [50], exam.random_filler_text, lambda x: len(x.split(" ")) == 50 and len(x) > 3 * 50) exam_test(True, [1000], exam.random_filler_text, lambda x: len(x.split(" ")) == 1000 and len(x) > 3 * 1000) exam_test(True, [100], exam.fast_filler, lambda x: len(x.split(" ")) == 100 and len(x) > 3 * 100) exam_test( True, [10], exam.fast_filler, lambda x: x[0] in string.uppercase and x[1] in string.lowercase, "Test if fast_filler is capitalised") exam_test(True, [10], exam.fast_filler, lambda x: x[-1] == ".", "Test if fast_filler finishes with a .") # # try: # with Timeout(1): # for _ in range(10): # exam.fast_filler(1000) # testResults.append( # test(True, # "subsiquent fast_filler")) # except Timeout as t: # testResults.append( # test(False, # "subsiquent fast_filler probably wasn't fast enough")) # except Exception as e: # testResults.append( # test(False, # "subsiquent fast_filler failed" + str(e))) print("{0}/{1} (passed/attempted)".format(sum(testResults), len(testResults))) if sum(testResults) == len(testResults): print(nyan_cat()) message = "Cowabunga! You've got all the tests passing!" completion_message(message, len(message) + 2) return { "of_total": len(testResults), "mark": sum(testResults), "results": testResults }
def theTests(path_to_code_to_check="../me") -> dict: """Run the tests.""" print(f"\nWelcome to week {WEEK_NUMBER}!\n") print("May the odds be ever in your favour.\n") testResults = [] # Tests from here: if ex_runs(path_to_code_to_check, exerciseNumber=0, weekNumber=WEEK_NUMBER): exercise0 = loadExerciseFile(path_to_code_to_check, weekNumber=WEEK_NUMBER, exerciseNumber=0) testResults.append( test(exercise0.add_1(55) == 56, "Exercise 0: add_1 - 55 + 1 = 56")) testResults.append( test(exercise0.add_1(-5) == -4, "Exercise 0: add_1 - -5 + 1 = -4")) testResults.append( test( exercise0.add_1(0.1) == 1.1, "Exercise 0: add_1 - 0.1 + 1 = 1.1")) testResults.append( test(exercise0.add_5(55) == 60, "Exercise 0: add_5 - 55 + 5 = 60")) testResults.append( test(exercise0.add_5(-5) == 0, "Exercise 0: add_5 - -5 + 5 = 0")) testResults.append( test( exercise0.add_5(0.1) == 5.1, "Exercise 0: add_5 - 0.1 + 5 = 5.1")) testResults.append( test( exercise0.adder(5, 5) == 10, "Exercise 0: adder - 5 + 5 = 10")) testResults.append( test( exercise0.adder(-5, -5) == -10, "Exercise 0: adder - -5 + -5 = -10")) testResults.append( test( exercise0.adder(0.1, 0.9) == 1, "Exercise 0: adder - 0.1 + 0.9 = 1")) words = "you've got to fight for your right to party".split(" ") for word in words: word_up = word.upper() testResults.append( test( exercise0.shout(word) == word_up, f"Exercise 0: shout - {word} => {word_up}", )) testResults.append( test( exercise0.shout_with_a_number("hi", 1) == "HI 1", "Exercise 0: shout_with_a_number - hi, 1 => HI 1", )) ex2_runs = ex_runs(path_to_code_to_check, exerciseNumber=2, weekNumber=WEEK_NUMBER) if not ex2_runs: print( "Don't worry, exercise 2 comes with errors. It's your job to fix them!" ) testResults.append(test(ex2_runs, "Exercise 2: debug the file")) if ex_runs(path_to_code_to_check, exerciseNumber=3, weekNumber=WEEK_NUMBER): exercise3 = loadExerciseFile(path_to_code_to_check, weekNumber=WEEK_NUMBER, exerciseNumber=3) # is odd testResults.append( test( exercise3.is_odd(2) is False, "Exercise 3: is_odd - is 2 odd")) testResults.append( test(exercise3.is_odd(5), "Exercise 3: is_odd - is 5 odd")) # fix it scenarios = [ { "it_moves": True, "it_should_move": True, "answer": "No Problem" }, { "it_moves": True, "it_should_move": False, "answer": "WD-40" }, { "it_moves": False, "it_should_move": True, "answer": "Duct Tape" }, { "it_moves": False, "it_should_move": False, "answer": "No Problem" }, ] for s in scenarios: it = "moves" if s["it_moves"] else "does not move" should = "" if s["it_should_move"] else "not" testResults.append( test( exercise3.fix_it(s["it_moves"], s["it_should_move"]) == s["answer"], f"Exercise 3: fix_it - it {it}, and it should {should} move", )) # loops tenStars = ["*", "*", "*", "*", "*", "*", "*", "*", "*", "*"] result = exercise3.loops_1a() if result == tenStars: testResults.append(test(True, "Exercise 3: loops_1a - 1d for loop")) else: print(f"{NORM}" f"You're returning: {EM}{result}{NORM}. " f"We're looking for: {EM}{tenStars}{NORM}") if result == None: print(( "{norm}Do you have a line that says " "{em}return the_answer{norm}?\n" "Or maybe you have a line that says {em}return None{norm}?" "Or you are returning a variable that has the value " "{em}return None{norm}?\n" "Remember: {em}return print(something){norm} is the same " "as {em}return None{norm} because {em}print{norm} returns " "None\n" "You need to return the computed value, so either assign " "it to a variable and return that, or return it directly." ).format(em=EM, norm=NORM)) elif result == "**********": print("remember that we're looking for a list") # TODO: write more failure modes as they come up in testing. testResults.append( test( exercise3.loops_1c(3, ":)") == [":)", ":)", ":)"], "Exercise 3: loops_1c - 1d with arguments", )) ten_by_ten_stars = [ ["*", "*", "*", "*", "*", "*", "*", "*", "*", "*"], ["*", "*", "*", "*", "*", "*", "*", "*", "*", "*"], ["*", "*", "*", "*", "*", "*", "*", "*", "*", "*"], ["*", "*", "*", "*", "*", "*", "*", "*", "*", "*"], ["*", "*", "*", "*", "*", "*", "*", "*", "*", "*"], ["*", "*", "*", "*", "*", "*", "*", "*", "*", "*"], ["*", "*", "*", "*", "*", "*", "*", "*", "*", "*"], ["*", "*", "*", "*", "*", "*", "*", "*", "*", "*"], ["*", "*", "*", "*", "*", "*", "*", "*", "*", "*"], ["*", "*", "*", "*", "*", "*", "*", "*", "*", "*"], ] testResults.append( test( exercise3.loops_2() == ten_by_ten_stars, "Exercise 3: loops_2 - 10×10 stars", )) ten_matching_numbers = [ ["0", "0", "0", "0", "0", "0", "0", "0", "0", "0"], ["1", "1", "1", "1", "1", "1", "1", "1", "1", "1"], ["2", "2", "2", "2", "2", "2", "2", "2", "2", "2"], ["3", "3", "3", "3", "3", "3", "3", "3", "3", "3"], ["4", "4", "4", "4", "4", "4", "4", "4", "4", "4"], ["5", "5", "5", "5", "5", "5", "5", "5", "5", "5"], ["6", "6", "6", "6", "6", "6", "6", "6", "6", "6"], ["7", "7", "7", "7", "7", "7", "7", "7", "7", "7"], ["8", "8", "8", "8", "8", "8", "8", "8", "8", "8"], ["9", "9", "9", "9", "9", "9", "9", "9", "9", "9"], ] testResults.append( test( exercise3.loops_3() == ten_matching_numbers, "Exercise 3: loops_3 - 10 matching lists", )) ten_rising_lists = [ ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], ] res = exercise3.loops_4() if res == ten_rising_lists: testResults.append( test(True, "Exercise 3: loops_4 - ten rising lists")) else: if len(res) == 10 and res[0][0] == 0: print("This is looking promising, but the test is looking for " "strings, not numbers. look into what str() does") testResults.append( test(False, "Exercise 3: loops_4 - ten rising lists")) else: testResults.append( test(False, "Exercise 3: loops_4 - ten rising lists")) coords = [ ["(i0, j0)", "(i0, j1)", "(i0, j2)", "(i0, j3)", "(i0, j4)"], ["(i1, j0)", "(i1, j1)", "(i1, j2)", "(i1, j3)", "(i1, j4)"], ["(i2, j0)", "(i2, j1)", "(i2, j2)", "(i2, j3)", "(i2, j4)"], ["(i3, j0)", "(i3, j1)", "(i3, j2)", "(i3, j3)", "(i3, j4)"], ["(i4, j0)", "(i4, j1)", "(i4, j2)", "(i4, j3)", "(i4, j4)"], ["(i5, j0)", "(i5, j1)", "(i5, j2)", "(i5, j3)", "(i5, j4)"], ["(i6, j0)", "(i6, j1)", "(i6, j2)", "(i6, j3)", "(i6, j4)"], ["(i7, j0)", "(i7, j1)", "(i7, j2)", "(i7, j3)", "(i7, j4)"], ["(i8, j0)", "(i8, j1)", "(i8, j2)", "(i8, j3)", "(i8, j4)"], ["(i9, j0)", "(i9, j1)", "(i9, j2)", "(i9, j3)", "(i9, j4)"], ] testResults.append( test(exercise3.loops_5() == coords, "Exercise 3: loops_5 - write the coords")) wedge = [ ["0"], ["0", "1"], ["0", "1", "2"], ["0", "1", "2", "3"], ["0", "1", "2", "3", "4"], ["0", "1", "2", "3", "4", "5"], ["0", "1", "2", "3", "4", "5", "6"], ["0", "1", "2", "3", "4", "5", "6", "7"], ["0", "1", "2", "3", "4", "5", "6", "7", "8"], ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], ] testResults.append( test(exercise3.loops_6() == wedge, "Exercise 3: loops_6 - make a wedge")) pyramid = [ [" ", " ", " ", " ", "*", " ", " ", " ", " "], [" ", " ", " ", "*", "*", "*", " ", " ", " "], [" ", " ", "*", "*", "*", "*", "*", " ", " "], [" ", "*", "*", "*", "*", "*", "*", "*", " "], ["*", "*", "*", "*", "*", "*", "*", "*", "*"], ] testResults.append( test(exercise3.loops_7() == pyramid, "Exercise 3: loops_7 - pyramid of stars")) testResults.append( test( lab_book_entry_completed(WEEK_NUMBER, path_to_code_to_check), "Lab book entry completed", )) message = "Rad, you've got all the tests passing!" return finish_up(testResults, message, nyan_cat())