本文共 2403 字,大约阅读时间需要 8 分钟。
Pytest的参数化功能可以帮助测试用例以多种方式运行,提高效率和覆盖率。最简单的方式是使用装饰器@pytest.mark.parametrize。例如,定义一个测试函数test_add,用来测试两个数的和是否正确:
def test_add(a, b, expected): assert add(a, b) == expected
为了运行这个测试函数,我们可以添加以下参数化装饰器:
@pytest.mark.parametrize("a, b, expected", [ (2, 3, 5), (-1, 1, 0), (0, 0, 0), (100, -100, 0)]) 这样,Pytest会自动运行四次测试,每次使用不同的参数组合来测试函数。
Pytest提供了多种参数化方式,根据需求选择合适的方式:
参数值列表
最简单的方式是将多组参数值放在一个列表中,直接传递给装饰器。适用于参数较少且每个参数值独立的情况。参数名称列表
有时我们希望将参数值列表和参数名称列表分开定义,以更清晰地表达参数的含义。例如,测试字符串是否包含子串:@pytest.mark.parametrize("s, sub, expected", [ ("hello world", "hello", True), ("hello world", "world", True), ("hello world", "python", False)])def test_contains(s, sub, expected): assert (sub in s) == expected @pytest.mark.parametrize("s1", ["hello", "world"])@pytest.mark.parametrize("s2", ["python", "pytest"])def test_concat(s1, s2): assert concat(s1, s2) == s1 + s2 @pytest.mark.parametrize("n", range(10))def test_is_prime(n): assert is_prime(n) == (n in [2, 3, 5, 7]) @pytest.fixture(scope="module")def data(): with open("test_data.csv") as f: reader = csv.reader(f) return list(reader)@pytest.mark.parametrize("n, s", data())def test_func(n, s): assert func(n, s) == ... Pytest参数化还提供了更多高级功能:
ids参数动态指定参数名称。例如,测试字符串连接后的长度:@pytest.mark.parametrize("s1, s2, expected", [ ("hello", "world", 10), ("pytest", "is awesome", 15)], ids=["case1", "case2"])def test_len(s1, s2, expected): assert len(concat(s1, s2)) == expected product函数将多个参数值列表组合起来。例如,测试两个整数相乘:@pytest.mark.parametrize("a", [1, 2, 3])@pytest.mark.parametrize("b", [4, 5, 6])def test_mul(a, b): assert mul(a, b) == a * b@pytest.mark.parametrize("a, b", product([1, 2, 3], [4, 5, 6]))def test_mul2(a, b): assert mul(a, b) == a * b @pytest.fixture(scope="module")def config(): with open("test_config.yaml") as f: return yaml.safe_load(f)@pytest.fixture(scope="module")def params(config): return [(s, n) for s in config["strings"] for n in config["numbers"]]def test_func(params): for s, n in params: assert func(s, n) == ... Pytest参数化提供了强大的功能,适用于各种测试场景。从简单的参数值列表到复杂的动态生成参数名称和组合,Pytest的参数化功能可以满足不同需求。通过合理使用这些功能,开发者可以编写更高效、可靠的测试用例。
转载地址:http://qjafk.baihongyu.com/