遇一山,过一山,处处有风景;只要勇敢向前,一路尽是繁花盛开。 | (点击查看→)【测试干货】python/java自动化、持续集成、性能、测开、简历、笔试面试等

pytest简易教程(09):fixture返回值(实现参数化)

 

pytest简易教程汇总,详见https://www.cnblogs.com/uncleyong/p/17982846

特点

1. fixture可以通过设计params,让依赖该fixture的用例迭代执行

2. params数据可以为[列表],(元组),{集合},{字典}

3. params数据在fixture中通过request变量来接收

 

示例:fixture返回值

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : 韧
# @wx :ren168632201
# @Blog :https://www.cnblogs.com/uncleyong/

import pytest

@pytest.fixture
def fun():
    return 666

class TestX:
    def test_case(self, fun):
        print("---test_case")
        print(f"data={fun}")

  

结果:

 

如果fixture有返回值,用@pytest.mark.usefixtures()报错,无法获取到返回值

@pytest.mark.usefixtures(fun)
class TestX:
    def test_case(self):
        print("---test_case")
        print(f"data={fun}")

  

结果:

 

示例:fixture返回params中的值

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : 韧
# @wx :ren168632201
# @Blog :https://www.cnblogs.com/uncleyong/

import pytest

@pytest.fixture(params=['韧','全栈测试笔记','性能测试','自动化测试','测试开发'])
def fun(request):  # 必须是request这个参数名
    return request.param  # 依次取列表中的每个值返回

class TestX:
    def test_case(self, fun):
        print(f"---test_case,data={fun}")

  

结果:

 

示例:也可以yield返回

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : 韧
# @wx :ren168632201
# @Blog :https://www.cnblogs.com/uncleyong/

import pytest


@pytest.fixture(params=['韧', '全栈测试笔记', '性能测试', '自动化测试', '测试开发'])
def fun(request):  # 必须是request这个参数名
    print("---前置")
    yield request.param  # 依次取列表中的每个值返回
    print("---后置")

class TestX:
    def test_case(self, fun):
        print(f"---test_case,data={fun}")

  

结果:

 

笛卡尔积

应用场景:需要传多个参数的不同组合,比如注册接口

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author : 韧
# @wx :ren168632201
# @Blog :https://www.cnblogs.com/uncleyong/

import pytest

data=['韧','全栈测试笔记','性能测试']
data2=[1,2,3]
@pytest.fixture(params=data)
def fun(request):  # 必须是request这个参数名
    return request.param  # 依次取列表中的每个值返回

@pytest.fixture(params=data2)
def fun2(request):
    return request.param

class TestX:
    def test_case(self, fun, fun2):
        print(f"---test_case,data={fun},{fun2}")

 

结果:

 

posted @ 2024-02-23 21:11  全栈测试笔记  阅读(244)  评论(0编辑  收藏  举报
浏览器标题切换
浏览器标题切换end