目录
1.错误类型
语法错误:syntax error
语义错误
逻辑错误
2.异常处理
try: 可能出现的异常代码
except 异常类型 as 实例: 捕获特定异常信息
else: 未遭遇异常
finally:不论是否遇到异常均会执行
try:
x = 5/0
print(x)
except ZeroDivisionError as e: #如果是ZeroDivisionError错误,e是错误信息
print('不能除以0',e)
except: #其他错误
print("其他错误")
else: #没有错误
print('没有异常')
finally: #finally中的内容最后一定会执行,常用于资源释放等
print('这个代码块最终一定会执行')
不能除以0 division by zero
这个代码块最终一定会执行
raise: 手动抛出异常
def method():
raise NotImplementedError('该方法尚未实现')
method()
Traceback (most recent call last):
File "C:/Users/666/Desktop/demo/demo.py", line 4, in <module>
method()
File "C:/Users/666/Desktop/demo/demo.py", line 2, in method
raise NotImplementedError('该方法尚未实现')
NotImplementedError: 该方法尚未实现
3.测试
假设事先定义好了一个main方法:
def get_formatted_name(first,last):
full_name = "{} {}".format(first,last)
return full_name.title()
对main方法进行测试用例:
class NameTestCase(unittest.TestCase): #继承unittest.TestCase基类
def test_title_name(self):
formatted_name = get_formatted_name('tom','lee')
self.assertEqual(formatted_name,"Tom Leee")
if __name__ == '__main__':
unittest.main()
F
======================================================================
FAIL: test_title_name (__main__.NameTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:/Users/666/Desktop/demo/demo.py", line 7, in test_title_name
self.assertEqual(formatted_name,"Tom Leee")
AssertionError: 'Tom Lee' != 'Tom Leee'
- Tom Lee
+ Tom Leee
? +
----------------------------------------------------------------------
Ran 1 test in 0.000s
FAILED (failures=1)
4.测试级别
1.单元测试
性质:
对代码最基本单元(函数、方法)的测试
给予给定条件判断结果是否符合预期
简化了测试任务
通过unittest模块实现
import unittest
def add(a,b):
return a + b
def substract(a,b):
return a - b
class MyTest(unittest.TestCase):
def test_add(self):
self.assertEqual(20 , add(5,15)) #断言是否相等
def test_substract(self):
self.assertEqual(-10 , substract(5,15))
if __name__ == '__main__':
unittest.main() #调用unittest中的main方法执行测试
测试结果
Testing started at 16:45 ...
C:\Applications\Anaconda3\python.exe "C:\Applications\JetBrains\PyCharm 2019.2.2\helpers\pycharm\_jb_pytest_runner.py" --path C:/Users/666/Desktop/demo/demo.py
Launching pytest with arguments C:/Users/666/Desktop/demo/demo.py in C:\Users\666\Desktop\demo
============================= test session starts =============================
platform win32 -- Python 3.7.4, pytest-5.2.1, py-1.8.0, pluggy-0.13.0 -- C:\Applications\Anaconda3\python.exe
cachedir: .pytest_cache
rootdir: C:\Users\666\Desktop\demo
plugins: arraydiff-0.3, doctestplus-0.4.0, openfiles-0.4.0, remotedata-0.3.2
collecting ... collected 2 items
demo.py::MyTest::test_add PASSED [ 50%]
demo.py::MyTest::test_substract PASSED [100%]
============================== 2 passed in 0.02s ==============================
Process finished with exit code 0
5.代码组织
1.断言
常用:
assertEqual(值,表达式) 是否相等
assertTrue() 是否为真
aseertIn() 是否包含
assertAlmostEqua() 是否几乎相等 (例如用于浮点型计算)
assertIs() 是否为同一引用
assertIsInstance() 是否为某类型实例
assertGreater() 是否大于
...
import unittest
person = {'name':'Mike','age':20}
numbers = [1,2,66,444]
s = 'www.baidu.com'
class TestAssert(unittest.TestCase):
def test_assert_method(self):
self.assertEqual('Mike',person.get('name'))
self.assertTrue('baidu' in s)
self.assertIn('www.baidu',s)
self.assertAlmostEqual(4.4,1.1+3.3)
self.assertIs(True+1,2)
self.assertIsNone(person.get('Name'))
self.assertIsInstance(numbers[0],int)
self.assertGreater(-7 , 1)
if __name__ == '__main__':
unittest.main()
2.装置
测试用例类继承字 unittest.TestCase
test_定义功能测试函数名
setUp() 函数定义准备初始化代码
tearDown() 函数执行清理工作
import unittest
from demo import Calculator
class Test(unittest.TestCase):
def setUp(self): #初始化作用,用于为测试做准备
self.c = Calculator(5,3)
def test_add(self):
self.assertEqual(8,self.c.add())
def test_subtract(self):
self.assertEqual(4,self.c.subtract())
def tearDown(self): #函数执行清理工作,例如释放资源
del self.c
if __name__ == '__main__':
unittest.main()