pytest參數化的兩種方式


1、傳統方式

 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()

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

2.1、在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.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()

 

推薦第二種方式!

 


免責聲明!

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



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