pytest---fixture參數化


前言  

  前面介紹了,可以使用parametrize來做參數化,非常的方便,其實fixture也可以用來做參數化,靈活性更高。

fixture參數化

fixture前面介紹的時候說過一共有5個參數分別是:name,scope,params,autouse,ids。每個參數都會介紹到,今天主要介紹params參數,這個參數主要用來做fixture的參數化內容。

這里需要用到一個參數request,用來接收fixture返回的結果。通過request.param來返回參數內容。

import pytest

data = ['anjing', 'test', 'admin']


@pytest.fixture(params=data)
def login(request):
    print('登錄功能')
    yield request.param
    print('退出登錄')


class Test_01:
    def test_01(self, login):
        print('---用例01---')
        print('登錄的用戶名:%s' % login)

    def test_02(self):
        print('---用例02---')



if __name__ == '__main__':
    pytest.main(['-vs'])

 

通過執行結果可以發現fixture完成了參數化內容,有的小伙伴們可能會問了,如果是多個參數怎么用呢?這里安靜在通過登陸案例在來介紹下多個參數

fixture傳入多個參數

這里我們需要了解到通過fixture傳參,是通過 request.param 進行整體接受到,如果參數多的話,需要request.param進行單獨取出。

import pytest

data = [{'user': "anjing",
         'pwd': "123456",},
        {'user': "admin",
         "pwd": "123"},
        {'user':"test",
         'pwd': '1234'}]


@pytest.fixture(params=data)
def login(request):
    print('登錄功能')
    yield request.param
    print('退出登錄')

class Test_01:
    def test_01(self, login):
        print('---用例01---')
        print('登錄的用戶名:%s' % login['user'])
        print('登錄的密碼:%s' % login['pwd'])

    def test_02(self):
        print('---用例02---')


if __name__ == '__main__':
    pytest.main(['-vs'])

 

安靜這里就是通過把整體參數全部傳出,然后通過request.param作為整體返回,返回的值就是通過login這個函數,然后通過login函數在進行取值,當然也可以在前置工作中進行直接取出來,然后傳出時,直接調用

自定義參數信息

fixture的參數化自定義信息和parametrize是一樣支持自定義信息的,都是通過ids參數來表示的。

import pytest

data = [{'user': "anjing",
         'pwd': "123456",},
        {'user': "admin",
         "pwd": "123"},
        {'user':"test",
         'pwd': '1234'}]


@pytest.fixture(params=data, ids=['This is anjing','This is admin', 'This is test'])
def login(request):
    print('登錄功能')
    yield request.param
    print('退出登錄')



class Test_01:
    def test_01(self, login):
        print('---用例01---')
        print('登錄的用戶名:%s' % login['user'])
        print('登錄的密碼:%s' % login['pwd'])

    def test_02(self):
        print('---用例02---')


if __name__ == '__main__':
    pytest.main(['-vs'])

 

通過return返回參數

上面介紹的是通過正常的request進行傳參,也可以通過return直接進行返回參數,這里返回參數只能用來單個參數,不能使用參數化,只是簡單介紹fixture的這個功能

import pytest

@pytest.fixture()
def login():
    print('完成登錄')
    a = {'user': "anjing",
         'pwd': "123456",}
    return a

class Test_01:
    def test_01(self, login):
        print('---用例01---')
        print(login)
        
    def test_02(self):
        print('---用例02---')


if __name__ == '__main__':
    pytest.main(['-vs'])

 

簡單的介紹了fixture的參數化內容,大家可以和parametrize進行做對比使用,具體哪個好用,大家可以進行使用那個。如果有更好的使用方法,可以下方留言進行交流哦

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM