1.单元测试
单元测试是用来对一个模块、一个函数或者一个类类进行正确性检验的测试工作
(1)编写单元测试
# 编写一个Dict类,可以通过属性来访问
class Dict(object):
def __init__(self, **kw):
super().__init__(**kw)
def __getattr__(self, key):
try:
return self[key]
except KeyError:
raise AttributeError(r"'Dict' object has no attribute '%s'" % key)
def __setattr__(self, key, value):
self[key] = value
# 编写单元测试
import unittest
from mydict import Dict
class TestDict(unittest.TestCase):
def test_init(self):
d = Dict(a = 1, b = 'test')
self.assertEqual(d.a, 1) # 最长用的断言:assertEqual()
self.assertEqual(d.b, 'test')
self.assertTrue(isinstance(d, dict))
def test_key(self):
d = Dict()
d['key'] = 'value'
self.assertEqual(d.key, 'value')
def test_attr(self):
d = Dict()
d.key = 'value'
self.assertEqual('key' in d)
self.assertEqual(d['key'], 'value')
def test_keyerror(self):
d = Dict()
with self.assertRaises(KeyError): # 另一种断言:assertRaises(),期待抛出指定类型的Error
value = d['empty']
def test_attrerror(self):
d = Dict()
with self.assertRaises(AttributeError):
value = d.empty
(2) 运行单元测试
1)方法一:在写的单元测试的文件,如webtest.py的最后两行添加代码
if __name__ == '__main__'
unittest.main()
class Dict(object):
def __init__(self, **kw):
super().__init__(**kw)
def __getattr__(self, key):
try:
return self[key]
except KeyError:
raise AttributeError(r"'Dict' object has no attribute '%s'" % key)
def __setattr__(self, key, value):
self[key] = value
import unittest
from mydict import Dict
class TestDict(unittest.TestCase):
def test_init(self):
d = Dict(a = 1, b = 'test')
self.assertEqual(d.a, 1) # 最长用的断言:assertEqual()
self.assertEqual(d.b, 'test')
self.assertTrue(isinstance(d, dict))
def test_key(self):
d = Dict()
d['key'] = 'value'
self.assertEqual(d.key, 'value')
def test_attr(self):
d = Dict()
d.key = 'value'
self.assertEqual('key' in d)
self.assertEqual(d['key'], 'value')
def test_keyerror(self):
d = Dict()
with self.assertRaises(KeyError): # 另一种断言:assertRaises(),期待抛出指定类型的Error
value = d['empty']
def test_attrerror(self):
d = Dict()
with self.assertRaises(AttributeError):
value = d.empty
if __name__ = '__main__'
unittest.main()
2)方法二:在命令行通过参数 -m unittest直接进行单元测试
python -m unittest 1120-0.py
(3)setUp与tearDown
class Dict(object):
def __init__(self, **kw):
super().__init__(**kw)
def __getattr__(self, key):
try:
return self[key]
except KeyError:
raise AttributeError(r"'Dict' object has no attribute '%s'" % key)
def __setattr__(self, key, value):
self[key] = value
import unittest
from mydict import Dict
class TestDict(unittest.TestCase):
def test_init(self):
d = Dict(a = 1, b = 'test')
self.assertEqual(d.a, 1) # 最长用的断言:assertEqual()
self.assertEqual(d.b, 'test')
self.assertTrue(isinstance(d, dict))
def test_key(self):
d = Dict()
d['key'] = 'value'
self.assertEqual(d.key, 'value')
def test_attr(self):
d = Dict()
d.key = 'value'
self.assertEqual('key' in d)
self.assertEqual(d['key'], 'value')
def test_keyerror(self):
d = Dict()
with self.assertRaises(KeyError): # 另一种断言:assertRaises(),期待抛出指定类型的Error
value = d['empty']
def test_attrerror(self):
d = Dict()
with self.assertRaises(AttributeError):
value = d.empty
# 添加setUp和tearDown
def setUp(self): # 调用测试方法前被执行
print('setUp...')
def tearDown(self): # 调用测试方法后被执行
print('tearDown...')
2.文档测试
在写注释的时候,添加这样的内容,告诉函数的调用者该函数的期望输入和输出
def abs(n):
'''
Function to get absolute value of number.
Example:
>>> abs(1)
1
>>> abs(-1)
1
>>> abs(0)
0
'''
return n if n >=0 else (-n)
"文档测试"(doctest)模块可以直接提取注释中的代码并执行测试。 doctest严格按照Python交互命令行的输入输出来判断测试结果是否正确,只有测试异常的时候,可以用...表示中间一大段烦人的输出。
例如:
class Dict(dict):
'''
Simple dict but also support access as x.y style.
>>>d1 = Dict()
>>>d1['x'] = 100
>>>d1.x
100
>>>d1.y = 200
>>>d1['y']
200
>>>d2 = Dict(a=1, b=2, c='3')
>>>d2.c
'3'
>>>d2['empty']
Traceback(most recent call last):
....
KetError:'empty'
>>>d2.empty
Traceback(most recent call last):
...
AttributeError:'Dict' object has no attribute 'empty'
'''
def __init__(self, **kw):
super(Dict, self).__init__(**kw)
def __getattr__(self, key):
try:
return self[key]
except KeyError:
raise Attribute(r"'Dict' object has no attribute '%s'" % key)
def __setattr__(self, key, value):
self[key] = value
if __name__ == '__main__':
import doctest
doctest.testmod()
3.文件读写
(1)读文件
1)读取文件
# 打开文件 f = open('文件名', '标示符')
f = open('/Users/michael/test.txt', 'r')
# 读取文件的全部内容,Python把内容读到内存
f.read()
# 关闭文件
f.close()
2)读取文件的两种写法 a.第一种
try:
f = open('/path/to/file', 'r')
print(f.read())
finally:
if f:
f.close()
b.第二种
with open('/path/to/file', 'r') as f:
print(f.read())
3)读取文件的注意事项
# 如果文件很小,read()一次性读取最方便
# 如果不能确定文件大小,反复调用read(size)比较保险
# 如果是配置文件,调用readlines()最方便
for line in f.readlines():
print(lines.strip())
(2).file-like Object
open()函数返回的这种有个read()方法的对象
(3).二进制文件
f = open('/User/michael/test.jpg', 'rb')
print f.read()
(4).字符编码
1)读取非UTF-8编码的文本文件 例如:传入GBK编码的文件
f = open('/Users/michael/gbk.txt', 'r', encoding='gbk')
print f.read()
2)遇到编码错误后的处理
f = open('/Users/michael/gbk.txt', 'r', encoding='gbk', errors='ignore')
(5)写文件:和读文件操作差不多
# 'w':写文本文件
# 'wb':写二进制文件
with open('/Users/michael/test.txt', 'w') as f:
f.write('Hello, world!')