Python 测试入门

Python 测试入门

Alexander Levin

Data Scientist

为何测试如此重要?

常见问题:

  • 缺陷与错误
  • 硬件故障
  • 非预期或不可预测行为

这些问题都可能显著增加修复成本。

测试有助于:

  • 发现缺陷与错误
  • 降低软件失效风险
  • 提升软件的可靠性、功能性与性能
Python 测试入门

什么是测试?

  • 测试:评估系统或软件的过程
  • 我们需要测试以确保其满足规定的需求

  • 测试用例:用于验证软件或系统正确性的步骤

Python 测试入门

课程先修要求

  • 高级 Python 编程
  • assert 语句
  • 装饰器
  • 面向对象概念(类、方法、继承)
Python 测试入门

现实中的测试

以飞机为例:

  • 外观检查
  • 电子与机械检查
  • 燃油检查
  • 乘客检查
  • 天气检查
  • 空管放行许可

以上都是测试!目的是保障安全。

起飞前的飞机

Python 测试入门

Python 中的 assert

  • assert condition:用于测试 condition 是否为 True
  • 若为 False,Python 将抛出 AssertionError
Python 测试入门

使用 pytest 测试:简单示例

pytest:一个流行的 Python 测试框架,便于编写测试。

使用 pytest 编写的"assert"测试示例:

import pytest

# A function to test
def squared(number):
    return number * number

# A test function always starts with "test"
def test_squared():
    assert squared(-2) == squared(2)
Python 测试入门

上下文管理器回顾

  • 上下文管理器:通过 with 语句使用的 Python 对象
  • 用于设置与清理临时上下文
# 写文件示例
with open("hello_world.txt", 'w') as hello_file:
    hello_file.write("Hello world \n")
Python 测试入门

认识 pytest:raises

pytest.raises:当预期测试会抛出 Exception 时使用

import pytest

# A function to test
def division(a, b):
    return a / b

# A test function
def test_raises():
    with pytest.raises(ZeroDivisionError):
        division(a=25, b=0)
Python 测试入门

小结

测试:

  • 评估软件是否按预期工作的过程
  • 存在于日常生活中
  • 对应对软件开发挑战至关重要
  • 有助于确保问题被正确解决

测试实现:

  • pytest:强大的 Python 框架,简化测试流程
  • assert:Python 关键字,在 pytest 中用于校验条件编写基础测试
  • pytest.raises:上下文管理器,用于编写预期抛出 Exception 的测试
Python 测试入门

让我们练习!

Python 测试入门

Preparing Video For Download...