@pytest.fixture函数怎么传变量参数
1、使用 params 参数进行参数化
import pytest
@pytest.fixture(params=[1, 2, 3])
def number_fixture(request):
return request.param
def test_with_params(number_fixture):
print(f"Testing with number: {number_fixture}")
2、使用 indirect 参数传递复杂参数
import pytest
@pytest.fixture
def complex_data(request):
return request.param
@pytest.mark.parametrize(‘complex_data’, [
{‘name’: ‘Alice’, ‘age’: 25},
{‘name’: ‘Bob’, ‘age’: 30}
], indirect=True)
def test_complex_data(complex_data):
print(f"Name: {complex_data[‘name’]}, Age: {complex_data[‘age’]}")
- fixture 之间传递参数
import pytest
@pytest.fixture
def complex_data(request):
return request.param
@pytest.mark.parametrize(‘complex_data’, [
{‘name’: ‘Alice’, ‘age’: 25},
{‘name’: ‘Bob’, ‘age’: 30}
], indirect=True)
def test_complex_data(complex_data):
print(f"Name: {complex_data[‘name’]}, Age: {complex_data[‘age’]}")
- 使用 request 对象获取参数
import pytest
@pytest.fixture
def complex_data(request):
return request.param
@pytest.mark.parametrize(‘complex_data’, [
{‘name’: ‘Alice’, ‘age’: 25},
{‘name’: ‘Bob’, ‘age’: 30}
], indirect=True)
def test_complex_data(complex_data):
print(f"Name: {complex_data[‘name’]}, Age: {complex_data[‘age’]}")
