51Testing软件测试论坛

 找回密码
 (注-册)加入51Testing

QQ登录

只需一步,快速开始

微信登录,快人一步

查看: 1130|回复: 2
打印 上一主题 下一主题

[转贴] Python 读取配置文件常用的几种方式

[复制链接]
  • TA的每日心情
    无聊
    前天 09:06
  • 签到天数: 941 天

    连续签到: 3 天

    [LV.10]测试总司令

    跳转到指定楼层
    1#
    发表于 2022-3-14 11:22:41 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
    引言
      我们在设计自动化测试框架的时候,经常使用到配置文件,而配置文件种类有很多,常见的配置文件格式有很多中:ini、yaml、xml、properties、txt、py等。
      配置文件ini
      虽然配置文件放置一些公共的内容,比如说环境、路径、参数等。但也可以放测试数据,比如说接口一些信息,但不建议这样做。
      下面看python读取配置文件ini的实例:
      1、新建配置文件ini,符号:;是注释。
    1. ;测试配置文件
    2.   [api]
    3.   url = "www."
    4.   method = get
    5.   header =
    6.   data =
    7.   resp_code = 200
    8.   resp_json = {}
    复制代码
    2、创建读取ini的py文件,最好与ini配置文件同一层级目录:

    1. from configparser import ConfigParser
    2.   import os
    3.   class ReadConfigFile(object):
    4.       def read_config(self):
    5.           conn = ConfigParser()
    6.           file_path = os.path.join(os.path.abspath('.'),'config_test.ini')
    7.           if not os.path.exists(file_path):
    8.               raise FileNotFoundError("文件不存在")
    9.           conn.read(file_path)
    10.           url = conn.get('api','url')
    11.           method = conn.get('api','method')
    12.           header = conn.get('api','header')
    13.           data = conn.get('api','data')
    14.           resp_code = conn.get('api','resp_code')
    15.           resp_json = conn.get('api','resp_code')
    16.           return [url,method,header,data,resp_code,resp_json]
    17.   rc = ReadConfigFile()
    18.   print(rc.read_config())
    复制代码
    运行结果:


     配置文件yaml
      上面已经介绍配置文件ini读取方法,现在讲yaml文件读取。
      yaml [ j m l]: Yet Another Markup Language :另一种标记语言。yaml 是专门用来写配置文件的语言。
      1、yaml文件规则
      1)区分大小写;
      2)使用缩进表示层级关系;
      3)使用空格键缩进,而非Tab键缩进;
      4)缩进的空格数目不固定,只需要相同层级的元素左侧对齐;
      5)文件中的字符串不需要使用引号标注,但若字符串包含有特殊字符则需用引号标注;
      6)注释标识为#。
      2、yaml文件数据结构
      1)对象:键值对的集合(简称 "映射或字典")。
      键值对用冒号 “:” 结构表示,冒号与值之间需用空格分隔。
      2)数组:一组按序排列的值(简称 "序列或列表")。
      数组前加有 “-” 符号,符号与值之间需用空格分隔。
      3)纯量(scalars):单个的、不可再分的值(如:字符串、bool值、整数、浮点数、时间、日期、null等)。
      None值可用null可 ~ 表示。

      yaml文件基本数据类型
     # 纯量
      s_val: name              # 字符串:{'s_val': 'name'}
      spec_s_val: "name\n"    # 特殊字符串:{'spec_s_val': 'name\n'
      num_val: 31.14          # 数字:{'num_val': 31.14}
      bol_val: true           # 布尔值:{'bol_val': True}
      nul_val: null           # null值:{'nul_val': None}
      nul_val1: ~             # null值:{'nul_val1': None}
      time_val: 2018-03-01t11:33:22.55-06:00     # 时间值:{'time_val': datetime.datetime(2018, 3, 1, 17, 33, 22, 550000)}
      date_val: 2019-01-10    # 日期值:{'date_val': datetime.date(2019, 1, 10)}

     简单读取:
      前提条件:python中读取yaml文件前需要安装pyyaml和导入yaml模块。
    1. import yaml
    2.   doc = """
    3.   ---
    4.   "data":
    5.    "id":
    6.      -
    7.        123
    8.   ---
    9.   "data":
    10.    "name":
    11.      -
    12.        "测试"
    13.    "age": 2
    14.      
    15.   """
    16.   doc2 = """
    17.   ---
    18.   "data":
    19.    "id":
    20.      -
    21.        123
    22.   """
    23.   # 方法1
    24.   data = yaml.load(doc2,Loader=yaml.FullLoader)
    25.   print(type(data))
    26.   print(data)
    27.   get_dict = []
    28.   # 迭代器
    29.   data2 = yaml.load_all(doc,Loader=yaml.FullLoader)
    30.   for i in data2:
    31.       print(i)
    32.       get_dict.append(i)
    33.   print(get_dict[1]['data']['age'] == 2)
    复制代码
    运行结果:




    这里有个问题点:Loader=yaml.FullLoader,解释如下:
    1. """
    2.   1.
    3.   yaml.load(f, Loader=yaml.FullLoader)
    4.   2.
    5.   yaml.warnings({'YAMLLoadWarning': False})  # 全局设置警告,不推荐
    6.   Loader的几种加载方式
    7.   BaseLoader - -仅加载最基本的YAML
    8.   SafeLoader - -安全地加载YAML语言的子集。建议用于加载不受信任的输入。
    9.   FullLoader - -加载完整的YAML语言。避免任意代码执行。这是当前(PyYAML5.1)默认加载器调用
    10.   yaml.load(input)(发出警告后)。
    11.   UnsafeLoader - -(也称为Loader向后兼容性)原始的Loader代码,可以通过不受信任的数据输入轻松利用。
    12.   """
    复制代码
    读取单个yaml文档
      这里使用python的open方法打开文件,使用yaml的load方法可以将单个yaml文档中数据转化成字典或列表。
      新建配置文件test_config02:
    1.  ---
    2.   data:
    3.     id: 1
    4.     name: {
    5.            age: 2}
    6.     other:
    7.       -
    8.         height: 3
    复制代码
    新建读取配置文件py:
    1.  # 单个文档
    2.   import yaml
    3.   import os
    4.   def get_yaml_data(yaml_file):
    5.       # 打开yaml文件
    6.       print("***获取yaml文件数据***")
    7.       file = open(yaml_file, 'r', encoding="utf-8")
    8.       file_data = file.read()
    9.       file.close()
    10.       print(file_data)
    11.       print("类型:", type(file_data))
    12.       # 将字符串转化为字典或列表
    13.       print("***转化yaml数据为字典或列表***")
    14.       data = yaml.load(file_data,Loader=yaml.FullLoader)
    15.       print(data)
    16.       print("类型:", type(data))
    17.       return data
    18.   current_path = os.path.abspath(".")
    19.   yaml_path = os.path.join(current_path, "test_config02")
    20.   get_yaml_data(yaml_path)
    复制代码
     运行结果:

    读取多个yaml文档
      多个文档在一个yaml文件,使用 --- 分隔方式来分段。新建一个yaml配置文件test_config:
    1.  ---
    2.   data:
    3.     id: 1
    4.     name: {
    5.            age: 2}
    6.     other:
    7.       -
    8.         height: 3
    9.   ---
    10.   id: 2
    11.   name: "测试用例2"
    复制代码
    编写读写yaml函数:
    1.  import yaml
    2.   import os
    3.   def get_yaml_load_all(filename):
    4.       with open(filename,'r') as fp:
    5.           file_data = fp.read()
    6.           fp.close()
    7.           print("类型: ",type(file_data))
    8.           all_data = yaml.load_all(file_data,Loader=yaml.FullLoader)
    9.           print("类型: ",type(all_data))
    10.           for data in all_data:
    11.               print(data)
    12.   current_path = os.path.abspath('.')
    13.   file_path = os.path.join(current_path,'test_config')
    14.   print(file_path)
    15.   get_yaml_load_all(file_path)
    复制代码
     运行结果:

     配置文件xml
      python读取xml文件可能自动化测试平时用的少,这里介绍一下:
      这个xml文件内容如下:
    1. <collection shelf="New Arrivals">
    2.   <movie title="Enemy Behind">
    3.      <type>War, Thriller</type>
    4.      <format>DVD</format>
    5.      <year>2003</year>
    6.      <rating>PG</rating>
    7.      <stars>10</stars>
    8.      <description>Talk about a US-Japan war</description>
    9.   </movie>
    10.   <movie title="Transformers">
    11.      <type>Anime, Science Fiction</type>
    12.      <format>DVD</format>
    13.      <year>1989</year>
    14.      <rating>R</rating>
    15.      <stars>8</stars>
    16.      <description>A schientific fiction</description>
    17.   </movie>
    18.      <movie title="Trigun">
    19.      <type>Anime, Action</type>
    20.      <format>DVD</format>
    21.      <episodes>4</episodes>
    22.      <rating>PG</rating>
    23.      <stars>10</stars>
    24.      <description>Vash the Stampede!</description>
    25.   </movie>
    26.   <movie title="Ishtar">
    27.      <type>Comedy</type>
    28.      <format>VHS</format>
    29.      <rating>PG</rating>
    30.      <stars>2</stars>
    31.      <description>Viewable boredom</description>
    32.   </movie>
    33.   </collection>
    复制代码
    读取代码:
    1.  # coding=utf-8
    2.   import xml.dom.minidom
    3.   from xml.dom.minidom import parse
    4.   DOMTree = parse('config')
    5.   collection = DOMTree.documentElement
    6.   if collection.hasAttribute("shelf"):
    7.       print("Root element : %s" % collection.getAttribute("shelf"))
    8.   # 在集合中获取所有电影
    9.   movies = collection.getElementsByTagName("movie")
    10.   # 打印每部电影的详细信息
    11.   for movie in movies:
    12.       print("*****Movie*****")
    13.       if movie.hasAttribute("title"):
    14.           print("Title: %s" % movie.getAttribute("title"))
    15.       type = movie.getElementsByTagName('type')[0]
    16.       print("Type: %s" % type.childNodes[0].data)
    17.       format = movie.getElementsByTagName('format')[0]
    18.       print("Format: %s" % format.childNodes[0].data)
    19.       rating = movie.getElementsByTagName('rating')[0]
    20.       print("Rating: %s" % rating.childNodes[0].data)
    21.       description = movie.getElementsByTagName('description')[0]
    22.       print("Description: %s" % description.childNodes[0].data)
    复制代码
    运行结果:





    本帖子中包含更多资源

    您需要 登录 才可以下载或查看,没有帐号?(注-册)加入51Testing

    x
    分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
    收藏收藏
    回复

    使用道具 举报

    本版积分规则

    关闭

    站长推荐上一条 /1 下一条

    小黑屋|手机版|Archiver|51Testing软件测试网 ( 沪ICP备05003035号 关于我们

    GMT+8, 2024-5-2 18:36 , Processed in 0.071978 second(s), 23 queries .

    Powered by Discuz! X3.2

    © 2001-2024 Comsenz Inc.

    快速回复 返回顶部 返回列表