In-depth analysis of YAML configuration files: from syntax to best practices

 

1. Understanding YAML

  • YAML (YAML Ain't Markup Language) is a human-readable data serialization language. Its design goal is to make it easy to exchange and share data between different programming languages. YAML employs a concise, intuitive syntax for representing data structures in a way that is easy to read and write.
  • YAML is widely used in configuration files, data serialization, API design, and many other areas. It is supported by many programming languages ​​and frameworks, including Python, Java, Ruby, etc. In Python, the PyYAML library can be used to read and write YAML files.
  • The advantages of YAML include high readability, easy understanding, compatibility with multiple programming languages, and support for rich data structures. Its concise syntax makes configuration files more intuitive and maintainable. Whether as a configuration file format or a data exchange format, YAML is a powerful and popular choice.

2. YAML syntax specification

Syntactic features of YAML include:

  1. Use indentation to indicate hierarchical relationships, and do not use curly braces or other symbols.
  2. Use colons to denote key-value pairs.
  3. List and nested structures are supported.
  4. Use comments starting with "#".
  5. Support references and anchors, you can refer to other parts of the data in the document.

YAML (YAML Ain't Markup Language) supports a variety of data types, including strings, numbers, booleans, lists, dictionaries, and null values. The following are sample codes and corresponding syntax specifications for each data type:

1. String

  • Grammar specification: use single quotes or double quotes to enclose the string. String quotes can also be omitted
name: "John"
addr: "长沙"

2. Numbers

  • Grammar specification: Just write the number directly.
age: 30

3. Boolean value

  • Grammar specification: use true to represent true, use false to represent false.
isStudent: true
isTeacher: false

4. List

  • Grammar specification: Use a dash (-) to represent list items, and use newlines to separate list items.
fruits:
    - apple
    - banana
    - orange

5. Dictionary

  • Grammar specification: Use a colon (:) to represent key-value pairs, and use spaces to separate key-value pairs.
person:
    name: "John"
    age: 30

6. Null value

  • Grammar specification: use null to represent an empty value.
status: null
  • These are the common data types supported by YAML and the corresponding sample code. You can use these data types to build complex data structures as needed.
  • Note : YAML is very sensitive to indentation, and spaces are used for indentation to indicate hierarchical relationships. The number of spaces for indentation can be 2 or 4, but must be consistent throughout the document.

Three, python operation YAML

  • Python provides the pyyaml ​​library to operate YAML files. Before operating yaml files, the pyyaml ​​library must be installed.
  • Run the following command in Terminal (Pycharm-Terminal) or Command Prompt (cmd) to install the pyyaml ​​library: pip install pyyaml

1. Python reads the yaml file

  • Step 1: The yaml file prepared in advance, the yaml file suffix is ​​.yaml or .yml
name: "John"
addr: "长沙"
age: 18
status: null
isStudent: true
fruits:
    - apple
    - banana
    - orange
teacher:
    name: "Alex"
    age: 30
  • Step 2: Use python to read the data in yaml
import yaml

with open(file="d.yaml", mode="r",encoding='utf-8') as f:
    res = yaml.safe_load(f)
print(res)
  • yaml.safe_load() method: read the data in the YAML file. The yaml.safe_load() method parameter is a file object
  • Running result: the data in yaml will be automatically converted to the data type supported by python

 

2.python writes data to yaml file

  • The first step: write the variable value specified by python into the yaml file
import yaml

data = {
    "Person": {
        "name": "John",
        "age": 30,
        "address": {
            "street": "123 Main St",
            "city": "Anytown",
            "state": "CA"
        }
    }
}
# 将data变量存储的数据写入YAML文件
with open(file="example.yaml", mode="w") as f:
    yaml.dump(data, f)
  • yaml.dump() method: write the data into the yaml file. The first parameter of the yaml.dump() method is to write the data, and the second parameter is the file object.
  • Step 2: View the display in example.yaml

 

4. YAML combined with UI automation to realize KDT

  • KDT (Keyword-Driven Testing): English abbreviation for keyword-driven testing.
  1. yaml data preparation
# 访问页面
- action: goto
  params:
    url: 'https://www.baidu.com'
# 输入python
- action: sendkeys
  params:
    locator: ['id','kw']
    value: 'python'
# 点击搜索按钮
- action: click
  params:
    locator: ['id','su']
# 断言
- action: assert_text_contains
  params:
    locator: ['id','content_left']
    excepted: 'python'
  1. Basepage method encapsulation
from selenium.webdriver import Chrome,ActionChains

class BasePage:
    def __init__(self,driver:Chrome):
        self.driver = driver

    def goto(self,url):
        '''打开网址'''
        self.driver.get(url)

    def click(self,locator):
        '''点击操作'''
        el = self.driver.find_element(*locator)
        try:
            el.click()
        except:
            ActionChains(self.driver).click(el).perform()

    def sendkeys(self,value,locator=None):
        '''发送文本操作'''
        if locator:
            # 相当于ActionChains中的send_keys_to_element(ele,value),先做点击,再做文本输入
            el = self.driver.find_element(*locator)
            el.send_keys(value)
        else:
            ActionChains(self.driver).send_keys(value).perform()

    def assert_text_contains(self,locator,excepted):
        '''断言文本是否包含指定的内容'''
        el = self.driver.find_element(*locator)
        assert excepted in el.text
  1. Test case writing --- implement keyword-driven testing
import time
import yaml
from selenium import webdriver
from basepage import BasePage

# 1、读取yaml文件中的数据
with open(file='test_keyword.yaml',mode='r',encoding='utf-8') as f:
    data = yaml.safe_load(f)

# 2、测试用例编写
def test_01():
    # 初始化浏览器操作
    driver = webdriver.Chrome()
    driver.implicitly_wait(10)
    driver.maximize_window()
    # 实例化BasePage的对象
    basepage = BasePage(driver)
    # 遍历读取到的data数据
    for step in data:
        # 获取动作名称
        method_name = step['action']
        # 获取参数
        params = step['params']
        # 获取类中方法名
        method = getattr(basepage, method_name)
        # 调用方法,输入参数
        method(**params)  # 字典解包
    time.sleep(2)
    driver.quit()

Guess you like

Origin blog.csdn.net/a448335587/article/details/131794971