python封装工具类之excel读写

在python自动化过程中,如果测试用例数据在excel中,就需要去对excel进行读写操作

这个测试类主要是读取excel中的测试用例,然后再将测试结果回写到excel中。

excel表格格式示例(cases.xlsx):

case_id case_name method url data expected actual result
1 用户正常登录 post /login {"usename":"zhangsan", "pwd": 123456} success success pass
2 密码错误登录 post /login {"usename":"zhangsan", "pwd": 123} unsuccess unsuccess pass

 

 

 

 

 

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

# 1. 某些操作中, 会改变的内容把它抽离出来 使用python中openpyxl模块进行封装
from openpyxl import load_workbook


class HandleExcel:
    """
    定义处理excel的类
    """
    def __init__(self, filename, sheetname=None):
        self.filename = filename
        self.sheetname = sheetname

    def get_cases(self):
        """
        获取所有的测试用例
        :return:
        """
        wb = load_workbook(self.filename)
        if self.sheetname is None:
            ws = wb.active
        else:
            ws = wb[self.sheetname]
        # 获取excel表头信息
        head_data_tuple = tuple(ws.iter_rows(max_row=1, values_only=True))[0]
        one_list = []
        # 将从第二行开始,每一条用例和表头相对应,组成嵌套字典的列表
        for one_tuple in tuple(ws.iter_rows(min_row=2, values_only=True)):
            one_list.append(dict(zip(head_data_tuple, one_tuple)))

        return one_list

    def get_case(self, row):
        """
        获取指定某一行的用例
        :param row: 行号
        :return:
        """
        return self.get_cases()[row-1]
    
    def write_result(self, row, actual, result):
        """
        在指定的行写入数据
        :param row: 行号
        :param actual: 实际结果
        :param result: 用例执行的结果(Pass或者Fail)
        :return:
        """
        # 同一个Workbook对象, 如果将数据写入到多个表单中, 那么只有最后一个表单能写入成功
        other_wb = load_workbook(self.filename)
        if self.sheetname is None:
            other_ws = other_wb.active
        else:
            other_ws = other_wb[self.sheetname]
        if isinstance(row, int) and (2 <= row <= other_ws.max_row):
            other_ws.cell(row=row,
                          column=do_config.get_int("excel", "actual_col"),
                          value=actual)
            other_ws.cell(row=row,
                          column=do_config.get_int("excel", "result_col"),
                          value=result)
            other_wb.save(self.filename)
            other_wb.close()
        else:
            print("传入的行号有误, 行号应为大于1的整数")


if __name__ == '__main__':
    filename = "cases.xlsx"
    do_excel = HandleExcel(filename)
    cases = do_excel.get_cases()
    do_excel.write_result(2, "pass", "pass")
    pass

 

posted @ 2024-04-17 12:27  幸运球与倒霉蛋  阅读(39)  评论(0编辑  收藏  举报