> 文章列表 > Python assert实现软件测试

Python assert实现软件测试

Python assert实现软件测试

  • PythonPythonPython 对于测试非常看重,例如测试中最常见的操作——断言 assertassertassert,其在 PythonPythonPython 中就是一个关键字而不是一个函数。而在 CCC 语言中,assertassertassert 只是一个普通的函数。从这点也可以看出,PythonPythonPython 将测试当作最基础的部分。
  • 需要注意的是,默认情况下,PythonPythonPython 解释器在运行时会忽略所有的 assertassertassert 语句,因此在发布版本中,assertassertassert 语句通常应该被禁用。可以通过使用 -O(大写字母 O)命令行选项来启用断言检查,例如 python -O myscript.py,这样在运行时 assertassertassert 语句将会生效。
  • PythonPythonPython 中,assertassertassert 关键字用于编写断言语句,用于在代码中检查某个条件是否为真,如果条件不满足,则会引发 AssertionErrorAssertionErrorAssertionError 异常。其基本语法如下:
assert condition [,message]
其中 $'condition'$ 是需要检查的条件表达式语句,如果结果为 $'False'$ ,则会触发 $'AssertionError'$异常;$message$ 是一个可选的字符串,用于在抛出异常时提供错误消息,可以帮助调试和定位错误。

以下是一个简单的示例,展示了如何在 PythonPythonPython 中使用 assertassertassert 关键字:

def divide(a, b):assert b != 0, "除数不能为0"return a / bresult = divide(10, 5)
print(result)  # 输出:2.0result = divide(10, 0)  # 触发 AssertionError,错误消息为 "除数不能为0"

== 1. 可以直接是使用 assert 在源代码中对其进行测试,常用的做法如图 1 所示。==
其中在这段代码中,if name == “main”: 是一个常见的 Python 编程惯用语法,用于判断当前模块是否作为独立的主程序执行,而不是作为模块被导入到其他模块中。如果当前模块作为独立的主程序执行,则会执行 if 语句块中的代码。
Python assert实现软件测试
下面看一个简单的例子,假定自定义了一个模块 sampleAssert,其代码如下:

def int_list_sort(input_list):input_list.sort()
if __name__ == ""__mian__":def test_normal_positive_input():input_list = [3, 5, 9, 1, 8]int_list_sort(input_list)assert input_list == [1, 3, 5, 8, 9]print("test_normal_positive_input: PASS")test_normal_positive_input()

如果是直接运行该脚本,则测试用例就会被触发。

(venv) chen@deMacBook-Air pythonProject % python test.py test_normal_positive_input: PASS

如果我们是 import(引入)该模块,case 是不会执行的,即第 3 行开始的块是不会执行的,所以包含在该块内的测试用例定义不会被看到,测试用例也不会被执行。

>>> import test                          # 引入模块
>>> test.test_normal_positive_input()    # 执行测试函数
Traceback (most recent call last):       # 测试函数不可见File "<stdin>", line 1, in <module>
AttributeError: module 'test' has no attribute 'test_normal_positive_input' 

但是被测函数是可见的

>>> input_list = [3, 5, 9, 1, 8]
>>> test.int_list_sort(input_list)
>>> input_list
[1, 3, 5, 8, 9]

== 2. 不在源代码中进行测试,在单独的文件中写测试用例代码==

被测代码
Python assert实现软件测试

def bubble_sort(input_list):          # 被测对象,完成对输入的整数列表排序if type(input_list) is not type([]):print("Invalid Input!")return Nonefor x in input_list:if type(x) != int:print("Invalid Input!")return Noneinput_len = len(input_list)if len(input_list) <= 1:return input_listfor i in range(input_len-1):for j in range(input_len-i-1):if input_list[j] > input_list[j+1]:input_list[j], input_list[j+1] = input_list[j+1], input_list[j]return input_list

测试用例
在功能测试中,测试代码的长度比被测代码的长度还要长,这是软件测试中,尤其是功能测试部分常见的现象。另外一个现象是对于针对特殊使用场景的测试用例数量比较大。多数情况下,问题不会隐藏在常用的使用场景,而多隐藏在这些不常见的使用场景中,所以针对这些特殊使用场景的测试用例的设计需要多下功夫。

import randomfrom Test import bubble_sort# 输入的列表为空
def test_empty_input():input_list = []output = bubble_sort(input_list)assert type(output) == type([])assert len(output) == 0, "输入为空的列表,输出也是空"# 输入的不是列表
def test_invalid_input():input_list = 1output = bubble_sort(input_list)assert output is Nonedef test_invalid_element():input_list = ['name']output = bubble_sort(input_list)assert output is None# 输入的列表数只有一个
def test_one_input():input_list = [1]output = bubble_sort(input_list)assert output == input_listassert len(output) == 1print("4.test_one_input: PASS")# 输入的列表数为两个
def test_two_input():input_list = [8, 1]output = bubble_sort(input_list)assert output == [1, 8]assert len(output) == 2print("5.test_two_input: PASS")# 列表包含非整数的元素
def test_invalid_elements():input_list = [8, 1, 'name']output = bubble_sort(input_list)assert output is None# 正常输入
def test_normal_pos():input = [88, 1, 20, 8, 9, 21, 98, 76]output = bubble_sort(input)expected_output = [1, 8, 9, 20, 21, 76, 88, 98]assert output == expected_outputprint("7.test_normal_pos: PASS")# 输入重复的数字
def test_dup_elements():input = [88, 1, 20, 8, 9, 21, 98, 8, 76]        # 两个8output = bubble_sort(input)expected_output = [1, 8, 8, 9, 20, 21, 76, 88, 98]assert output == expected_outputprint("8.test_dup_elements: PASS")# 输入都是相同的数字
def test_all_same():input = [8, 8, 8, 8, 8, 8, 8]output = bubble_sort(input)expected_output = [8, 8, 8, 8, 8, 8, 8]assert output == expected_outputprint("9.test_all_same: PASS")# 随机生成测试数据
def test_random_input():length = random.randint(10, 100)random_list = []for i in range(length):random_list.append(random.randint(-100, 100))org_list = random_listprint(org_list)output_list = bubble_sort(random_list)print((output_list))assert len(output_list) == len(org_list), '排序前后元素数量相等'for j in range(length):val = output_list[j]assert val in org_list, '元素应该和原有列表中的一样'assert output_list.count(val) == org_list.count(val), '每个元素出现的次数应该和原有列表相等'for j in range(length-1):assert output_list[j] <= output_list[j+1], '从小到大排序'print("10.test_random_input: PASS")# 随机进行100轮测试
def test_random_100():for i in range(100):test_random_input()print("11.test_random_100: PASS")
test_empty_input()
test_invalid_input()
test_invalid_element()
test_invalid_elements()
test_one_input()
test_two_input()
test_normal_pos()
test_dup_elements()
test_all_same()
test_random_input()
test_random_100()