您的位置:首页 > 编程语言 > Python开发

python测试——doctest和unittest

2014-07-28 17:12 501 查看
一. doctest——功能相对较少,主要用于文档说明时对某个函数的使用说明。

下面是一个官方的例子:

"""

This is the "example" module.

The example module supplies one function, factorial(). For example,

>>> factorial(5)

120

"""

def factorial(n):

"""Return
the factorial of n, an exact integer >= 0.

If the result is small enough to fit in an int, return an int.

Else return a long.

>>> [factorial(n) for n in range(6)]

[1, 1, 2, 6, 24, 120]

>>> [factorial(long(n)) for n in range(6)]

[1, 1, 2, 6, 24, 120]

>>> factorial(30)

265252859812191058636308480000000L

>>> factorial(30L)

265252859812191058636308480000000L

>>> factorial(-1)

Traceback (most recent call last):

...

ValueError: n must be >= 0

Factorials of floats are OK, but the float must be an exact integer:

>>> factorial(30.1)

Traceback (most recent call last):

...

ValueError: n must be exact integer

>>> factorial(30.0)

265252859812191058636308480000000L

It must also not be ridiculously large:

>>> factorial(1e100)

Traceback (most recent call last):

...

OverflowError: n too large

"""

import math

if not n >= 0:

raise ValueError("n
must be >= 0")

if math.floor(n) != n:

raise ValueError("n
must be exact integer")

if n+1 == n: # catch
a value like 1e300

raise OverflowError("n
too large")

result = 1

factor = 2

while factor <= n:

result *= factor

factor += 1

return result

if __name__ == "__main__":

import doctest

doctest.testmod()

将上述代码保存为"factorial.py",然后在终端中输入:#python factorial.py -v 就能看到测试结果。

自从Python2.6之后,可以直接在命令行敲上命令运行testmod()来运行测试:

# python -m doctest -v factorial.py
说明:

if __name__ == "__main__":

import doctest

doctest.testmod()

这部分也可以写成下面这样:

if __name__ == "__main__":

import doctest,factorial

doctest.testmod(factorial)

二. unittest——通用测试框架,功能比较全,能够用来做真正的单元测试。

1. 使用unittest进行测试的流程:

import unittest
定义一个继承自unittest.TestCase的测试用例类
定义setUp和tearDown,在每个测试用例前后做一些辅助工作。
定义测试用例,名字以test开头。
一个测试用例应该只测试一个方面,测试目的和测试内容应很明确。主要是调用assertEqual、assertRaises等断言方法判断程序执行结果和预期值是否相符。
调用unittest.main()启动测试
如果测试未通过,会输出相应的错误提示。如果测试全部通过则不显示任何东西,添加-v参数会显示详细信息。

2. unittest模块提供的方法:

方法测试内容最低支持版本
assertEqual(a, b) a == b
assertNotEqual(a, b) a != b
assertTrue(x) bool(x) is True
assertFalse(x) bool(x) is False
assertAlmostEqual(a, b) round(a-b, 7) == 0
assertNotAlmostEqual(a, b) round(a-b, 7) != 0
assertIs(a, b)a is b2.7
assertIsNot(a, b)a is not b2.7
assertIsNone(x)x is None2.7
assertIsNotNone(x)x is not None2.7
assertIn(a, b)a in b2.7
assertNotIn(a, b)a not in b2.7
assertIsInstance(a, b)isinstance(a, b)2.7
assertNotIsInstance(a, b)not isinstance(a, b)2.7
assertGreater(a, b)a > b2.7
assertGreaterEqual(a, b)a >= b2.7
assertLess(a, b)a < b 2.7
assertLessEqual(a, b)a <= b 2.7
assertRegexpMatches(s, re)regex.search(s) 2.7
assertNotRegexpMatches(s, re)not regex.search(s) 2.7
assertItemsEqual(a, b)sorted(a) == sorted(b) and works with unhashable objs2.7
assertDictContainsSubset(a, b)all the key/value pairs in a exist in b2.7
assertMultiLineEqual(a, b)strings2.7
assertSequenceEqual(a, b)sequences2.7
assertListEqual(a, b)lists2.7
assertTupleEqual(a, b)tuples2.7
assertSetEqual(a, b)sets or frozensets2.7
assertDictEqual(a, b)dicts2.7
assertMultiLineEqual(a, b) strings2.7
assertSequenceEqual(a, b) sequences2.7
assertListEqual(a, b)lists 2.7
assertTupleEqual(a, b)tuples2.7
assertSetEqual(a, b) sets or frozensets2.7
assertDictEqual(a, b) dicts 2.7
示例:

import unittest

import urllib #引入模块

class TestUrlHttpcode(unittest.TestCase):

def setUp(self):

urlinfo = ['http://www.baidu.com', 'http://www.163.com', 'http://www.google.com.hk' ] #要测试的网址

self.checkurl = urlinfo

def test_ok(self): #测试用例

for m in self.checkurl:

httpcode = urllib.urlopen(m).getcode() #返回码

self.assertEqual(httpcode, 200) # != 200 表示打开失败

if __name__ == "__main__"

unittest.main() #启动测试

将上述代码保存位"unittest_ex1.py",然后通过命令: #python unittest_ex1.py -v 来 查看测试结果。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: