def test_number2(verbose): print("Running " + inspect.stack()[0][3]) test_cases = {0: 0, 2: 1, 234252: 3, 345: 0} for tc in test_cases: if verbose: print('\ttrying ' + str(tc)) ca.assert_equals(test_cases[tc], lab09_optional.number2(tc))
def test_clamp(verbose): """Test clamp. If verbose is True, then each test input is printed out, as well.""" fn_name = inspect.stack()[0][3] print("Running " + fn_name) # Format: each key is a tuple. # The item at index 0 of the key is a tuple version of the input list. # The item at index 1 of the key is the min value allowed. # The item at index 2 of the key is the max value allowed # The value is the list that the input list should match once the function # is applied. test_cases = { ((-1, 1, 3, 5), 0, 4): [0, 1, 3, 4], ((4, -1, 1, 6, 3), 0, 5): [4, 0, 1, 5, 3], ((17, -1, 2, 27, 14), 2, 3): [3, 2, 2, 3, 3], ((17, -1, 2, 27, 14), 2, 2): [2, 2, 2, 2, 2], ((5.3, 0, 2, 8.5, 4), 0, 8): [5.3, 0, 2, 8, 4], ((5.3, 0, 2, 8.5, 4), 1.3, 7.2): [5.3, 1.3, 2, 7.2, 4], ((), 2, 3): [], } for test_input in test_cases: if verbose: print("\tTesting input " + str(test_input)) input_list = list(test_input[0]) # Need to convert tuple to list input_min = test_input[1] input_max = test_input[2] lab08for.clamp(input_list, input_min, input_max) ca.assert_equals(test_cases[test_input], input_list)
def test_space_runs(): # print test procedure name print('Running ' + inspect.stack()[0][3]) # print test-procedure name for fn in [ labfile.num_space_runs1, labfile.num_space_runs2, labfile.num_space_runs3 ]: print('\t Testing', fn.__name__) # print function name test_cases = { "a f g": 2, " a f g ": 4, " a f g ": 4, " a bc d": 3, " a": 1, "ab": 0, "abc a": 1, "abc ": 1, " ": 1 } try: for tc in test_cases: print('\t\t Testing "', tc + '"') result = fn(tc) right_answer = test_cases[tc] ca.assert_equals(right_answer, result) print(fn.__name__, "passed all test cases. Hurrah!") except: print("ERROR: something wrong with", fn.__name__, "for test case ", \ "'" + tc + "'") sys.exit()
def test_pigify(): print("Running test_pigify to test lab05.pigify") ## STUDENTS: ## At this point in the class, you do not know what dictionaries are. ## But for the curious: test_cases is a structure that lets you organize ## pairs of a so-called "key" (the first item in a pair) and an associated ## "value" (the second item in a pair). ## In our case, the keys and values are inputs and desired outputs. # These test cases come from the lab handout. test_cases = { 'ask': 'askhay', 'use': 'usehay', 'quiet': 'ietquay', 'quay': 'ayquay', 'qu': 'quay', 'tomato': 'omatotay', 'school': 'oolschay', 'you': 'ouyay', 'pssst': 'pssstay' } ## STUDENTS: " ## At this point in the class, you do not know what for-loops/blocks are. ## But for the curious: the code below runs assert_equals on each ## input/output pair in the test_cases dictionary for w in test_cases: print('\tTrying "' + w + '"') cornellasserts.assert_equals(test_cases[w], lab05.pigify(w))
def test_sum_digits(verbose): print("Running " + inspect.stack()[0][3]) test_cases = {0: 0, 3: 3, 34: 7, 345: 12} for tc in test_cases: if verbose: print('\ttrying ' + str(tc)) ca.assert_equals(test_cases[tc], lab09_optional.sum_digits(tc))
def test_into(verbose): print("Running " + inspect.stack()[0][3]) test_cases = {(5, 3): 0, (6, 3): 1, (3 * 3 * 3 * 3 * 7, 3): 4} for tc in test_cases: if verbose: print('\ttrying ' + str(tc)) ca.assert_equals(test_cases[tc], lab09_optional.into(tc[0], tc[1]))
def test_exp(verbose): print("Running " + inspect.stack()[0][3]) test_cases = {(3, 0): 1, (3, 2): 9, (2, 5): 32} for tc in test_cases: if verbose: print('\ttrying ' + str(tc)) ca.assert_equals(test_cases[tc], lab09_optional.exp(tc[0], tc[1]))
def test_helper2(): """Test function a1.after""" print("Testing a1.after") # tag in the middle t = '<a id="c111">' s = 'start <a id="c111">xthis that the other' result = a1.after(t, s) cornellasserts.assert_equals('xthis that the other', result)
def test_convert_lines_to_string(verbose): """Test a3.test_convert_lines_to_string() and a3.test_convert_lines_to_string2() """ # A generic line that can be pasted into any function; # retrieves the name of current function from its frame on the stack. # Each item in the list returned by inspect.stack() is a call frame. # You can print out the frame at the top of the stack by: # print(str(inspect.stack()[0]) tester_name = inspect.stack()[0][3] print("Running " + tester_name + "()") # Have to store lists as tuples in order to have them be dict. keys. test_cases = { ("hi\n", "there"): "hi there", ("hi\n", "there\n"): "hi there", (" hola ", " salut \n howdy "): "hola salut \n howdy", ("so", "la", "", "do"): "so la do", ("so", "\n", "la", "", "", "do"): "so la do", # no extra space after la # STUDENTS: you should add enough test cases to make the set of test cases # sufficient. Put any new test cases you want in the dictionary # below this line, and leave the next comment line in your code so the # graders to easily locate it and your additions. # ..... STUDENT-ADDED DICT. CONVERT...STRING TEST CASES BELOW THIS LINE .... } # Yes, functions can be elements of lists, too! Note that the elements # are not (values returned by) function calls, but the functions themselves. fns_to_test = [a3.convert_lines_to_string, a3.convert_lines_to_string2] for ind in range(len(fns_to_test)): # also OK to wrap "list" around range() convertfn = fns_to_test[ind] print("testing " + convertfn.__name__) for test_input in test_cases: if verbose: print("\tTesting " + str(test_input)) expected = test_cases[test_input] ca.assert_equals(expected, # Convert tuple back to list convertfn(list(test_input))) # STUDENTS: you should add enough test cases to make the set of test cases # sufficient. If you have additional test cases to add that wouldn't be # suitable for encoding in dictionary test_cases, then place them here. # Make sure you call the generic alias `convertfn` so that both your # convert_line_to_string() and convert_line_to_string2() can be tested # on the same test cases. # Leave the following comment line in your submitted code so that the # graders can easily locate it and thus your additions. # ..... STUDENT-ADDED NON-DICT. CONVERT...STRING TEST CASES BELOW THIS LINE .... if ind < (len(fns_to_test)-1): # Not the last fn to test # Check whether students are ready to test the next function ask_to_quit(verbose, fns_to_test[ind+1].__name__)
def test_sum_list(verbose): print("Running " + inspect.stack()[0][3]) test_cases = {(): 0, (34, ): 34, (7, 34, 1, 2, 2): 46} for tc in test_cases: inputlist = list(tc) if verbose: print('\ttrying ' + str(inputlist)) ca.assert_equals(test_cases[tc], lab09_optional.sum_list(inputlist))
def test_sum_to(verbose): print("Running " + inspect.stack()[0][3]) test_cases = {1: 1, 3: 6, 5: 15} for tc in test_cases: if verbose: print('\ttrying ' + str(tc)) ca.assert_equals(test_cases[tc], lab09_optional.sum_to(tc))
def test_helper1(): """Test function a1.before_first_double_quote""" print("Testing a1.before_first_double_quote") # 1st quote three in from beginning result = a1.before_first_double_quote('abd"def') cornellasserts.assert_equals('abd', result) # quote at beginning result = a1.before_first_double_quote('"def"') cornellasserts.assert_equals('', result)
def test_lesser_than(verbose): """Test lesser_than and lesser_than2. If verbose is True, then each test input is printed out, as well.""" # A generic line that can be pasted into any function; # retrieves the name of current function from its frame on the stack. # Each item in the list returned by inspect.stack() is a call frame. # You can print out the frame at the top of the stack by: # print(str(inspect.stack()[0]) fn_name = inspect.stack()[0][3] print("Running " + fn_name) # We turn to dictionaries and for-loops to make writing test cases less # tedious. # The keys are tuples representing the two inputs to lesser_than. # The values are the expected answers for those two inputs. # We have to use tuples because dictionaries don't allow the keys to be # "hashable". # Format: # (input1, input2): expected_value # where input1 is a tuple version of an input list. # STUDENTS: beware! One test case is incorrect on purpose! test_cases = { ((5, 9, 1, 7), -1): 0, ((5, 9, 1, 7), 1): 0, ((5, 9, 1, 7), 5): 1, # etc. ((5, 9, 1, 7), 7): 2, ((5, 9, 1, 7), 6): 2, ((5, 9, 1, 7), 9): 3, ((5, 9, 1, 7), 10): 4, ((), -2): 0, # testing empty list ((), 2): 0, ((4, 5, 6), 1): 0, ((4, 5, 6), 7): 3, ((4, 4, 4), 7): 3 # testing list with duplicates } for test_input in test_cases: if verbose: print("\tTesting input " + str(test_input)) input_list = list(test_input[0]) # Convert from tuple to list orig = input_list[:] # Create a copy to check that nothing is changed # by the function being tested input_value = test_input[1] # Test that output is correct ca.assert_equals(test_cases[test_input], lab08for.lesser_than(input_list, input_value)) # Test that the input list was not changed ca.assert_equals(orig, input_list)
def test_open_status(): """Test function a1.open_status""" print("Testing a1.open_status") # standard case d1 = '<a id="c10775"> fa-circle open-status-open"></i></span>' result = a1.open_status("10775", d1) cornellasserts.assert_equals("open", result) # a near-match at the beginning, so check for exact match d2 = '<a id="10775"> open-status-no <a id="c10775"> open-status-Y"></i></span>' result = a1.open_status("10775", d2) cornellasserts.assert_equals("Y", result)
def test_draw(): """Quick diagnostic test of whether cardstuff.draw seems to be working. May depend on equality being correct for cards""" print("Testing test_draw") orig_clist = [card_lab06.Card(1, 11)] clist = orig_clist[:] orig_hand = [card_lab06.Card(2, 3)] hand = orig_hand[:] # Have a hand containing the 3 of hearts, drawing from a 'deck' # containing just the Jack of Diamonds c = cardstuff.draw(clist) hand.append(c) try: cornellasserts.assert_not_equals(c, None) except: print("Error: draw is returning None") sys.exit() try: cornellasserts.assert_equals(0, len(clist)) except: print("Error: the drawn card is not being removed from the list") print("Consider adding print statements to debug") sys.exit() # Now trying to draw from a full deck, checking that we don't seem to # be drawing from the same position each time orig_deck = card_lab06.full_deck() clist = card_lab06.full_deck() c1 = cardstuff.draw(clist) i1 = orig_deck.index(c1) orig_deck.pop(i1) c2 = cardstuff.draw(clist) i2 = orig_deck.index(c2) orig_deck.pop(i2) c3 = cardstuff.draw(clist) i3 = orig_deck.index(c3) if i1 == i2 and i2 == i3: print( "***Suspicious output***: seems like the drawn card is not randomly picked" ) print("\tbut is always drawn from the same position.") print("Consider testing in Python interactive mode") sys.exit() print("finished test of test_draw()")
def test_embed(verbose): print("Running " + inspect.stack()[0][3]) ca.assert_equals(0, lab09_optional.embed('cs1110')) ca.assert_equals(1, lab09_optional.embed(['cs1110'])) ca.assert_equals(1, lab09_optional.embed(['cs1110', 'opython', 'typoon'])) ca.assert_equals( 3, lab09_optional.embed(['cs1110', ['opython', ['recursion'], 'typoon']]))
def test_score(verbose): """Test _score function. Extra info printed if `verbose` is True.""" tester_name = inspect.stack()[0][3] print("Running " + tester_name + "()") for tc in test_cases_in_common: if verbose: print('\tTesting ' + c11.cardlist_str(tc)) answer = test_cases_in_common[tc] output = blackjack._score(list(tc)) # Convert tuple to list ca.assert_equals(answer, output) print_done_message(verbose, tester_name)
def test_max_nested_list(verbose): print("Running " + inspect.stack()[0][3]) ca.assert_equals(0, lab09_optional.max_nested_list(0)) ca.assert_equals(8, lab09_optional.max_nested_list([0, [2, 5], 8, [-10, -1]])) ca.assert_equals(1, lab09_optional.max_nested_list([[[[1]]]])) ca.assert_equals(1110, lab09_optional.max_nested_list([[[[1, 1110], 2], 3], 4]))
def test_playerBust(verbose): """Test playerBust function. Extra info printed if `verbose` is True.""" tester_name = inspect.stack()[0][3] print("Running " + tester_name + "()") game = make_dummy_game() for tc in test_cases_bust: if verbose: print('\tTesting ' + c11.cardlist_str(tc)) answer = test_cases_bust[tc] game.playerHand = list(tc) output = game.playerBust() ca.assert_equals(answer, output) print_done_message(verbose, tester_name)
def test_dealerScore(verbose): """Test dealerScore function. Extra info printed if `verbose` is True.""" tester_name = inspect.stack()[0][3] print("Running " + tester_name + "()") game = make_dummy_game() for tc in test_cases_in_common: if verbose: print('\tTesting ' + c11.cardlist_str(tc)) answer = test_cases_in_common[tc] game.dealerHand = list(tc) # Set the dealerHand to be a test case. output = game.dealerScore() ca.assert_equals(answer, output) print_done_message(verbose, tester_name)
def test_sum_nested_list(verbose): print("Running " + inspect.stack()[0][3]) # dictionaries can't have lists as keys, so using list instead of dict. test_cases = [[0, 0], [4, 4], [[0, [2, 5], [8, [-10, -1]]], 4], [[0, [2, 5, []], [8, [-10, -1]]], 4], [[], 0]] # We have several different implementations, and so use a list of functions # to test them all. fns_to_test = [lab09.sum_nested_list] for fn in fns_to_test: print("\tTesting " + fn.__name__) for item in test_cases: test_input = item[0] if verbose: print('\ttrying ' + str(test_input)) correct = item[1] ca.assert_equals(correct, lab09.sum_nested_list(test_input))
def test_number_not(verbose): print("Running " + inspect.stack()[0][3]) mylist_as_tuple = (5, 3, 3455, 74, 74, 74, 3) test_cases = { (mylist_as_tuple, 74): 4, (mylist_as_tuple, 3): 5, (mylist_as_tuple, 4): 7, ((3, ), 4): 1, # Need comma to make Python realize we want a tuple ((), 4): 0 } for tc in test_cases: inputlist = list(tc[0]) inputval = tc[1] if verbose: print('\ttrying ' + str(inputlist) + ' and ' + str(inputval)) ca.assert_equals(test_cases[tc], lab09_optional.number_not(inputlist, inputval))
def test_remove_first(verbose): print("Running " + inspect.stack()[0][3]) # Using a list because converting everything to tuples for a dictionary # seems too painful. # Format: each item is (input1, input2, answer) test_cases = [([], 3, []), ([3], 3, []), ([3], 4, [3]), ([3, 4, 4, 4, 5], 4, [3, 4, 4, 5]), ([3, 4, 5, 4, 4, 4], 4, [3, 5, 4, 4, 4])] for item in test_cases: inputlist = item[0] inputval = item[1] if verbose: print('\ttrying ' + str(inputlist) + ' and ' + str(inputval)) expected = item[2] ca.assert_equals(expected, lab09_optional.remove_first(inputlist, inputval))
def test_numberof(verbose): print("Running " + inspect.stack()[0][3]) # dictionaries can't have lists as keys, so using tuples test_cases = { ((5, 3, 3455, 74, 74, 74, 3), 74): 3, ((5, 3, 3455, 74, 74, 74, 3), 3): 2, ((5, 3, 3455, 74, 74, 74, 3), 4): 0, ((4, ), 4): 1, ((4, 4), 4): 2, ((), 3): 0 } for test_input in test_cases: if verbose: print('\ttrying ' + str(test_input)) output = lab09.numberof(list(test_input[0]), test_input[1]) ca.assert_equals(test_cases[test_input], output)
def test_reverses(verbose): print("Running " + inspect.stack()[0][3]) test_cases = {(): [], (3, ): [3], (3, 2, 1): [1, 2, 3]} fns_to_test = [lab09_optional.reverse1, lab09_optional.reverse2] for ind in range(len(fns_to_test)): reverse_fn = fns_to_test[ind] print("\ttesting " + reverse_fn.__name__) for tc in test_cases: inputlist = list(tc) if verbose: print('\ttrying ' + str(inputlist)) ca.assert_equals(test_cases[tc], reverse_fn(inputlist)) mylist = [3] ca.assert_equals(False, mylist is reverse_fn(mylist)) if ind < len(fns_to_test) - 1: # Still another function to test ask_to_quit(verbose)
def test_get_econ_vocab(verbose): """ Test a3.get_econ_vocab() """ # Does just some rough checks tester_name = inspect.stack()[0][3] print("Running " + tester_name + "()") print("...this takes a little while") result = a3.get_econ_vocab() assert type(result) == list ca.assert_equals(type(result), list) ca.assert_true(len(result) > 20) # spot checks ca.assert_equals(672, len(result)) some_terms = ['agency costs', 'capital gains', 'euro', 'poverty', 'third way'] some_terms.extend(['tax base', 'volatility', 'yield', 'welfare']) for term in some_terms: ca.assert_true(term in result) ca.assert_false('Tariff' in result)
def test_remove_dups(verbose): print("Running " + inspect.stack()[0][3]) # dictionaries can't have lists as keys, so using tuples test_cases = { (): [], (1, 2, 2, 3, 3, 3, 4, 5, 1, 1, 1): [1, 2, 3, 4, 5, 1], (3, 3): [3], (4, ): [4], (4, 3, 4): [4, 3, 4], } for test_input in test_cases: if verbose: print('\ttrying ' + str(test_input)) test_list = list(test_input) output = lab09_optional.remove_dups(test_list) ca.assert_equals(test_cases[test_input], output) # see if new list is a different list ca.assert_false(output is test_list)
def test_get_content_lines(verbose): """Test a3.get_content_lines()""" # A generic line that can be pasted into any function; # retrieves the name of current function from its frame on the stack. # Each item in the list returned by inspect.stack() is a call frame. # You can print out the frame at the top of the stack by: # print(str(inspect.stack()[0]) tester_name = inspect.stack()[0][3] print("Running " + tester_name + "()") test_cases = { # Different operating systems have different ways of dealing with # subdirectories, which is what os.path.join helps us deal with. # See section 14.4 "Filenames and paths" of the text. add_sources_to_fname('shortest.txt'): ["abc abcabc natural language processing\n", "3 o'clock bc!d\n"], add_sources_to_fname('short.txt'): [ "here is a small piece of text a small piece of text a small piece of text here is a small piece of text at nine o'clock in the morning\n" ], add_sources_to_fname('shortest_commented.txt'): ["abc abcabc natural language processing\n", "bc!d bc!d\n"], } for test_input in test_cases: if verbose: print("\tTesting " + str(test_input)) expected = test_cases[test_input] ca.assert_equals(expected, a3.get_content_lines(test_input)) # For longer files, rough check that we get the right number of lines test_cases = { add_sources_to_fname('imbeciles.txt'): 33 - 6, add_sources_to_fname('lonely_as_a_cloud.txt'): 29 - 2, add_sources_to_fname('2013_obama.txt'): 184, } for test_input in test_cases: if verbose: print("\tTesting " + str(test_input)) expected = test_cases[test_input] ca.assert_equals(expected, len(a3.get_content_lines(test_input)))
def test_label(): """Test function a1.label""" print("Testing a1.label") # STUDENTS, we have constructed enough test cases for you, so # you don't need to add any more. You're welcome. print(" running test case 1") s1 = 'blah blah blah <a id="c10782"> more stuff ' s1 = s1 + 'class="course-repeater">CS 1110 abcedfgh' s1 = s1 + 'data-ssr-component="DIS" data-section="208"789012' result = a1.label("10782", s1) cornellasserts.assert_equals("CS 1110 DIS 208", result) print(" running test case 2, has two courses in it and some tricky stuff") s2 = s1 + '<a id="c45"> class="course-repeater">ART 314 ' s2 = s2 + 'data-ssr-component data-ssr-component="LEC" ' s2 = s2 + 'data-section=118 data-section="412"' result = a1.label("45", s2) cornellasserts.assert_equals("ART 314 LEC 412", result)
def test_replace(verbose): print("Running " + inspect.stack()[0][3]) # dictionaries can't have lists as keys, so using tuples test_cases = { ((5, 6), 5, 4): [4, 6], ((5, 6), 6, 4): [5, 4], ((5, 5), 5, -4): [-4, -4], ((), 1, 2): [], ((5, 3, 3455, 74, 74, 74, 3), 3, 20): [5, 20, 3455, 74, 74, 74, 20], ((5, 3, 3455, 74, 74, 74, 3), 1, 20): [5, 3, 3455, 74, 74, 74, 3], } for test_input in test_cases: if verbose: print('\ttrying ' + str(test_input)) test_list = list(test_input[0]) output = lab09.replace(test_list, test_input[1], test_input[2]) ca.assert_equals(test_cases[test_input], output) # see if new list is a different list, even if no values are different ca.assert_false(output is test_list)