def test_example_guessingGame(repo_path): """Test the example_guessingGame function. This should always pass becasue it's provided code """ try: exercise2 = loadExerciseFile(repo_path, weekNumber=WEEK_NUMBER, exerciseNumber=2) except Exception as e: return syntax_error_message(2, e) upperBound = 5 guesses = list(range(5 + 1)) mockInputs = [upperBound] + guesses with mock.patch("builtins.input", side_effect=mockInputs): my_args = None try: message = func_timeout(TIMEOUT_IN_SECONDS, exercise2.exampleGuessingGame, args=my_args) return message == "You got it!" except FunctionTimedOut: timeout_message( function_name=sys._getframe().f_code.co_name, args=my_args, timeout_in_seconds=TIMEOUT_IN_SECONDS, ) except Exception as e: print(e)
def test_stubborn_asker(low, high): """Test the stubborn asker function.""" try: exercise1 = loadExerciseFile(weekNumber=WEEK_NUMBER, exerciseNumber=1) except Exception as e: return syntax_error_message(4, e) mockInputs = list(range(low - 25, high + 20, 5)) try: with mock.patch("builtins.input", side_effect=mockInputs): try: x = exercise1.stubborn_asker(low, high) if x is not None: result = low <= x <= high return result else: print( "Trouble testing the test_stubborn_asker.", "Maybe you haven't started yet?", ) except Exception as e: print(e) return except Exception as e: print("exception:", e)
def test_advanced_guessingGame(repo_path, mockInputs): """Test the advanced_guessingGame function.""" try: exercise3 = loadExerciseFile(repo_path, weekNumber=WEEK_NUMBER, exerciseNumber=3) except Exception as e: return syntax_error_message(3, e) with mock.patch("builtins.input", side_effect=mockInputs): try: my_args = None message = func_timeout(TIMEOUT_IN_SECONDS, exercise3.advancedGuessingGame, args=my_args) return message == "You got it!" except FunctionTimedOut: print( "{f}({args}) could not complete within {t} seconds and was killed." .format(f=sys._getframe().f_code.co_name, args=my_args, t=TIMEOUT_IN_SECONDS)) except Exception as e: print(e)
def test_advanced_guessingGame(repo_path, mockInputs): """Test the advanced_guessingGame function.""" try: exercise3 = loadExerciseFile(repo_path, weekNumber=WEEK_NUMBER, exerciseNumber=3) except Exception as e: return syntax_error_message(3, e) with mock.patch("builtins.input", side_effect=mockInputs): my_args = None try: message = func_timeout(TIMEOUT_IN_SECONDS, exercise3.advancedGuessingGame, args=my_args) return message == "You got it!" except FunctionTimedOut: timeout_message( function_name=sys._getframe().f_code.co_name, args=my_args, timeout_in_seconds=TIMEOUT_IN_SECONDS, ) except Exception as e: print(e)
def test_not_number_rejector(repo_path): """Test the not number rejector function.""" try: exercise1 = loadExerciseFile(repo_path, weekNumber=WEEK_NUMBER, exerciseNumber=1) except Exception as e: return syntax_error_message(1, e) mockInputs = ["aword", [1, 2, 3], {"an": "object"}, 40] with mock.patch("builtins.input", side_effect=mockInputs): my_args = "Testing some values:" try: r = func_timeout(TIMEOUT_IN_SECONDS, exercise1.not_number_rejector, args=[my_args]) return r except FunctionTimedOut: timeout_message( function_name=sys._getframe().f_code.co_name, args=my_args, timeout_in_seconds=TIMEOUT_IN_SECONDS, ) except Exception as e: print("exception:", e)
def test_super_asker(repo_path, low, high): """Test the super asker function.""" try: exercise1 = loadExerciseFile(repo_path, weekNumber=WEEK_NUMBER, exerciseNumber=1) except Exception as e: return syntax_error_message(1, e) dirty_things = ["aword", [1, 2, 3], {"an": "object"}] neat_range = list(range(low - 25, high + 20, 5)) mockInputs = dirty_things + neat_range with mock.patch("builtins.input", side_effect=mockInputs): my_args = (low, high) try: message = func_timeout(TIMEOUT_IN_SECONDS, exercise1.super_asker, args=my_args) return message except FunctionTimedOut: timeout_message( function_name=sys._getframe().f_code.co_name, args=my_args, timeout_in_seconds=TIMEOUT_IN_SECONDS, ) except Exception as e: print(e)
def test_not_number_rejector(repo_path): """Test the not number rejector function.""" try: exercise1 = loadExerciseFile( repo_path, weekNumber=WEEK_NUMBER, exerciseNumber=1 ) except Exception as e: return syntax_error_message(1, e) mockInputs = ["aword", [1, 2, 3], {"an": "object"}, 40] with mock.patch("builtins.input", side_effect=mockInputs): try: my_args = "Testing some values:" r = func_timeout( TIMEOUT_IN_SECONDS, exercise1.not_number_rejector, args=my_args ) return r except FunctionTimedOut: print( "{f}({args}) could not complete within {t} seconds and was killed.".format( f=sys._getframe().f_code.co_name, args=my_args, t=TIMEOUT_IN_SECONDS ) ) except Exception as e: print("exception:", e)
def test_example_guessingGame(): """Test the example_guessingGame function. This should always pass becasue it's provided code """ try: exercise2 = loadExerciseFile(weekNumber=WEEK_NUMBER, exerciseNumber=2) except Exception as e: return syntax_error_message(2, e) upperBound = 5 guesses = list(range(5 + 1)) mockInputs = [upperBound] + guesses with mock.patch("builtins.input", side_effect=mockInputs): try: my_args = None message = func_timeout(TIMEOUT_IN_SECONDS, exercise2.exampleGuessingGame, args=my_args) return message == "You got it!" except FunctionTimedOut: print( "{f}({args}) could not complete within {t} seconds and was killed." .format(f=sys._getframe().f_code.co_name, args=my_args, t=TIMEOUT_IN_SECONDS)) except Exception as e: print(e)
def test_super_asker(low, high): """Test the super asker function.""" try: exercise1 = loadExerciseFile(weekNumber=WEEK_NUMBER, exerciseNumber=1) except Exception as e: return syntax_error_message(1, e) dirty_things = ["aword", [1, 2, 3], {"an": "object"}] neat_range = list(range(low - 25, high + 20, 5)) mockInputs = dirty_things + neat_range with mock.patch("builtins.input", side_effect=mockInputs): try: my_args = (low, high) message = func_timeout(TIMEOUT_IN_SECONDS, exercise1.super_asker, args=my_args) return message except FunctionTimedOut: print( "{f}({args}) could not complete within {t} seconds and was killed." .format(f=sys._getframe().f_code.co_name, args=my_args, t=TIMEOUT_IN_SECONDS)) except Exception as e: print(e)
def test_binary_search(repo_path, low, high, actual): # TODO: I don't think this test is working """Test the binary search function. checks to see that it's searching better than O(log n) """ try: exercise4 = loadExerciseFile( repo_path, weekNumber=WEEK_NUMBER, exerciseNumber=4 ) BASE2 = 2 b = None try: my_args = (low, high, actual) b = func_timeout(TIMEOUT_IN_SECONDS, exercise4.binary_search, args=my_args) b["WorstCaseO"] = math.log(high - low, BASE2) if b is not None: if b["tries"] is not 0 and b["tries"] < b["WorstCaseO"]: print("b", b) print("snuck it in") return True elif b["tries"] is 0: print( "Tries is 0, that probably means that you haven't started yet" ) else: print( ( "That took {t} tries, you " "should get it in under {o} tries" ).format(t=b["tries"], o=b["WorstCaseO"]) ) else: return False except FunctionTimedOut: print( "{f}({args}) could not complete within {t} seconds and was killed.".format( f=sys._getframe().f_code.co_name, args=my_args, t=TIMEOUT_IN_SECONDS ) ) return False except Exception as e: syntax_error_message(4, e) return False except Exception as e: syntax_error_message(4, e) return False
def test_binary_search(repo_path, low, high, actual, label): """Test the binary search function. checks to see that it's searching better than O(log n) """ try: exercise4 = loadExerciseFile(repo_path, weekNumber=WEEK_NUMBER, exerciseNumber=4) BASE2 = 2 b = None my_args = (low, high, actual) try: b = func_timeout(TIMEOUT_IN_SECONDS, exercise4.binary_search, args=my_args) b["WorstCaseO"] = math.log(high - low, BASE2) if b is not None: if b["tries"] is not 0 and b["tries"] < b["WorstCaseO"]: print("b", b) print("snuck it in") return True elif b["tries"] is 0: print( "Tries is 0, that probably means that you haven't started yet" ) else: print(f"That took {b['tries']} tries, you " f"should get it in under {b['WorstCaseO']} tries") else: return False except FunctionTimedOut: timeout_message( function_name=sys._getframe().f_code.co_name, args=my_args, timeout_in_seconds=TIMEOUT_IN_SECONDS, ) return False except Exception as e: syntax_error_message(4, e) return False except Exception as e: syntax_error_message(4, e) return False
def test_hello_world(): exercise1 = loadExerciseFile(weekNumber=WEEK_NUMBER, exerciseNumber=1) source = "".join(inspect.getsourcelines(exercise1)[0]) if ("print('hello world!')" in source.lower() or 'print("hello world!")' in source.lower()): return True print(""" We're looking for: {em}print(\"hello world!\"){norm} but your code is \n{sep}\n{em}{code}{norm}\n{sep} Look carefully at your capitalisation, spelling, brackets, spaces etc.""".format(code=source, sep="═" * 80, em=EM, norm=NORM)) return False
def vis_binary_search_performance(repo_path): """Provide a visualisation of the performance of the binary search.""" try: exercise4 = loadExerciseFile( repo_path, weekNumber=WEEK_NUMBER, exerciseNumber=4 ) except Exception as e: return syntax_error_message(4, e) import matplotlib.pyplot as plt BASE2 = 2 results = [] testRuns = 1000 for _ in range(testRuns): low = random.randint(-100, 100) high = random.randint(low + 2, 200) guess = random.randint(low + 1, high - 1) bs = exercise4.binary_search(low, high, guess) # print bs, low, high, guess tries = bs["tries"] worst = math.log(high - low, BASE2) ratio = tries / worst results.append(ratio) plt.hist(results) plt.title( "Proportion of worst case performance " "over {} iterations".format(testRuns) ) print( """ This histogram shows the number of guesses that it took the search to find the answer. The big O worst case is the base 2 log of the range that you're guessing within. In other words, what power of two fills that space? E.g. if your range is 16, then the worst case is 4 guesses: 2×2×2×2 = 16 Think back to when you were playing the game with your brain, sometimes you'd go over the worst case because you aren't a perfect arithmatic machine but the computer is, so it's always below that worst case limit. Close the histogram to finish running the tests.""" ) plt.show()
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 = [] # Give each person 10 seconds to complete all tests. if ex_runs(path_to_code_to_check, exerciseNumber=1, weekNumber=WEEK_NUMBER): exercise1 = loadExerciseFile(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(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_example_guessingGame(), "Exercise 2: example guessing game")) if ex_runs(path_to_code_to_check, exerciseNumber=3, weekNumber=WEEK_NUMBER): exercise1 = loadExerciseFile(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(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", )) secondGuess = 25 guesses = list(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 = list(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 = list(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 ex_runs(path_to_code_to_check, exerciseNumber=4, weekNumber=WEEK_NUMBER): exercise1 = loadExerciseFile(weekNumber=WEEK_NUMBER, exerciseNumber=4) try_these = [(1, 100, 5), (1, 100, 6), (1, 100, 95), (1, 51, 5), (1, 50, 5)] for _ in range(10): try_these.append((0, 100, random.randint(1, 99))) for tv in try_these: try: testResults.append( # *tv unpacks this tuple -------------- vv test( test_binary_search(*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(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 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(ex1path, 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) 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(160, [], 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, chdir=True, ) exam_test(True, ["./week8/speedy_dict.words"], os.path.exists) # 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) > 0 and 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( 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())
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) exercise1 = loadExerciseFile(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 = [ { "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 = exercise1.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 = exercise1.calculate_hypotenuse(t["base"], t["height"]) testResults.append( test( hyp == t["hypotenuse"], pattern.format( 1, "calculate_hypotenuse", t["base"], t["height"], t["hypotenuse"] ), ) ) 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"]), ) ) 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 ) tf = exercise1.triangle_master( base=5, height=5, return_diagram=True, return_dictionary=False ) ft = exercise1.triangle_master( base=5, height=5, return_diagram=False, return_dictionary=True ) tt = exercise1.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 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]): 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] ), "exercise 1: get_a_word_of_length_n {}".format(word), ) ) some_lengths = [[4, 5, 6], [4, 18, 4]] for lengths in some_lengths: 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 {}".format(word)) ) testResults.append( test( "list_of_words_with_lengths" in exercise1.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 = 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 = "{}/week{}/exercise2.py".format(path_to_code_to_check, WEEK_NUMBER) print(path) e2 = loadExerciseFile(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): 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: 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 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=".") -> 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") 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="../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="../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())