一般情況下,我們是通過一個(gè)yaml文件進(jìn)行關(guān)聯(lián)實(shí)現(xiàn)
在根目錄下新建一個(gè)文件yaml,通過上述conftest.py文件實(shí)現(xiàn)全局變量的更新:
1.首先需要建立一個(gè)讀取、寫入、清除yaml文件的工具類
如下:
import os
import yaml
class YamlUnit:
def readAllYaml(self):
with open(os.getcwd() + "/extract.yml", mode='r', encoding='utf-8') as f:
value = yaml.load(stream=f, Loader=yaml.FullLoader)
return value
def readKeyYaml(self,key):
with open(os.getcwd() + "/extract.yml", mode='r', encoding='utf-8') as f:
value = yaml.load(stream=f, Loader=yaml.FullLoader)
return value[key]
def writeYaml(self, data):
with open(os.getcwd() + "/extract.yml", mode='w', encoding='utf-8') as f:
print(os.getcwd() + "/extract.yml")
value = yaml.dump(data=data, stream=f, allow_unicode=True)
def deleteYaml(self):
with open(os.getcwd()+"/extract.yml",mode="w",encoding='utf-8') as f:
f.truncate()
2.配合conftest.py文件+ fixture實(shí)現(xiàn)全局共享調(diào)用
# 實(shí)現(xiàn)部分前置
import pytest
from comment.yaml_unit import YamlUnit
@pytest.fixture(scope="function")
def conn_getbase():
print("連接數(shù)據(jù)庫成功")
yield
print("關(guān)閉數(shù)據(jù)庫成功")
@pytest.fixture(scope="session", autouse=True)
def clear_yaml():
YamlUnit().deleteYaml()
@pytest.fixture(scope="session", autouse=True)
def get_token():
token = ''; # 獲取token的代碼請求
return token
3.調(diào)用時(shí)只需傳入方法函數(shù)名稱即可
如:下面函數(shù)使用之前需要連接數(shù)據(jù)庫用踩,只需傳入conftest.py文件里面的conn_getbase函數(shù)名即可
def test_Login(self,conn_getbase):
# post請求
url = "xxxxxxx"
# 參數(shù)
data = {
"captcha": "Gkak!@#2019",
"checkKey": 1637811815838,
"password": "123456",
"remember_me": 1,
"username": "admin"
}
rep = requests.request('post', url, json=data)
statues = rep.json()["success"]
message = rep.json()["message"]
if statues:
print(message )
else:
raise Exception(message)