目录
专栏列表
- python教程(一):环境搭建及pycharm安装
- python 教程(二):语法与数据结构
- python 教程(三):字符串特性大全
- python 教程(四):python运算符合集
- python 教程(五):理解条件语句和循环结构
- python 教程(六):函数式编程
- python 教程(七):match…case 模式匹配
- python 教程(八):高级特性【高逼格代码】
- python 教程(九):内置模块与第三方模块
- python教程(十):面向对象编程(oop)
前言
在软件开发过程中,测试和异常捕获是两个非常重要的环节。测试可以帮助我们确保代码的正确性,而异常捕获则可以提高代码的健壮性和容错性。本篇文章将详细介绍python中的测试方法和异常捕获机制,并通过实例帮助你更好地理解和应用这些知识。
一、python中的测试
1.1 单元测试
单元测试是对软件中的最小可测试单元进行验证的测试。python中有一个内置模块 unittest
,用于编写和运行单元测试。
1.1.1 定义测试类
首先,我们需要定义一个测试类,并继承 unittest.testcase
。
复制并运行下列代码,unittest
会自动查找继承了 unittest.testcase
的类,并执行其中的测试方法。
import unittest
def hello(w):
return f'hello {w}!'
class testmathoperations(unittest.testcase):
def test_hello(self):
self.assertequal(hello('ziyu'), 'hello ziyu!')
def test_subtraction(self):
self.assertequal(5 - 3, 1)
if __name__ == '__main__':
unittest.main()
1.2.1 安装 pytest
pip install pytest
1.2.2 编写测试
创建 pytest-demo.py
文件 ,编写测试不需要继承任何类,只需定义以 test_
开头的函数。
def hello(w):
return f'hello {w}!'
def test_hello():
assert hello('ziyu') == 'hello ziyu!'
def test_subtraction():
assert 5 - 3 == 1
1.2.3 运行测试
在终端运行 pytest
命令,pytest
会自动查找并运行所有以 test_
开头的测试函数。
pytest .\test-demo\pytest-demo.py
二、python中的异常捕获
2.1 常规代码
print('程序开始...')
r = 10 / 0
print('打印结果:', r)
print('后续逻辑。。。。')
2.2 异常基础
在python中,异常是指在程序运行过程中发生的错误。我们可以使用 try
、except
、else
和 finally
关键字来捕获和处理异常。
try:
# 可能发生异常的代码
x = 1 / 0
except zerodivisionerror as e:
# 处理异常
print(f"出错了: {e}")
else:
# 没有发生异常时执行的代码
print("上面代码完美运行")
finally:
# 无论是否发生异常都执行的代码
print("一定会执行的代码")
三、抛出异常(异常传播)
def foo():
raise exception('服务器内部错误') # 抛出异常
def bar():
print('bar ...')
foo() # 获取到异常,但是没用使用try 。。 捕获,导致函数中断执行
print('bar done')
try:
bar()
except exception as e:
print(e) # 最外层捕获
finally:
print('程序结束了')
四、 自定义异常
class customerror(exception):
pass
def coo():
raise customerror('网络错误。。。')
try:
print('自定义错误测试。。。')
coo()
except customerror as e:
print(f"捕获自定义错误: {e}")
发表评论