Problem 1 - Unit Testing using doctest in Python

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

Table of Content:


1. Problem 1 - Unit Testing using doctest in Python

A palindrome is number or other sequence of characters which is the same when read backward or forward.

Define the function 'isPalindrome' and write doctests which test the functionality of 'isPalindrome' as specified in the following:

 

Tasks to be performed

• Complete the function definition of 'isPalindrome' which checks if a given positive integer is a palindrome or not, and returns True and False correspondingly.

• Write a doctest which checks if the function call 'isPalindrome(121)' returns True.

• Write a doctest which checks if the function call 'isPalindrome(344)' returns False.

• Write a doctest which checks if the function call 'isPalindrome(-121)' raises a 'ValueError' with an error message: "x must be a positive integer".

• Write a doctest which checks if the function call 'isPalindrome("hello")' raises a 'TypeError' with an error message: "x must be an integer".


#!/bin/python3

import math
import os
import random
import re
import sys
import inspect



def isPalindrome(x):
    # Write the doctests:
    """
    >>>isPalindrome(121)
    True
    >>>isPalindrome(344)
    False
    >>>isPalindrome(-121)
    Traceback (most recent call last):
    ValueError : x must be a positive integer
    >>>isPalindrome("hello")
    Traceback (most recent call last):
    TypeError : x must be an integer
    """
    # Write the functionality:
    x = int(x)
    temp=x
    rev=0
    if(x>0):
        while(x>0):
            dig=x%10
            rev=rev*10+dig
            x=x//10
        if(temp==rev):
            return True
        else:
            return False

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    x = input()
    
    if x.isdigit():
        x = int(x)

    res = isPalindrome(x)
    
    doc = inspect.getdoc(isPalindrome)
    
    func_count = len(re.findall(r'isPalindrome', doc))
    true_count = len(re.findall(r'True', doc))
    false_count = len(re.findall(r'False', doc))
    pp_count = len(re.findall(r'>>>', doc))
    trace_count = len(re.findall(r'Traceback', doc))

    fptr.write(str(res)+'\n')
    fptr.write(str(func_count)+'\n')
    fptr.write(str(true_count)+'\n')
    fptr.write(str(false_count)+'\n')
    fptr.write(str(pp_count) + '\n')
    fptr.write(str(trace_count) + '\n')

    fptr.close()