【分享】pytest fixture中 params参数运用

fixture中的params参数运用

官方参数解释

   :param params:
        An optional list of parameters which will cause multiple invocations
        of the fixture function and all of the tests using it. The current
        parameter is available in ``request.param``.

params 参数:一个可选的参数列表,它将导致多次调用fixture函数和使用它的所有测试,获取当前参数可以使用request.param,request 是pytest的内置 fixture ,主要用于传递参数

实际运用场景一:获取账号和密码

import pytest

data = [("user1", "pwd1"), ("user2", "pwd2")]
@pytest.fixture(scope="function", params=data)
def get_data(request):
    print(request.param)
    return request.param

def test_login(get_data):
    user,pwd=get_data
    print(f"账号:{user},密码:{pwd}")

实际运用场景二:注册后清理用户

import pytest

def del_user(user):
    #这里写删除用户的操作
    print(f"删除用户{user}")

mobiledata = ["13200001111", "13200001112"]# 测试数据

@pytest.fixture(scope="function", params=mobiledata)
def users(request):
    #这里写注册用户的操作
    yield request.param
    del_user(request.param) #这里写删除用户的操作

def test_register(users):
    print("注册用户:%s" % users)

实际运用场景三:不同浏览器上运行同一个测试用例

import pytest
from selenium import webdriver

@pytest.fixture
def chrome():
    driver = webdriver.Chrome()
    yield driver
    driver.quit()

@pytest.fixture
def firefox():
    driver = webdriver.Firefox()
    yield driver
    driver.quit()

@pytest.fixture(params=['chrome', 'firefox'])
def driver(request):
    return request.getfixturevalue(request.param)

def test_case1(driver):
    driver.get("https://ceshiren.com/")

运行结果
image

实际运用场景四:动态取值

import uuid
import  pytest

def getuuid():
    def _uuid():
        return str(uuid.uuid4())
    return _uuid

@pytest.fixture(scope="function", params=[getuuid()])
def rndparam(request):
    p = request.param
    return p()

def test_1(rndparam):
   print("test_params1:"+rndparam)

def test_2(rndparam):
   print("test_params2:"+rndparam)

两条用例获取到不同的uuid值
image
待续