Effective Python 读书笔记: 第56条: 用unittest来测试全部代码

新建一个文件叫做utils.py,内容如下:

# -*- encoding: utf-8 -*-

import os

'''
第56条: 用unittest来测试全部代码

关键:
1 python是动态语言
特点:
1) 阻碍静态类型检查
2) 容易为代码编写unittest
3) 用动态特性覆写相关行为

2 unittest模块
测试编写可以使用unittest模块
特点:
1) 测试以TestCase形式组织,每个以test开头
2) assertRaises(错误类型,方法名称,传给该方法的参数)
验证是否会抛出异常。
setUp方法: 执行每个测试前,会调用一词
tearDown: 执行每个测试后,会调用一词
上述是为了确保测试独立运行


3 注意
测试文件必须以test开头,否则无法找到;待测试的方法也必须
以test开否,否则无法找到

参考:
Effectiv Python 编写高质量Python代码的59个有效方法
'''

def toUnicode(value):
    if isinstance(value, unicode):
        return value
    elif isinstance(value, str):
        return value.decode('utf-8')
    else:
        raise TypeError('Value must be unicode or str, found: %r' % (value))


def process():
    pass


if __name__ == "__main__":
    process() 

然后新建一个文件叫做test_utils.py.内容如下:

# -*- encoding: utf-8 -*-

from unittest import main
from unittest import TestCase
from driver56 import toUnicode

class TestUtils(TestCase):
    def test_toUnicode_by_str(self):
        self.assertEqual(u'hello', toUnicode('hello'))

    def test_toUnicode_by_unicode(self):
        self.assertEqual(u'hello', toUnicode(u'hello'))

    def test_toUnicode_by_other(self):
        self.assertRaises(TypeError, toUnicode, object())


def process():
    main()


if __name__ == "__main__":
    process() 

猜你喜欢

转载自blog.csdn.net/qingyuanluofeng/article/details/89080520