本文转自测试人社区,原文链接:https://ceshiren.com/t/topic/31954

二、项目要求

2.1 项目简介

计算器是一个经典的编程场景,可以获取两个数据的计算结果。

2.1.1 知识点

  • Pytest 测试框架基本用法

2.1.2 受众

  • 初级测试工程师

2.1.3 作业内容

  • 使用 Pytest 编写自动化测试用例对相加函数进行测试
  • 在调用每个测试函数之前打印【开始计算】
  • 在调用测试函数之后打印【结束计算】
  • 调用完所有的测试用例最终输出【结束测试】
  • 使用参数化实现测试数据的动态传递

2.1.4 被测源码

def is_match_condition(a):
    '''
    判断输入参数是否满足条件
    :param a: 输入参数
    :return: 满足条件返回 "符合条件",否则返回对应场景提示信息
    '''
    # 判断 a 的类型
    if not (isinstance(a, int) or isinstance(a, float)):
        return "参数为非数字"
    # 判断 a 的范围
    if a > 99 or a < -99:
        return "参数大小超出范围"
    return "符合条件"

def add(a, b):
    '''
    相加方法
    :param a: 加数
    :param b: 被加数
    :return: a + b 的结果,或者提示信息
    '''
    # 判断 a 参数类型与范围符合条件
    if is_match_condition(a) == "符合条件":
        # 判断 b 参数类型与范围符合条件
        if is_match_condition(b) == "符合条件":
            return a + b
        # b 不符合条件,返回提示信息
        else:
            return f"b{is_match_condition(b)}"
    # a 不符合条件,返回提示信息
    else:
        return f"a{is_match_condition(a)}"

2.2 实现过程

新建test_calculator.py文件,调用被测源码的calculator.py

import pytest
from calculator import add

@pytest.fixture(autouse=True)
def start_end_add():
    print("=====开始计算=====")
    yield
    print("=====结束计算=====")

def end_test():
    print("=========结束测试=========")

@pytest.mark.parametrize(
    "a, b, expected",
    [
        (50, 30, 80),                # 正常情况
        (-100, 50, "a参数大小超出范围"),  # a 超出范围
        (50, 100, "b参数大小超出范围"),   # b 超出范围
        (23.55, 55.13, 78.68),          # 浮点数情况
        ("50", 30, "a参数为非数字"),     # a 不是数字
        (50, "thirty", "b参数为非数字"), # b 不是数字
        (0, 0, 0),                   # 边界情况,零值相加
        (-99, 99, 0),                # 边界情况,负数与正数相加
    ]
)

def test_add(a, b, expected):
    result = add(a, b)
    assert result == expected

2.3 实现效果

软件测试学习笔记丨Pytest+Allure测试计算器_参数类型

软件测试学习笔记丨Pytest+Allure测试计算器_提示信息_02