前言
前面介紹了,可以使用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進行做對比使用,具體哪個好用,大家可以進行使用那個,如果有更好的使用方法,可以下方留言進行交流哦
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/271853.html
標籤:其他
