pytest之fixture:有返回值(return)的前置操作


前言:

我们知道,在实际测试工作中,往往需要前置操作返回某些值来供测试方法或测试函数使用。如测试函数或测试方法
执行操作的前提条件是登录状态,即需要token值。pytest中,对于有返回值的前置操作是怎样处理呢?
其实,fixture中对于前置操作或后置操作,使用方式都是一样的。

一、有返回值的fixture:
来看示例:

文件:conftest.py

@pytest.fixture()
def login(): print("this is login ") return "我是login的返回值"
文件:test_a.pu

import
pytest def test_1(login): assert 3 == 3 print("this is test_1") print(login) def test_2(): assert 4 == 4 print("this is test_2") class TestA(object): def test_a(self, login): assert 1 == 1 print("this is test_a") print(login) def test_a_1(self): assert 2 == 2 print("this is test_a_1")

示例中:conftest.py中的前置函数login()有返回值:“我是login的返回值”。在test_a.py中,测试函数test_1和测试方法test_a传入了该前置操作函数名。
我们来看一下执行效果:

test_a.py::test_1 this is login 
PASSED                                                 [ 25%]this is test_1
我是login的返回值

test_a.py::test_2 PASSED                                                 [ 50%]this is test_2

test_a.py::TestA::test_a this is login 
PASSED                                          [ 75%]this is test_a
我是login的返回值

我们惊奇的发现:前置函数login的返回值在测试用例中被打印了。
结论:当fixture前置函数有返回值时,传入前置函数名时,可以通过函数名来拿到返回值。

重点、重点、重点:对于@pytest.mark.usefixtures()的方式时无法拿到前置函数的返回值的。

二、fixture返回值:
上例中,我们知道前置函数名可以拿到返回值(例子中是一个字符串),如果是其他数据类型呢?
其实,道理都是一样的,比如是字典,那函数名就是一个字典,通过字典的键就可以拿到对应的值了。
见示例:

import pytest


@pytest.fixture()
def login():
    print("this is login ")
    dict_r = {"name": "tom", "age": 18}
    return dict_r

conftest.py中,login返回了一个{"name": "tom", "age": 18}字典。

import pytest


def test_1(login):
    assert 3 == 3
    print("this is test_1")
    print(login["name"])


def test_2():
    assert 4 == 4
    print("this is test_2")


class TestA(object):
    def test_a(self, login):
        assert 1 == 1
        print("this is test_a")
        print(login["age"])

    def test_a_1(self):
        assert 2 == 2
        print("this is test_a_1")

测试模块中,通过login["name"]和login["age"]拿对应的值:
执行结果如下:

 

 

总结:
1,通过@pytest.mark.usefixtures()无法拿到返回值,而直接传入前置函数名可以拿到返回值。
2,前置函数返回值,通过前置函数名即可拿到,返回什么类型,函数名就是什么类型(可以这样理解)。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM