首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >python中函数的Doc测试

python中函数的Doc测试
EN

Stack Overflow用户
提问于 2019-03-31 10:15:07
回答 1查看 344关注 0票数 1

我想定义一个函数isPalindrome并编写一个doctest

我的产出:

真实4 1 1 4 0

预期产出:

真实4 1 1 4 2

使用的代码:

代码语言:javascript
运行
复制
import math
import random
import re
import inspect

def isPalindrome(x):

    """
    >>> isPalindrome(121)
    True
    >>> isPalindrome(344)
    False
    >>> isPalindrome(-121)
    ValueError: x must be positive integer.
    >>> isPalindrome("hello")
    TypeError: x must be integer.
    """  


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

回答 1

Stack Overflow用户

发布于 2019-04-01 08:42:47

您的doc测试没有正确处理异常,下面是更正的测试:

代码语言:javascript
运行
复制
"""
>>> isPalindrome(121)
True
>>> isPalindrome(344)
False
>>> isPalindrome(-121)
Traceback (most recent call last):
    ...
ValueError: x must be positive integer.
>>> isPalindrome("hello")
Traceback (most recent call last):
    ...
TypeError: x must be an integer.
"""  

请注意,我将Traceback (most recent call last): ...添加到例外情况中,并将an添加到TypeError: x must be an integer.中。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55439879

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档