CompSci Blogs

August 2023 to June 2024

View the Project on GitHub IshanCornick/new_student

21 September 2023

Tester Function

def add_numbers(num1, num2):
    """
    A simple function that adds two numbers.
    """
    return num1 + num2


def test_add_numbers():
    """
    Test function for add_numbers function.
    """
    test_cases = [
        ((3, 5), 8),    # Test case 1: Positive numbers
        ((-3, -5), -8), # Test case 2: Negative numbers
        ((0, 7), 7),    # Test case 3: Zero and positive number
        ((0, -9), -9),  # Test case 4: Zero and negative number
        ((2.5, 3.5), 6) # Test case 5: Float numbers
    ]
   
    for args, expected_result in test_cases:
        try:
            result = add_numbers(*args)
            if result == expected_result:
                print(f"Test passed: {args} => {result}")
            else:
                print(f"Test failed: {args} => {result}, expected {expected_result}")
        except Exception as e:
            print(f"An error occurred during testing: {e}")


# Calling the tester function
test_add_numbers()
Test passed: (3, 5) => 8
Test passed: (-3, -5) => -8
Test passed: (0, 7) => 7
Test passed: (0, -9) => -9
Test passed: (2.5, 3.5) => 6.0
def calculate_factorial(n):
    """
    Calculates the factorial of a non-negative integer n.


    Args:
        n (int): Non-negative integer.


    Returns:
        int: Factorial of n.
       
    Raises:
        ValueError: If n is negative.
    """
    if n < 0:
        raise ValueError("Input must be a non-negative integer")
   
    if n == 0:
        return 1
   
    return n * calculate_factorial(n-1)


def test_factorial():
    """
    Test the calculate_factorial function.
    """
    test_cases = [
        (0, 1),
        (1, 1),
        (5, 120),
        (10, 3628800)
    ]


    for input_value, expected_output in test_cases:
        try:
            result = calculate_factorial(input_value)
            assert result == expected_output
            print(f"Test passed for input {input_value}")
        except AssertionError as e:
            print(f"Test failed for input {input_value}: Expected {expected_output}, got {result}")
        except ValueError as e:
            print(f"Test failed (ValueError) for input {input_value}: {e}")
        except Exception as e:
            print(f"An unexpected error occurred: {e}")


# Run the test function
test_factorial()
Test passed for input 0
Test passed for input 1
Test passed for input 5
Test passed for input 10
def list_operations(numbers):
    """
    Performs operations on a list of numbers.


    Args:
        numbers (list): List of numbers.


    Returns:
        dict: A dictionary with various computed values.
    """
    if not isinstance(numbers, list):
        raise TypeError("Input must be a list of numbers")


    if not numbers:
        raise ValueError("List cannot be empty")


    # Calculate the sum of all numbers
    total_sum = sum(numbers)


    # Find the maximum and minimum values
    max_value = max(numbers)
    min_value = min(numbers)


    # Calculate the mean
    mean = total_sum / len(numbers)


    # Calculate the variance
    variance = sum((x - mean) ** 2 for x in numbers) / len(numbers)


    # Calculate the standard deviation
    std_deviation = variance ** 0.5


    return {
        'sum': total_sum,
        'max': max_value,
        'min': min_value,
        'mean': mean,
        'variance': variance,
        'std_deviation': std_deviation
    }


def complex_tester():
    """
    Complex tester function for list_operations.


    This function performs extensive testing on the list_operations function.


    It includes various test cases to validate the behavior of the function.


    Returns:
        None
    """
    test_cases = [
        # Valid cases
        ([1, 2, 3, 4, 5], {'sum': 15, 'max': 5, 'min': 1, 'mean': 3.0, 'variance': 2.5, 'std_deviation': 1.5811388300841898}),
        ([0, 0, 0, 0, 0], {'sum': 0, 'max': 0, 'min': 0, 'mean': 0.0, 'variance': 0.0, 'std_deviation': 0.0}),
        ([-1, -2, -3, -4, -5], {'sum': -15, 'max': -1, 'min': -5, 'mean': -3.0, 'variance': 2.5, 'std_deviation': 1.5811388300841898}),
        ([10, 20, 30, 40, 50], {'sum': 150, 'max': 50, 'min': 10, 'mean': 30.0, 'variance': 250.0, 'std_deviation': 15.811388300841896}),
       
        # Edge cases
        ([], ValueError),  # Empty list should raise ValueError
        (5, TypeError)     # Non-list input should raise TypeError
    ]


    for input_data, expected_output in test_cases:
        try:
            if expected_output == TypeError:
                # This is an edge case where we expect a TypeError
                list_operations(input_data)
                print(f"Test failed for input {input_data}: Expected TypeError, but no error was raised.")
            elif expected_output == ValueError:
                # This is an edge case where we expect a ValueError
                list_operations(input_data)
                print(f"Test failed for input {input_data}: Expected ValueError, but no error was raised.")
            else:
                # Normal test case
                result = list_operations(input_data)
                assert result == expected_output
                print(f"Test passed for input {input_data}")
        except Exception as e:
            print(f"An unexpected error occurred for input {input_data}: {e}")


# Run the complex tester function
complex_tester()
An unexpected error occurred for input [1, 2, 3, 4, 5]: 
Test passed for input [0, 0, 0, 0, 0]
An unexpected error occurred for input [-1, -2, -3, -4, -5]: 
An unexpected error occurred for input [10, 20, 30, 40, 50]: 
An unexpected error occurred for input []: List cannot be empty
An unexpected error occurred for input 5: Input must be a list of numbers
def add_numbers(num1, num2):
    """
    A simple function that adds two numbers.
    """
    return num1 + num2


def test_add_numbers():
    """
    Test function for add_numbers function.
    """
    test_cases = [
        ((3, 5), 8),    # Test case 1: Positive numbers
        ((-3, -5), -8), # Test case 2: Negative numbers
        ((0, 7), 7),    # Test case 3: Zero and positive number
        ((0, -9), -9),  # Test case 4: Zero and negative number
        ((2.5, 3.5), 6) # Test case 5: Float numbers
    ]
   
    for args, expected_result in test_cases:
        try:
            result = add_numbers(*args)
            if result == expected_result:
                print(f"Test passed: {args} => {result}")
            else:
                print(f"Test failed: {args} => {result}, expected {expected_result}")
        except Exception as e:
            print(f"An error occurred during testing: {e}")


# Calling the tester function
test_add_numbers()
Test passed: (3, 5) => 8
Test passed: (-3, -5) => -8
Test passed: (0, 7) => 7
Test passed: (0, -9) => -9
Test passed: (2.5, 3.5) => 6.0
def calculate_factorial(n):
    """
    Calculates the factorial of a non-negative integer n.


    Args:
        n (int): Non-negative integer.


    Returns:
        int: Factorial of n.
       
    Raises:
        ValueError: If n is negative.
    """
    if n < 0:
        raise ValueError("Input must be a non-negative integer")
   
    if n == 0:
        return 1
   
    return n * calculate_factorial(n-1)


def test_factorial():
    """
    Test the calculate_factorial function.
    """
    test_cases = [
        (0, 1),
        (1, 1),
        (5, 120),
        (10, 3628800)
    ]


    for input_value, expected_output in test_cases:
        try:
            result = calculate_factorial(input_value)
            assert result == expected_output
            print(f"Test passed for input {input_value}")
        except AssertionError as e:
            print(f"Test failed for input {input_value}: Expected {expected_output}, got {result}")
        except ValueError as e:
            print(f"Test failed (ValueError) for input {input_value}: {e}")
        except Exception as e:
            print(f"An unexpected error occurred: {e}")


# Run the test function
test_factorial()
Test passed for input 0
Test passed for input 1
Test passed for input 5
Test passed for input 10
def list_operations(numbers):
    """
    Performs operations on a list of numbers.


    Args:
        numbers (list): List of numbers.


    Returns:
        dict: A dictionary with various computed values.
    """
    if not isinstance(numbers, list):
        raise TypeError("Input must be a list of numbers")


    if not numbers:
        raise ValueError("List cannot be empty")


    # Calculate the sum of all numbers
    total_sum = sum(numbers)


    # Find the maximum and minimum values
    max_value = max(numbers)
    min_value = min(numbers)


    # Calculate the mean
    mean = total_sum / len(numbers)


    # Calculate the variance
    variance = sum((x - mean) ** 2 for x in numbers) / len(numbers)


    # Calculate the standard deviation
    std_deviation = variance ** 0.5


    return {
        'sum': total_sum,
        'max': max_value,
        'min': min_value,
        'mean': mean,
        'variance': variance,
        'std_deviation': std_deviation
    }


def complex_tester():
    """
    Complex tester function for list_operations.


    This function performs extensive testing on the list_operations function.


    It includes various test cases to validate the behavior of the function.


    Returns:
        None
    """
    test_cases = [
        # Valid cases
        ([1, 2, 3, 4, 5], {'sum': 15, 'max': 5, 'min': 1, 'mean': 3.0, 'variance': 2.5, 'std_deviation': 1.5811388300841898}),
        ([0, 0, 0, 0, 0], {'sum': 0, 'max': 0, 'min': 0, 'mean': 0.0, 'variance': 0.0, 'std_deviation': 0.0}),
        ([-1, -2, -3, -4, -5], {'sum': -15, 'max': -1, 'min': -5, 'mean': -3.0, 'variance': 2.5, 'std_deviation': 1.5811388300841898}),
        ([10, 20, 30, 40, 50], {'sum': 150, 'max': 50, 'min': 10, 'mean': 30.0, 'variance': 250.0, 'std_deviation': 15.811388300841896}),
       
        # Edge cases
        ([], ValueError),  # Empty list should raise ValueError
        (5, TypeError)     # Non-list input should raise TypeError
    ]


    for input_data, expected_output in test_cases:
        try:
            if expected_output == TypeError:
                # This is an edge case where we expect a TypeError
                list_operations(input_data)
                print(f"Test failed for input {input_data}: Expected TypeError, but no error was raised.")
            elif expected_output == ValueError:
                # This is an edge case where we expect a ValueError
                list_operations(input_data)
                print(f"Test failed for input {input_data}: Expected ValueError, but no error was raised.")
            else:
                # Normal test case
                result = list_operations(input_data)
                assert result == expected_output
                print(f"Test passed for input {input_data}")
        except Exception as e:
            print(f"An unexpected error occurred for input {input_data}: {e}")


# Run the complex tester function
complex_tester()
An unexpected error occurred for input [1, 2, 3, 4, 5]: 
Test passed for input [0, 0, 0, 0, 0]
An unexpected error occurred for input [-1, -2, -3, -4, -5]: 
An unexpected error occurred for input [10, 20, 30, 40, 50]: 
An unexpected error occurred for input []: List cannot be empty
An unexpected error occurred for input 5: Input must be a list of numbers