40-pytest-Hook函数之参数化生成用例
Posted 爱学习de测试小白
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了40-pytest-Hook函数之参数化生成用例相关的知识,希望对你有一定的参考价值。
Hook函数之参数化生成用例
前言
- 本篇来学习pytest中使用Hook函数–pytest_generate_tests实现参数化
pytest_generate_tests
- 在 conftest.py 自定义参数化的钩子, 判断当测试用例传了 param 参数,就让它生成参数化的用例
conftest.py
# -*- coding: utf-8 -*-
# @Time : 2021/10/14
# @Author : 大海
# conftest.py
def pytest_generate_tests(metafunc):
""" generate (multiple) parametrized calls to a test function."""
if "param" in metafunc.fixturenames:
metafunc.parametrize("param",
metafunc.module.test_data,
ids=metafunc.module.names,
scope="function")
编写case
# -*-coding:utf-8一*-
# @Time:2022/10/14
# @Author: 大海
# test_71.py
import os
import requests
# 用例的id名称
names = ["get 1", "get 2"]
# 测试数据 list of dict
test_data = [
"url": "https://postman-echo.com/get",
"method": "GET",
"headers":
"Content-Type": "application/json"
,
"json":
"username": "test1",
"password": "123456"
,
"url": "https://postman-echo.com/get",
"method": "GET",
"headers":
"Content-Type": "application/json"
,
"json":
"username": "test2",
"password": "123456"
]
def test_get_request(param):
"""测试get请求"""
r = requests.session().request(**param)
print('\\nrsp', r.text)
user_name = r.json().get('args').get('username')
print('user_name', user_name)
assert 'test' in user_name
if __name__ == '__main__':
os.system('pytest -s -v test_71.py')
- 查看运行结果
以上是关于40-pytest-Hook函数之参数化生成用例的主要内容,如果未能解决你的问题,请参考以下文章
pytest文档69-Hook函数之参数化生成测试用例pytest_generate_tests
pytest-17-fixture之autouse=True