目的:
1. 统一管理接口关联的中间变量
2. 解决多个py文件中间的中间变量关联的问题
新建一个yaml_util.py进行封装读写清空yaml方法
# 读取
def read_yaml(key): with open("extract.yaml",encoding="utf-8") as f: #这里的文件如果没有会自动创建value = yaml.safe_load(f)return value[key] # 注意这里一定要传入key,因为同一个yaml文件会写入很多个key,如果不指定会全部读取到
# 写入
def writer_yaml(data):with open("extract.yaml",encoding="utf-8",mode="a+") as f: # 这里一定要使用追加的方式写入,不然会将之前的写入的清空掉yaml.safe_dump(data,stream=f,allow_unicode=True)
# 清空
def clean_yaml():with open("extract.yaml",encoding="utf-8",mode="w") as f:pass
测试用例py文件使用方法,并将需要的参数写入到指定yaml文件中
class TestApi:def test_phpwind(self):url = 'http://aaa/phpwind/'res = RequestUtil().send_request(method="get",url=url)# 通过yaml的方式存储token,这样即使跨文件也可以使用res_token = re.search('name="csrf_token" value="(.*?)"', res.text)data = {"csrf_token":res_token.group(1)} # 注意这里应该是键值对的形式写入的,注意yaml的格式writer_yaml(data) # 将内容写入到指定yaml文件中def test_phpwind_login(self):print(read_yaml("csrf_token"))url = 'http://aaa/phpwind/index.php?m=u&c=login&a=dorun'header = {"Accept":"application/json, text/javascript, /; q=0.01","X-Requested-With":"XMLHttpRequest"}data = {"username":"aaa","password":"aaa","csrf_token":read_yaml("csrf_token"), # 根据指定key读取需要的参数"backurl":"http://aaa/phpwind/","invite":""}res = RequestUtil().send_request(method="post",url=url, data=data, headers=header)print(res.json())
此时就完成了通过yaml进行读写的能力,但是由于每次调用用例都会写入,因而需要清空历史的写入的数据,保证使用的是最新且唯一的数据,因而就需要使用conftest.py进行,注意这里fixture的作用域是整个session
@pytest.fixture(scope="session",autouse=True)
def clean_extract():# 在用例执行前清空历史yaml数据clean_yaml()# 在用例执行之后清空历史yaml数据,不建议使用,不利于排查问题# yield# clean_yaml()