6

软件测试/测试开发全日制|Pytest结合CSV实现测试的数据驱动

 8 months ago
source link: https://blog.51cto.com/u_15640304/9202214
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

软件测试/测试开发全日制|Pytest结合CSV实现测试的数据驱动

精选 原创

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

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

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

数据驱动测试是一种有效的测试方法,可以使用不同的输入数据运行相同的测试用例。结合pytest和CSV文件可以方便地实现数据驱动测试,相比于yaml以及Excel,使用CSV实现数据驱动不需要借助其他的第三方库,可以直接使用Python读取数据。在这篇文章中,我们将介绍如何使用pytest和CSV实现数据驱动测试。

创建测试文件和CSV文件

假设我们要测试一个简单的函数,比如计算两个数的乘积:

# code.py

def multiply(a, b):
    return a * b

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

operand_a,operand_b,expected_result
2,3,6
-1,5,-5
0,10,0
0.5,2,1
0.5,0.5,0.25

编写测试用例

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

# test_code.py

import csv
import pytest
from code import multiply

def load_test_data():
    test_data = []
    with open('test_data.csv', newline='') as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            test_data.append(row)
    return test_data

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

    result = multiply(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文件中的测试用例,并根据CSV文件中提供的数据对multiply函数进行测试。每个测试用例都会使用CSV文件中的数据进行数据驱动测试。

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

  • 收藏
  • 评论
  • 分享
  • 举报

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK