diff --git a/solutions/sum_of.py b/solutions/sum_of.py new file mode 100644 index 000000000..42694ab68 --- /dev/null +++ b/solutions/sum_of.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +Created on XX XX XX + +A module gives a summation of two numbers. + +@author: Tagwa Hashim +""" + + +def sum_of(num1, num2): + """ + Adds two numbers and returns their sum. + + Args: + num1: The first number. Can be an integer or a float. + num2: The second number. Can be an integer or a float. + + Returns: + The sum of num1 and num2. + + Raises: + AssertionError: If either num1 or num2 is not a number (int or float). + + Examples: + >>> sum_of(3, 5) + 8 + >>> sum_of(2.5, 3.7) + 6.2 + >>> sum_of("hello", 2.718) + Traceback (most recent call last): + ... + AssertionError: Both arguments must be numbers (int or float). + """ + assert isinstance(num1, (int, float)) and isinstance(num2, (int, float)), ( + "Both arguments must be numbers (int or float)." + ) + return num1 + num2 diff --git a/solutions/tests/test_sum_of.py b/solutions/tests/test_sum_of.py new file mode 100644 index 000000000..c8563b6e3 --- /dev/null +++ b/solutions/tests/test_sum_of.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +""" +Unit tests for the sum_of function. + +@author: Tagwa Hashim +""" + +import unittest + +from solutions.sum_of import sum_of + + +class TestSumOf(unittest.TestCase): + """Test the sum_of function""" + + def test_add_integers(self): + """Test sum_of of two integers.""" + self.assertEqual(sum_of(7, 12), 19) + + def test_add_floats(self): + """Test sum_of of two floats.""" + self.assertEqual(sum_of(1.6, 3.3), 4.9) + + def test_add_mixtype(self): + """Test sum_of of integer and float.""" + self.assertEqual(sum_of(3, 2.05), 5.05) + + def test_add_zero(self): + """Test sum_of with zero.""" + self.assertEqual(sum_of(0, 5), 5) + self.assertEqual(sum_of(5, 0), 5) + + def test_add_negative_numbers(self): + """Test sum_of with negative numbers.""" + self.assertEqual(sum_of(-3, -5), -8) + self.assertEqual(sum_of(-3, 5), 2) + + def test_invalid_input_type_num(self): + """Test with invalid input type for num1 or num2, should raise assertion error""" + + with self.assertRaises(AssertionError): + sum_of("hello", 2) + sum_of(18, "hello") + + +if __name__ == "__main__": + unittest.main()