Skip to content

Commit

Permalink
Fix #28: Make test more robust (#35)
Browse files Browse the repository at this point in the history
Modify the `test` function to validate the test table and confirm: 
 - the test table is a list or tuple
 - each test case from the test table is list or tuple
 - the first element of each case is a string
 - each test case has the correct number of args
  • Loading branch information
densnow authored Apr 12, 2024
1 parent b0a3c9c commit 7457c84
Showing 1 changed file with 37 additions and 14 deletions.
51 changes: 37 additions & 14 deletions src/algoesup/test.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,43 @@ def test(function: Callable, test_table: list) -> None:
Args:
function (Callable): The function to be tested.
test_table (list): The list of tests. Each element of test_table is a list or
test_table (list): The list of tests. Each element of test_table is a list or
tuple with: a string (the test case name); one or more values (the inputs to the function);
the expected output value.
"""
print(f"Testing {function.__name__}...")
passed = failed = 0
for test_case in test_table:
name = test_case[0]
inputs = test_case[1:-1]
expected = test_case[-1]
actual = function(*inputs)
if actual != expected:
print(name, "FAILED:", actual, "instead of", expected)
failed += 1
else:
passed += 1
print("Tests finished:", passed, "passed,", failed, "failed.")
not_tested = f"The test table is invalid, {function.__name__} has NOT been tested."
if not isinstance(test_table, (list, tuple)):
print(f"Error: The test table must be a list or tuple.\n{not_tested}")
return
# The number of arguments function expects.
expects = function.__code__.co_argcount
invalid = []
for num, test_case in enumerate(test_table, start=1):
if not isinstance(test_case, (list, tuple)):
invalid.append(f"test case {num} must be a list or tuple.")
elif not isinstance(test_case[0], str):
invalid.append(f"test case {num} must have string as first element.")
elif len(test_case[1:-1]) != expects:
num_args = len(test_case[1:-1])
invalid.append(
f'test case "{test_case[0]}" has {num_args} input(s) instead of {expects}'
)
if invalid:
for msg in invalid:
print(f"Error: {msg}")
print(not_tested)
return
else:
print(f"Testing {function.__name__}...")
passed = failed = 0
for test_case in test_table:
name = test_case[0]
inputs = test_case[1:-1]
expected = test_case[-1]
actual = function(*inputs)
if actual != expected:
print(name, "FAILED:", actual, "instead of", expected)
failed += 1
else:
passed += 1
print("Tests finished:", passed, "passed,", failed, "failed.")

0 comments on commit 7457c84

Please sign in to comment.