键值对使用冒号结构表示 key: value,冒号后面要加一个空格。
# 对象(object)格式
request:
method: post
url: https://127.0.0.1:8080/api/login
headers:
Content - type: application/json
datas:
username: test
password: test123456
validate: none
以 - 开头的行表示构成一个数组
# 数组(array)
companies:
-
id: 1
name: company1
price: 200W
-
id: 2
name: company2
price: 500W
纯量是最基本的,不可再分的值,包括:字符串、布尔值、整数、浮点数、Null、日期、时间
# 字符串:
string:
- 你好
- 'hello word' # 可以用双引号或者单引号包裹特殊字符
- newline
- newline2
# 布尔值
boolean:
- TRUE
- FALSE
# 整数
int:
- 123456
# 浮点数
float:
- 3.14159
- 23.325
# Null#(使用~表示null)
params: ~
# 日期(日期必须使用ISO 8601格式,即yyyy-MM-dd)
- 2022-07-08
# 时间 (时间使用ISO8601格式,时间和日期之间使用T连接,最后使用+代表时区)
- 2022-07-08T10:06:31+08:00
安装 yaml 模块:
pip install pyyaml
导包:
import yaml
具体方法:
yaml.load(f) 作用是将yaml文档转化为python对象
yaml.load_all(f) 返回yaml文件中所有的yaml文档的对象生成一个迭代器,再使用for打印出来
yaml.dump(c,f) 将一个python对象生成yaml文档,存放再f中
yaml.dump_all(c,f) 将多个python对象生成yaml文档,存放在f中
yaml文件小demo:data.yaml
#创建data.yml
-
name: 张飞
age: 15
score:
- English: 90
- Chinese: 92
- Math: 95
-
name: 孙策
age: 19
score:
- English: 85
- Chinese: 98
- Math: 69
import yaml
class yamlUtil(object):
def __init__(self, yaml_file):
'''
通过init把文件传入到这个类中
:param yaml_file
'''
self.yaml_file = yaml_file
def read_yaml(self):
'''
读取yaml,将yaml反序列化,就是把yaml格式转换为dict格式
'''
with open(self.yaml_file, encoding="utf-8") as f:
value = yaml.load(stream=f, Loader=yaml.FullLoader) # 文件流,加载方式
print(value)
return value
if __name__ == '__main__':
yamlUtil(r"D:\ApiTest3\PyYaml_cases\data.yaml").read_yaml()
Import_yaml.py
import pytest
import os
from PyYaml_cases import test_yaml
class Test_yaml(object):
file = os.getcwd() + "./data.yaml"
print(file)
@pytest.mark.parametrize("args", test_yaml.yamlUtil(os.getcwd() + './data.yaml').read_yaml())
def test_yaml(self, args):
print(args)
name = args['name']
age = args['age']
print(name)
print(age)
输出:
============================= test session starts =============================
collecting ... collected 2 items
Import_yaml.py::Test_yaml::test_yaml[args0] PASSED [ 50%]{'name': '张飞', 'age': 15, 'score': [{'English': 90}, {'Chinese': 92}, {'Math': 95}]}
张飞
15
Import_yaml.py::Test_yaml::test_yaml[args1] PASSED [100%]{'name': '孙策', 'age': 19, 'score': [{'English': 85}, {'Chinese': 98}, {'Math': 69}]}
孙策
19
============================== 2 passed in 0.08s ==============================
Process finished with exit code 0