4

软件测试/测试开发全日制|Pyest结合json实现数据驱动测试

 8 months ago
source link: https://blog.51cto.com/u_15640304/9202235
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

软件测试/测试开发全日制|Pyest结合json实现数据驱动测试

精选 原创

霍格沃兹测试 2024-01-11 18:22:01 ©著作权

文章标签 JSON 数据驱动 测试用例 文章分类 软件测试 阅读数256

软件测试/测试开发全日制|Pyest结合json实现数据驱动测试_测试用例

数据驱动测试是提高代码覆盖率和可靠性的重要方法。结合pytest和JSON(JavaScript对象表示)文件可以轻松实现数据驱动测试。和CSV文件类似,Python读取json文件也不需要借助其他的第三方库,因此我们不需要进行额外的环境安装。下面是如何使用pytest和JSON文件进行数据驱动测试的步骤。

创建测试文件和JSON文件

假设我们有一个简单的函数需要测试,比如对两个数进行求和:

# code.py

def add(a, b):
    return a + b

接下来,创建一个JSON文件,用于存储测试数据:

[
  {
    "test_case": "Case 1",
    "operand_a": 2,
    "operand_b": 3,
    "expected_result": 5
  },
  {
    "test_case": "Case 2",
    "operand_a": -1,
    "operand_b": 10,
    "expected_result": 9
  },
  {
    "test_case": "Case 3",
    "operand_a": 0,
    "operand_b": 0,
    "expected_result": 0
  }
]

编写测试用例

创建一个pytest测试文件,编写测试用例并读取JSON文件中的数据:

# test_code.py

import json
import pytest
from code import add

def load_test_data():
    with open('test_data.json', 'r') as file:
        test_data = json.load(file)
    return test_data

@pytest.mark.parametrize("data", load_test_data())
def test_add(data):
    operand_a = data['operand_a']
    operand_b = data['operand_b']
    expected_result = data['expected_result']

    result = add(operand_a, operand_b)
    assert result == expected_result, f"{operand_a} + {operand_b} 应该得到 {expected_result},实际得到 {result}"

现在,运行pytest命令来执行测试:

pytest test_code.py

pytest将会读取test_code.py文件中的测试用例,并根据JSON文件中提供的数据对add函数进行测试。每个测试用例都会使用JSON文件中的数据进行数据驱动测试。

结合pytest和JSON文件,我们成功实现了数据驱动测试,对同一个函数在不同输入下进行了多组测试。这种方法使得测试用例易于管理和维护,同时能够更全面地覆盖不同的测试场景,确保代码的稳定性和正确性。数据驱动测试的优势在于能够快速扩展测试数据,提高测试的覆盖率和可靠性。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK