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