Pytest计划_day18(读取ini材料)

读取ini文件

  • 安装configparser

ini的格式如下

  • []内为key值
  • 另起一行为value值,可以用字典嵌套
  • 配置文件不需要加引号
[host]
api_sit_url = http://sellshop.5istudy.online/sell/shouji/query

read_ini()方法

  • 主要作用是获取ini文件
  • 写法比较固定,如下:
import configparser
import os
path = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))),"config", "settings.ini")
def read_ini():
config = configparser.ConfigParser()
config.read(path, encoding="utf8")
return config
  • 可以在测试用例中直接使用
    在这里插入图片描述

合并 read_ini() 和 read_data() 方法

  • 这两个方法都是读取操作,可以合并到一个文件中
  • 如果一个文件中有两个方法都返回数据,那么可以将它们放到一个类中,代码如下:
import configparser
import os
import yaml
ini_path = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "config", "settings.ini")
data_path = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "data", "data.yaml")
class FileRead:
def __init__(self):
self.ini_path = ini_path
self.data_path = data_path
def read_ini(self):
config = configparser.ConfigParser()
config.read(self.ini_path, encoding="utf8")
return config
def read_data(self):
f = open(self.data_path, encoding="utf8")
data = yaml.safe_load(f)
return data
# 此处直接实例化,方便调用
get_data = FileRead()
  • 测试用例中可以做相应修改
    在这里插入图片描述
posted @ 2025-08-22 14:06  yjbjingcha  阅读(4)  评论(0)    收藏  举报