Problem 2 - Unit Testing using doctest in Python

Rumman Ansari   Software Engineer     962 Share
☰ Table of Contents

Table of Content:


2. Problem 2 - Unit Testing using doctest in Python

 

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

• Define doctests for '__init_' which creates a circle 'c1' with radius 2.5, and checks if the accessing attribute 'radius', returns the value 2.5.

• 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 the 'math' module.

• Define doctests for 'area which creates a circle 'c1' with radius 2.5, and checks if its computed area is 19.63.

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

• Define doctests for 'circumference' which creates a circle 'c1' with radius 2.5, and checks if its computed circumference is 15.71.

Code


import inspect
import doctest
import re
import math

# Define the class 'Circle' and its methods with proper doctests:
class Circle:
    
    def __init__(self, radius):
        """
        >>> c1 = Circle(2.5)
        >>> c1.radius
        2.5
        """
        self.radius = radius
        
    def area(self):
        """
        >>> c1 = Circle(2.5)
        >>> round(c1.area(), 2)
        19.63
        """
        return math.pi * (self.radius ** 2)
        
        
    def circumference(self):
        """
        >>> c1 = Circle(2.5)
        >>> round(c1.circumference(), 2)
        15.71
        """
        return 2 * math.pi * self.radius
        
if __name__ == '__main__':
    doctest.testmod()
    
    c2 = Circle(2.5)
    doc1 = inspect.getdoc(c2.__init__)
    doc2 = inspect.getdoc(c2.area)
    doc3 = inspect.getdoc(c2.circumference)
    
    class_count = len(re.findall(r'Circle', doc1))
    func1_count = len(re.findall(r'c1.radius', doc1))
    func1_val = len(re.findall(r'2.5', doc1))
    
    print(str(class_count), str(func1_count), str(func1_val))
    
    class_count = len(re.findall(r'Circle', doc2))
    func1_count = len(re.findall(r'c1.area', doc2))
    func1_val = len(re.findall(r'19.63', doc2)) 
                      
    print(str(class_count), str(func1_count), str(func1_val))
                      
    class_count = len(re.findall(r'Circle', doc3))
    func1_count = len(re.findall(r'c1.circumference', doc3))
    func1_val = len(re.findall(r'15.71', doc3)) 
                      
    print(str(class_count), str(func1_count), str(func1_val))