Python-使用unittest进行单元测试和文档测试
2019-01-21
本博客所有文章采用的授权方式为 自由转载-非商用-非衍生-保持署名 ,转载请务必注明出处,谢谢。
声明: 本博客欢迎转发,但请保留原作者信息!
github地址:atanx
新浪微博:@蜀山掌门V
QQ:365039667
博客地址:江斌的博客
内容仅供学习参考,如有不当引用,请告知博主。
单元测试和文档测试
#!/usr/bin/env python
# coding=utf-8
""" 测试 heapq """
import heapq
import unittest
class Item(object):
"""
>>> a= Item(6)
>>> a.value
6
"""
def __init__(self, v):
self.value = v
def __lt__(self, other):
return self.value < other.value
def __repr__(self):
return 'Item({value})'.format(value=self.value)
__str__ = __repr__
def log(func):
def wrapper(*args, **kwargs):
print "hello this is log"
return func(*args, **kwargs)
return wrapper
def log2(text):
def wrapper(func):
def _wrapper(*args, **kwargs):
t = args[0]
if hasattr(t, 'messages'):
t.messags.append(text)
else:
t.messages = [text]
print text
return func(*args, **kwargs)
return _wrapper
return wrapper
class TestHeapq(unittest.TestCase):
@log2("hello 12")
def setUp(self):
print "setup..."
def tearDown(self):
print "tearDown..."
@unittest.skip('跳过该测试\n')
def test_heapq(self):
x = [1, 2, 3, 5, 610]
a = heapq.nlargest(2, x)
self.assertEqual(a, [610, 5])
def test_heapq_item(self):
x = [1, 2, 3, 5, 610]
z = [Item(i) for i in x]
a = heapq.nlargest(2, z)
a = [i.value for i in a]
self.assertEqual(a, [610, 5])
print self.messages
if __name__ == "__main__":
unittest.main()