Problem 1 - Unit Testing using unittest in Python

Rumman Ansari   Software Engineer   2023-02-27   617 Share
☰ Table of Contents

Table of Content:


Python Unit Test

1. Problem 1 - Unit Testing using unittest in Python

 

Complete the definition of class 'Circle' with the following specifications:

• Define class method '_init_' which initializes a circle with attribute 'radius', having the following restrictions:

• 'radius' must be a numeric value. If not, raise TypeError with error message "radius must be a

number".

• 'radius' must be between 0 and 1000 (inclusive on both sides). If not, raise ValueError with error message "radius must be between 0 and 1000 inclusive".

• Define class method 'area' which computes the area of a circle, and returns the value rounded off to 2 decimals. Hint: Use 'pi' value from 'math' module.

• Define the class method 'circumference' which computes the circumference of a circle, and returns the value rounded off to 2 decimals. Hint: Use 'pi' value from 'math' module.

 

Complete the definition of class 'TestingCircleCreation' which tests the behavior of the '__init__' method, as specified: Sipping

• Define test method 'test_creating_circle_with_numeric_radius' which creates a circle with radius 2.5, and checks if its radius matches the value 2.5.

• Define test method 'test_creating_circle_with_negative_radius' which checks if a ValueError exception is raised with the error message "radius must be between 0 and 1000 inclusive" while creating a circle of radius -2.5.

• Define test method 'test_creating_circle_with_greaterthan_radius' which checks if a ValueError exception is raised with the error message "radius must be between 0 and 1000 inclusive" while creating a circle of radius 1000.1.

• Define test method 'test_creating_circle_with_nonnumeric radius' which checks if a TypeError exception is raised with the error message "radius must be a number" while creating a circle of radius 'hello'.


import inspect
import re
import unittest
import math

# Define class 'Circle' and its methods with proper doctests:
class Circle:
    
    def __init__(self, radius):
        if not isinstance(radius, (int, float)):
            raise TypeError("radius must be a number")
        if not (0 <= radius <= 1000):
            raise ValueError("radius must be between 0 and 1000 inclusive")
        self.radius = radius
        
    def area(self):
        return round(math.pi * self.radius ** 2, 2)
               
    def circumference(self):
        return round(2 * math.pi * self.radius, 2)


        
class TestCircleCreation(unittest.TestCase):

    def test_creating_circle_with_numeric_radius(self):
        c1 = Circle(2.5)
        self.assertEqual(c1.radius, 2.5)
    
    def test_creating_circle_with_negative_radius(self):
        with self.assertRaises(ValueError) as cm:
            Circle(-2.5)
        self.assertEqual(str(cm.exception), "radius must be between 0 and 1000 inclusive")
    
    def test_creating_circle_with_greaterthan_radius(self):
        with self.assertRaises(ValueError) as cm:
            Circle(1000.1)
        self.assertEqual(str(cm.exception), "radius must be between 0 and 1000 inclusive")
        
    def test_creating_circle_with_nonnumeric_radius(self):
        with self.assertRaises(TypeError) as cm:
            Circle('hello')
        self.assertEqual(str(cm.exception), "radius must be a number") 

if __name__ == '__main__':
    
    fptr = open('output.txt', 'w')
    
    runner = unittest.TextTestRunner(fptr)
    
    unittest.main(testRunner=runner, exit=False)
    
    fptr.close()
    
    with open('output.txt') as fp:
        output_lines = fp.readlines()
    
    
    pass_count = len(re.findall(r'\.', output_lines[0]))
                       
    print(str(pass_count))
                       
    doc1 = inspect.getsource(TestCircleCreation.test_creating_circle_with_numeric_radius)
    doc2 = inspect.getsource(TestCircleCreation.test_creating_circle_with_negative_radius)
    doc3 = inspect.getsource(TestCircleCreation.test_creating_circle_with_greaterthan_radius)
    doc4 = inspect.getsource(TestCircleCreation.test_creating_circle_with_nonnumeric_radius)
    
    assert1_count = len(re.findall(r'assertEqual', doc1))
    
    print(str(assert1_count))
    
    assert1_count = len(re.findall(r'assertEqual', doc2))
    assert2_count = len(re.findall(r'assertRaises', doc2))
    
    print(str(assert1_count), str(assert2_count))
    
    assert1_count = len(re.findall(r'assertEqual', doc3))
    assert2_count = len(re.findall(r'assertRaises', doc3))
    
    print(str(assert1_count), str(assert2_count))
    
    assert1_count = len(re.findall(r'assertEqual', doc4))
    assert2_count = len(re.findall(r'assertRaises', doc4))
    
    print(str(assert1_count), str(assert2_count))