pytest + yaml 框架 -21.int类型和数字类型的str相互转换

前言

在 yaml 文件中定义变量的时候,如果是纯数字的值,默认是数字类型,加上引号可以变成字符串类型。
对于取值结果,我们还可以使用python 内置的函数去转换

环境要求
Python 大于等于3.8版本,(低于python3.8版本不支持)
Pytest 大于等于 7.2.0

pip 安装插件, 最新版本v1.1.8,此功能在v1.1.8版本上实现

pip install pytest-yaml-yoyo

yaml 中定义int 和 str

config 中 先声明2个变量, test_api.yml内容

# 作者 上海-悠悠 微信:283340479

config:
  variables:
    user: 123456
    key: "223344"


test_post:
  name: 注册用户
  request:
    method: post
    url: http://httpbin.org/post
    json:
      username: ${user}
      password: ${key}

运行结果查看日志,可以看到引用成功

demo/test_api.yml::test_post
---------------------------------------------------- live log call -----------------------------------------------------
2023-03-17 19:58:41 [INFO]: 执行文件-> test_api.yml
2023-03-17 19:58:41 [INFO]: base_url-> None
2023-03-17 19:58:41 [INFO]: variables-> {'user': 123456, 'key': '223344'}
2023-03-17 19:58:41 [INFO]: 运行用例-> test_post
2023-03-17 19:58:41 [INFO]: 取值表达式 user
2023-03-17 19:58:41 [INFO]: 取值结果:123456, <class 'int'>
2023-03-17 19:58:41 [INFO]: 取值表达式 key
2023-03-17 19:58:41 [INFO]: 取值结果:223344, <class 'str'>
2023-03-17 19:58:41 [INFO]: --------  request info ----------
post http://httpbin.org/post
{'method': 'post', 'url': 'http://httpbin.org/post', 'json': {'username': 123456, 'password': '223344'}}

int 转 str 类型

在yaml 中,可以使用内置函数对取值的结果转换数据类型

# 作者 上海-悠悠 微信:283340479

config:
  variables:
    user: 123456
    key: "223344"


test_post:
  name: 注册用户
  request:
    method: post
    url: http://httpbin.org/post
    json:
      username: ${str(user)}
      password: ${key}

运行后查看日志结果

demo/test_api.yml::test_post
---------------------------------------------------- live log call -----------------------------------------------------
2023-03-17 20:01:14 [INFO]: 执行文件-> test_api.yml
2023-03-17 20:01:14 [INFO]: base_url-> None
2023-03-17 20:01:14 [INFO]: variables-> {'user': 123456, 'key': '223344'}
2023-03-17 20:01:15 [INFO]: 运行用例-> test_post
2023-03-17 20:01:15 [INFO]: 取值表达式 str(user)
2023-03-17 20:01:15 [INFO]: 取值结果:123456, <class 'str'>
2023-03-17 20:01:15 [INFO]: 取值表达式 key
2023-03-17 20:01:15 [INFO]: 取值结果:223344, <class 'str'>
2023-03-17 20:01:15 [INFO]: --------  request info ----------
post http://httpbin.org/post
{'method': 'post', 'url': 'http://httpbin.org/post', 'json': {'username': '123456', 'password': '223344'}}

从运行结果看到已经转换成功,同样也可以使用str函数对int类型转成字符串类型。
网易云完整视频课程https://study.163.com/course/courseMain.htm?courseId=1213419817&share=2&shareId=480000002230338
报名咨询wx:283340479 (已报名的同学学习过程中有问题,都可以协助解决)

posted @ 2023-03-17 20:06  上海-悠悠  阅读(375)  评论(0编辑  收藏  举报