yaml_util.py文件
import os
import yaml
class YamlUtil:
# 读取extract.yml文件
def read_extract_yaml(self, key):
with open(os.getcwd()+"/extract.yml", mode='r', encoding='utf-8') as f:
# 读取f文件流 读取方式FullLoader,然后复制给value
value = yaml.load(stream=f, Loader=yaml.FullLoader)
return value[key]
# 写入extract.yml文件
def write_extract_yaml(self, data):
with open(os.getcwd()+"/extract.yml", mode='a', encoding='utf-8') as f:
# 写入的数据从data传入
yaml.dump(data, stream=f, allow_unicode=True)
# 清空extract_yaml文件(将这个方法放入到前置后置文件中(conftest.py),每次运行用例 他就会自动清空yaml文件内容,无需调佣,自动执行=True)
def clear_extract_yaml(self):
# 打开yaml文件
with open(os.getcwd()+'/extract.yml', mode='w', encoding='utf-8') as f:
# 清空yaml文件
f.truncate()
conftest.py文件
import pytest
from common.yaml_util import YamlUtil
@pytest.fixture(scope='function')
def conn_database():
print('链接数据库')
yield
print('关闭数据库')
# 作用域session 自动执行=True,在所有的接口请求之前执行
@pytest.fixture(scope='session', autouse=True)
def clear_yaml():
YamlUtil().clear_extract_yaml()
test_login.py文件
import pytest
import requests
from common.yaml_util import YamlUtil
class TestLoginRequest:
# @staticmethod
# def setup(self):
# print('在每个用例之前执行一次')
# @staticmethod
# def teardown(self):
# print('在每个用例之后执行一次')
# @pytest.mark.smoke
def test_login(self):
# 定义登录接口URL
login_url = "登录地址"
# 构造POST请求参数
payload = {
'account': '账号',
'password': '密码'
}
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'clientAppId': '1241916430255710209'
}
try:
# 发送POST请求并获取返回结果
response = requests.request('post', login_url, data=payload, headers=headers)
status_code = response.json()['code']
print(status_code)
if status_code == 200:
print("登录成功!")
extract_value = {
'login_token': response.json()['data']['token']['token'],
'login_Authorization': response.json()['data']['token']['principal']
}
print(extract_value)
YamlUtil().write_extract_yaml(extract_value)
else:
print("登录失败!错误信息:", response.text)
return False
except Exception as e:
print("登录过程中出现异常:", str(e))
def test_update_file(self):
# 上传文件
login_token = YamlUtil().read_extract_yaml('login_token')
login_Authorization = YamlUtil().read_extract_yaml('login_Authorization')
url_update_file = 'https://corp.lesoft.com.cn/lsapi/userauth/account/upLoadProfilePhoto'
data = {
'files': open(r'D:\PythonTest\Python_picture\飞云02.jpg', 'rb')
}
headers = {
'Authorization': login_Authorization,
'Token': login_token
}
response = requests.request('post', url=url_update_file, files=data, headers=headers)
print(response.json())
if __name__ == '__main__':
# TestLoginRequest().test_login()
pytest.main(['-vs'])
extract.yaml
login_Authorization: xxxxxx
login_token: 8DE8CA63FB96FC3A8280