从零开始学习pytest和selenium框架03.配置文件的使用

一、前言

什么是配置文件?

配置文件就是把一些固定的数据,比如数据库账户、测试地址,统一放在一个文件里面进行管理。

常见的配置文件有INI格式和YAML格式的配置文件,今天我们先说INI配置文件的使用。

二、创建配置文件

(a)在项目中创建config目录

(b)在config目录下面创建config.ini文件

 

 (c)在配置文件中输入你的内容

关于INI配置文件的语法格式(by百度百科)

在config.ini文件中是这样: 

三、读写配置文件

 配置文件创建完成了我们是不是该读取配置文件了。下面我们读取它。

3.1创建common目录

在项目根目录下创建common目录。这个里面是要放至python模块的,但是目前他还是一个普通目录,所以我们需要添加__init__.py文件把他变成python包。

3.2创建readconfig模块

在common目录下创建readconfig.py模块。

3.3配置文件读写的实现

#!/usr/bin/env python
# coding=utf-8
'''
@File    :   readconfig.py
@Time    :   2019/09/30 14:11:32
@Author  :   wxhou
@Version :   1.0
'''
import sys
sys.path.append('.')
import os
import configparser

root_dir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))

HOST = 'server'
HOST_NAME = 'url'


class Config:
    def __init__(self):
        self.config_path = os.path.join(root_dir, 'config', 'config.ini')
        if not os.path.exists(self.config_path):
            raise FileNotFoundError("配置文件不存在")
        self.config = configparser.RawConfigParser()
        self.config.read(self.config_path, encoding='utf-8')

    def get_config(self, *args):
        """获取"""
        return self.config.get(*args)

    def set_config(self, *args):
        """修改"""
        self.config.set(*args)

    @property
    def host(self):
        """测试地址"""
        return self.get_config(HOST, HOST_NAME)

    @host.setter
    def host(self, value):
        self.set_config(HOST, HOST_NAME, value)
        with open(self.config_path, 'w', encoding='utf-8') as f:
            self.config.write(f)


conf = Config()

if __name__ == "__main__":
    print(conf.host)
    conf.host = 'http://www.baidu.com'
    print(conf.host)

就这样一个简单的读取和写入配置文件模块就完成了。

本节就到此结束了。

喜欢python自动化测试或正在学习自动化测试的同学,欢迎加入我的QQ群一起学习 : 299524235 (python自动化测试学习)

猜你喜欢

转载自www.cnblogs.com/wxhou/p/11611559.html
今日推荐