Python检验函数的方法

2015-12-06  本文已影响84人  Rim99

1.使用assert声明方法

# define a function to test
def fib(x):
    if x==0:
        return  0
    elif x==1:
        return  1
    else:
        return fib(x-1)+fib(x-2)

# define a test function       
def fib_test():
    assert fib(2) == 1, 'The 2nd Fibonacci number should be 1'
    assert fib(3) == 1, 'The 3rd Fibonacci number should be 1'
    assert fib(50) == 7778742049, 'Error at the 50th Fibonacci number'
  
# execute test      
fib_test(2)

fib_test()函数会先执行fib()函数,然后与assert命令的指标进行对比,如果不符就会报错。

2.使用run_docstring_examples函数

def sum_naturals(n):
        """Return the sum of the first n natural numbers.

        >>> sum_naturals(10)
        55
        >>> sum_naturals(100)
        5050
        """
        total, k = 0, 1
        while k <= n:
            total, k = total + k, k + 1
        return total

from doctest import run_docstring_examples
run_docstring_examples(sum_naturals,globals(),True)

函数sum_naturals()在声明时使用三个引号提供了一份简单的说明。在编译器中执行help()函数皆可获得这段说明(按Q退出)。同时,这份说明也指出了特定之下的输出值。利用run_docstring_examples函数可以自动完成检验,并输出检验结果。例如,

Trying:
    sum_naturals(10)
Expecting:
    55
ok
Trying:
    sum_naturals(100)
Expecting:
    5050
ok
上一篇下一篇

猜你喜欢

热点阅读