美文网首页
python3+selenium实现Web自动化7:unitte

python3+selenium实现Web自动化7:unitte

作者: C1R2 | 来源:发表于2021-03-17 22:36 被阅读0次

1.目录结构图

image

2.目录详解

下图是框架中各个目录和文件作用的简单介绍,后面的章节会具体介绍如何封装这些方法。

image

公共方法封装

一、getPathInfo.py

# _*_ coding:utf-8 _*_

import os

def get_Path():
    """
    返回上级目录的绝对路径
    """
    return os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

def join_cwd(path):
    """
    和上级目录拼接路径
    """
    return os.path.join(get_Path(), path)

if __name__ == '__main__':
    print(join_cwd('Logs'))                                 #测试一下

二、log.py
日志系统:记录执行用例过程中的log。

# _*_ coding:utf-8 _*_
import logging, os, time
from Common import getPathInfo
from logging.handlers import TimedRotatingFileHandler

now = time.strftime("%Y%m%d%H%M%S")  # 当前时间变量

# 日志系统:记录执行用例过程中的log。
class Logger(object):
    def __init__(self):
        self.resultPath = getPathInfo.join_cwd('Logs')  # 存放log文件的路径
        if not os.path.exists(self.resultPath):  # 判断Logs路径是否存在
            os.mkdir(self.resultPath)  # 创建Logs文件
        self.logger = logging.getLogger()
        logging.root.setLevel(logging.NOTSET)
        self.backup_count = 5  # 最多存放日志的数量

        # 日志输出级别
        self.console_output_level = 'WARNING'
        # self.file_output_level = 'DEBUG'
        self.file_output_level = 'INFO'

        # 日志输出格式
        self.formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

    def get_logger(self, logfile_name=now):
        """在logger中添加日志句柄并返回,如果logger已有句柄,则直接返回"""
        if not self.logger.handlers:  # 避免重复日志
            console_handler = logging.StreamHandler()
            console_handler.setFormatter(self.formatter)
            console_handler.setLevel(self.console_output_level)
            self.logger.addHandler(console_handler)
            # 每天重新创建一个日志文件,最多保留backup_count份
            file_handler = TimedRotatingFileHandler(filename=os.path.join(self.resultPath, logfile_name + '.log'),
                                                    when='D',
                                                    interval=1, backupCount=self.backup_count, delay=True,
                                                    encoding='utf-8')
            file_handler.setFormatter(self.formatter)
            file_handler.setLevel(self.file_output_level)
            self.logger.addHandler(file_handler)
        return self.logger


logger = Logger().get_logger()  # 实例化

三、readConfig.py
读取Config配置文件的方法。

# _*_ coding:utf-8 _*_
import configparser
from Common import getPathInfo


# 读取Config配置文件的方法
class Read_Config(object):
    """
    读取配置文件信息
    """

    def __init__(self):
        config_path = getPathInfo.join_cwd('config.ini')        # 拼接路径
        self.config = configparser.ConfigParser()               # 调用配置文件方法
        # self.config.read(config_path)                         # 读取配置文件
        self.config.read(config_path, encoding='utf-8')         # illegal multibyte sequence,报错后加了encoding='utf-8',问题解决

    def get_info(self, group_name, key):
        """
        读取配置文件config中指定组的键值
        :param group_name:组名
        :param key: key值
        """
        return self.config.get(group_name, key)


if __name__ == '__main__':
    print(Read_Config().get_info('HTTP', 'baseurl'))  # 测试一下,读取配置文件的方法是否可用


四、readExcel.py
本次采用的是数据与代码相分离模式,测试数据保存在Excel文件中,readExcel.py就是封装的读取测试数据方法。

# _*_ coding:utf-8 _*_
from Public import getPathInfo
import xlrd, os


# 采用的是数据与代码相分离模式,测试数据保存在Excel文件中,readExcel.py就是封装的读取测试数据方法.
class readExcel(object):
    def __init__(self, xlsx_name):
        path = getPathInfo.get_Path()  # 获得上级目录路径
        self.xlsPath = os.path.join(path, 'TestData', xlsx_name)  # 获取用例文件路径
        self.file = xlrd.open_workbook(self.xlsPath)  # 打开用例Excel

    def get_sheetnames(self):
        """
        返回所有sheet名称
        """
        return self.file.sheet_names()

    def get_xlsx(self, sheet):
        """
        获取Excel中测试用例相关信息
        """
        list = []  # 定义一个空列表
        sheet = self.file.sheet_by_name(sheet)  # 获得指定sheet数据
        row_value1 = sheet.row_values(0)  # 获取第1行的标题

        nrows = sheet.nrows  # 获取当前sheet行数
        ncols = sheet.ncols  # 获取当前sheet列数
        for i in range(1, nrows):  # 从第2行遍历当前sheet
            row = sheet.row_values(i)  # 获取行数据
            dict = {}  # 创建空字典
            for j in range(0, ncols):  # 遍历sheet列,组成字典
                if row_value1[j] == 'NO.' or row_value1[j] == 'code':
                    dict[row_value1[j]] = int(row[j])  # NO和code值取int
                else:
                    dict[row_value1[j]] = row[j]  # 从第一列开始,将每一列的数据与第1行的数据组成一个键值对,形成字典
            list.append(dict)  # 将字典添加list中
        return list  # 返回列表


if __name__ == '__main__':  # 测试一下方法是否可用
    x = readExcel('UI_TestCase.xlsx')
    print(x.get_sheetnames())
    print(x.get_xlsx('login'))


参考链接:
https://www.cnblogs.com/airb/p/13490266.html

相关文章

网友评论

      本文标题:python3+selenium实现Web自动化7:unitte

      本文链接:https://www.haomeiwen.com/subject/mzircltx.html