0
点赞
收藏
分享

微信扫一扫

操作系统:内存----知识点

eelq 2024-08-03 阅读 41

目录

专栏列表

  • 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中,异常是指在程序运行过程中发生的错误。我们可以使用 tryexceptelsefinally 关键字来捕获和处理异常。

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}")

在这里插入图片描述

举报

相关推荐

0 条评论