Skip to content
Snippets Groups Projects
Commit 03fc255e authored by Erkki Kaila's avatar Erkki Kaila
Browse files

initial commit

parents
No related branches found
No related tags found
No related merge requests found
import inspect, traceback
def test_function_name():
"""
Tests if the function with given name exists.
Additionally, sets the FUNCTION variable to point to the function,
if it exists.
"""
global FUNCTION
if FUNCTION_NAME in globals():
print(f"Name {FUNCTION_NAME} defined succesfully in the program.")
FUNCTION = globals()[FUNCTION_NAME]
if inspect.isfunction(FUNCTION):
return True
return False
else:
print(f"Function {FUNCTION_NAME} does not seem to exist. Check your code!")
return False
def test_number_of_parameters():
"""" Outputs the number of parameters in a function """
try:
pcount = FUNCTION.__code__.co_argcount
print(f"Function has {pcount} parameters defined.")
return True
except:
print("Could not fetch function parameter count.")
return False
def test_parameter_types():
""" Outputs the type hints of parameters if any """
sig = FUNCTION.__annotations__
types = [format_type_name(type) for name,type in sig.items() if name != "return"]
print("Parameter types:", ", ".join(types))
return True
def test_return_value_type():
""" Outputs return value of the function if any. """
sig = FUNCTION.__annotations__
try:
rtype = format_type_name(sig["return"])
print("Return value type:", rtype)
return True
except:
print("There was a problem in the return type hint in the program.")
return False
def format_type_name(classname: "type"):
""" Helper method for formatting type string to more readable form """
classname = str(classname)
return classname.replace("<class '","").replace("'>", "")
def format_function_name(fname: str):
""" Helper function for formatting function name string to readable form """
return fname[:fname.find(" at")].replace("<function ", "")
def display_test_result(function_name: str, params: str, expected: str, got: str):
""" Displays the test results of a function call """
print(f"<ignore>Function {function_name} was called like this:")
print(f"<ignore>{function_name}{params}")
print(f"<ignore>Expected result was {expected}")
print(f"Your function returned {got}")
def test_function_call(func: callable, expected: str, *param_list):
""" Executes a function with given parameters and displays the results """
try:
result = str(func(*param_list))
display_test_result(format_function_name(str(func)), str(param_list), expected, result)
return True
except Exception as exp:
print("Function call")
print(f"{format_function_name(str(func))}({param_list})")
print("resulted in error:")
print(exp)
print("<ignore>")
print(traceback.format_exc())
return False
# ---------------------------------------------------
# STUDENT CODE: WRITE YOUR SOLUTION HERE!
# ---------------------------------------------------
def sum_of_values(a: int, b: int) -> int:
return a + b
# ----------------------------------------------------
# These are test functions related to this specific exercise
# ----------------------------------------------------
def test_with_positives():
for v1, v2 in [(1,1), (6,9), (5,500), (1999, 1)]:
if not test_function_call(sum_of_values, str(v1 + v2), v1, v2):
return False
print("<ignore>")
return True
def test_with_negatives():
for v1, v2 in [(-1,1), (6,-9), (-5,-500)]:
if not test_function_call(sum_of_values, str(v1 + v2), v1, v2):
return False
print("<ignore>")
return True
# ----------------------------------------------------
# Testing done here
# ----------------------------------------------------
# Note, that you can test several functions by looping the stuff below
# Constants for testing
FUNCTION_NAME = "sum_of_values"
FUNCTION = None # set automatically by test_function_name if succesful
PARAM_LIST = (int, int) # list of parameter types, use empty tuple if none
RETURN_VALUE = int # function return value, use None if no value
# Include the list of tests you want to execute
# Add your own test functions in the list
testlist = [
test_function_name,
test_number_of_parameters,
test_parameter_types,
test_return_value_type,
test_with_positives,
test_with_negatives
]
# Runs tests
for test in testlist:
if not test():
break
print("<ignore>") # empty string in ViLLE output
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment