在 python 中使用 doctest 进行单元测试

新手上路,请多包涵

定义 ‘isPalindrome’ 的函数定义,它检查给定的正数是否为回文,并相应地返回 True 和 False。

  • 写一个 doctest 检查函数调用 ‘isPalindrome(121)’ 是否返回 True。
  • 写一个 doctest 检查函数调用 ‘isPalindrome(344)’ 是否返回 False。
  • 写一个 doctest 检查函数调用 ‘isPalindrome(-121)’ 引发 ValueError 错误消息为 ‘x 必须是正整数’。
  • 编写一个 doctest 检查函数调用 ‘isPalindrome(‘hello’)’ 引发 TypeError 并显示错误消息 ‘x 必须是整数’。

我在下面尝试过,但它给出的答案是 -

真 4 1 1 4 0

但预期的答案是

正确 4 1 1 4 2

 #!/bin/python3
import math
import os
import random
import re
import sys
import inspect

# Complete the isPalindrome function below.
def isPalindrome(x):
    # Write your doctests below.
    """
    >>> isPalindrome(121)
    True
    >>> isPalindrome(344)
    False
    >>> isPalindrome(-121)
    ValueError: x must be positive integer.
    >>> isPalindrome("hello")
    TypeError: x must be integer.
    """

    # Write the functionality below
    try:
        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
        elif(x<0):
            raise TypeError
        else:
            raise ValueError
    except ValueError:
        raise ValueError("x must be positive integer")
    except TypeError:
        raise TypeError("x must be an integer")

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()

请建议

原文由 R D 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 361
1 个回答

在 doctest 中,为了检测异常,它需要两个关键字: TracebackExceptionName

例如:如果你的块引发 ValueError ,你在 doctest 文件中提供的测试用例应该有一个 Traceback 行,它旁边的第二行应该有异常名称及其自定义消息(如果有)。

以下是测试代码的正确写法:

 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()

原文由 Aradhya 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进