Skip to content

pytest 数据驱动怎么做

面试题目

  • 级别: L3
  • 知识模块: pytest/自动化测试

pytest数据驱动怎么做

公司

  • 字节外包

招聘类型

社招

题目解析

面试官考察:

  1. 数据驱动的理解程度。
  2. pytest数据驱动的实现方法。

解题思路:

  1. 数据驱动定义:数据驱动是一种测试技术,它可以将测试用例与测试数据分离,使测试用例具有更高的可复用性和可维护性。数据驱动的基本思想是将测试用例与测试数据分离,通过参数化的方式运行测试用例,从而减少代码冗余,提高测试效率。数据量小的测试用例可以使用代码的参数化来实现数据驱动,数据量大的情况下建议大家使用一种结构化的文件(例如 yamljson, 等)来对数据进行存储,然后在测试用例中读取这些数据。

  2. Pytest数据驱动就是通过参数化的方式运行测试用例。Pytest提供了两种数据驱动的方式:

    1. 使用@pytest.mark.parametrize():通过此装饰器为测试函数提供多组输入数据和期望输出,例如@pytest.mark.parametrize("input, expected", [(1, 2), (2, 4)]),从而以数据驱动的方式运行测试。
import pytest
from math import sqrt

@pytest.mark.parametrize("x", [0, 1, 2, 3])
def test_sqrt(x):
    assert sqrt(x) == x**0.5
  1. 使用`pytest.fixture`结合`params`:定义fixture时,利用`params`参数传入多组数据,然后在测试函数中通过fixture获取数据,实现数据驱动。
import pytest

# 定义Fixture
@pytest.fixture(params=[
    (1, 2),
    (2, 4),
    (3, 6),
    (4, 8)
])
def input_output(request):
    return request.param

# 测试函数
def test_multiplication(input_output):
    input_value, expected_result = input_output
    result = input_value * 2
    assert result == expected_result

答案

pytest完成数据驱动有两种方式使用@pytest.mark.parametrize()pytest.fixture结合params来实现数据驱动。