Document

Python+Selenium+unittest数据驱动

重写unittest

import unittest

class ParametrizedTestCase(unittest.TestCase):
    """ TestCase classes that want to be parametrized should
        inherit from this class.
    """
    def __init__(self, methodName='runTest', param=None):
        super(ParametrizedTestCase, self).__init__(methodName)
        self.param = param
    @staticmethod
    def parametrize(testcase_klass, param=None):
        """ Create a suite containing all tests taken from the given
            subclass, passing them the parameter 'param'.
        """
        testloader = unittest.TestLoader()
        testnames = testloader.getTestCaseNames(testcase_klass)
        suite = unittest.TestSuite()
        for name in testnames:
            suite.addTest(testcase_klass(name, param=param))
        return suite

xlrd读取Excel数据

import xlrd

class Common():
    def excel_data(self,excelPath, sheetName):
        '''获取测试数据
            参数:excelPath Excel文件路径
            参数:sheetName Excel文件中Sheet名称
            返回当前Sheet的全部数据'''
        data = xlrd.open_workbook(excelPath)  # 根据路径,找到excel文件
        table = data.sheet_by_name(sheetName)  # 打开excel文件中的哪一个sheet
        keys = table.row_values(0)  # 获取第一行作为key
        rowNum = table.nrows  # 获取总行数,从1开始数
        colNum = table.ncols  # 获取总列数,从1开始数
        if rowNum <= 1:
            print("数据文件:{0} Sheet名称:{1} 数据异常".format(excelPath, sheetName))
        else:
            r = []
            j = 1
            # 提取每一行的值
            for i in range(rowNum - 1):
                s = {}
                # 从第二行取对应的values值
                values = table.row_values(j)
                for x in range(colNum):
                    s[keys[x]] = values[x]
                r.append(s)
                j += 1
            return r

测试脚本

from src.test.common.common import Common
from src.test.common.common import ParametrizedTestCase
import unittest


class Test(ParametrizedTestCase):

    def test_login(self):
        data = self.param
        print("执行用例:{0}".format(data))

if __name__ == '__main__':
    suite = unittest.TestSuite()
    allData = Common().excel_data("E:\PycharmProjects\WebTest\data\case\login.xlsx","login")
    for data in allData:
        suite.addTest(ParametrizedTestCase.parametrize(Test,param=data))
    unittest.TextTestRunner(verbosity=2).run(suite)

输出:
=======================================================================================
E:\PycharmProjects\WebTest\venv\Scripts\python.exe E:/PycharmProjects/WebTest/src/test/case/test.py
执行用例:{'Account': 'test1', 'Password': 'edoc2', 'Verify': '登录成功'}
执行用例:{'Account': 'test2', 'Password': 'edoc2', 'Verify': '账号错误'}
test_login (__main__.Test) ... ok
test_login (__main__.Test) ... ok

----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK

进程已结束,退出代码为 0

可能会存在的问题

1.执行时,发现data为None

问题原因:运行配置中,使用的是“Python 测试” 执行的程序

解决方法:改用“Python”执行即可

设置入口:界面右上角箭头

posted @ 2022-01-21 15:04  lsepi  阅读(53)  评论(0编辑  收藏  举报