pytest參數化的兩種方式

一、傳統方式

 1 import requests,pytest  2 from Learning.variable import *
 3 
 4 # 定義變量
 5 #url = "https://www.baidu.com"
 6 
 7 class TestClass(object):  8     global url    #在此獲取全局變量,並將其設置爲TestClass類的全局變量
 9     def setup_class(self): 10         print("start...") 11 
12     def test_get(self): 13         #global url #在此獲取全局變量,並將其設置爲test_get方法內的全局變量
14         res = requests.get(url=url) 15         assert res.status_code == 200
16 
17 
18 if __name__ == '__main__': 19     pytest.main()

二、pytest推薦模式,即conftest測試數據共享

2.一、在function中使用

# content of test01.py

import pytest,requests #將conftest中的com_variable方法傳入用例中,不須要導入便可使用 def test_getBaidu(com_variable): a=requests.get(com_variable['url']) code = a.status_code assert code == 200
def test_paas(): pass
# content of conftest.py
import pytest iaas={ 'url':'https://www.baidu.com', } @pytest.fixture(scope="module") def com_variable(): return iaas

 2.二、在class中使用

conftest不變,直接在class中的方法入參中傳入便可測試

import requests,pytest from Learning.variable import *

# 定義變量 #url = "https://www.baidu.com"

class TestClass(object): #global url #在此獲取全局變量,並將其設置爲TestClass類的全局變量
    def setup_class(self): print("start...") #直接在此傳入便可
    def test_get(self,com_variable): #global url #在此獲取全局變量,並將其設置爲test_get方法內的全局變量
        res = requests.get(url=com_variable['url']) assert res.status_code == 200


if __name__ == '__main__': pytest.main()

 

推薦第二種方式!

相關文章
相關標籤/搜索