026python-excel

eval()函数:eval()函数,把数据类型转换成原本的数据类型
1:True原本是布尔值类型的数据
s = True
print(type(s))

2:将布尔值修改问字符串
s = 'True'
print(type(s))

3:使用eval将字符串s装换成原本的数据类型
s = 'True'
s_1 = eval(s)
print(type(s_1))


将数据存在excel里面,python去操作Excel 1:只支持.xlsx后缀 ——> 第三方库openpyxl 只支持这种格式 2:按照步骤去做:
(1)打开excel,接收返回的excel (2)定位表单
(3)定位单元格

from openpyxl import load_workbook

# 1:打开一个excel,变量wb接收返回的excel
wb = load_workbook('excel名.xlsx')  # Open the given filename and return the workbook:打开给定的文件,并返回excel

# 2:定位表单
sheet = wb['excel中的sheet页名']  # 传表单名,返回一个表单对象

# 3:定位单元格,行列值
res = sheet.cell(1, 1).value
print('拿到的结果是:', res)

# 求表单的最大行sheet.max_row
print('excel中数据的最大行是:{0}'.format(sheet.max_row))
# 求表单的最大列sheet.max_column
print('excel中数据的最大列是:{0}'.format(sheet.max_column))
数据从excel里面拿出来是什么类型?
数字还是数字,其他均为字符串
from openpyxl import load_workbook

# 1:打开一个excel,变量wb接收返回的excel
wb = load_workbook('excel名.xlsx')  # Open the given filename and return the workbook:打开给定的文件,并返回excel

# 2:定位表单
sheet = wb['excel中的sheet页名']  # 传表单名,返回一个表单对象

# 数据从excel里面拿出来是什么类型?数字还是数字,其他均为字符串
print('url:{0},类型是{1}'.format(sheet.cell(1, 1).value, type(sheet.cell(1, 1).value)))
print('data:{0},类型是{1}'.format(sheet.cell(1, 2).value, type(sheet.cell(1, 2).value)))
print('method:{0},类型是{1}'.format(sheet.cell(1, 3).value, type(sheet.cell(1, 3).value)))
print('expected:{0},类型是{1}'.format(sheet.cell(1, 4).value, type(sheet.cell(1, 4).value)))
练习:
1:把这些数据存在Excel里面,格式请看视频
{'url': 'https://XXXXX', 'data': {"email": "18510336097", "password": "116150ing"},'expected': 10000, 'method': 'post'},
{'url': 'https://XXXXX', 'data': {"isstudy": "1", "search": "查询"},'expected': 10000, 'method': 'post'},
2:利用openpyxl写一个专门读取Excel里面测试数据的类
3:结合课堂上老师讲解的单元测试方,通过初始化函数传参的方法,完成单元测试。
4:提交操作Excel的类、test_suite、test_http类(类名可以你自己定,我提供的是老师上课写的类名)
方法一:

步骤一:创建一个http_request请求
import requests


class HttpRequest:
    def http_request(self, url, data, method, cookie=None):
        if method == 'post':
            # res = requests.post(url, data.encode('utf-8'), cookies=cookie)
            res = requests.post(url, data, cookies=cookie)
        elif method == 'get':

            res = requests.get(url, data, cookies=cookie)
        return res
步骤二:创建一个反射测试类
class GetData:
    Cookie = None  # 存储cookie,初始值None
步骤三:创建测试用例测试类
import unittest

from class_013.class_excel_001.class_home_work.http_request_001 import HttpRequest
from class_013.class_excel_001.class_home_work.get_data import GetData


class TestHttp(unittest.TestCase):

    def setUp(self):  # 初始化,属性可以被实例调用,可以被类函数里面调用
        pass

    # 通过初始化函数来传参
    def __init__(self, methodName, method,url, data,  expected):
        # 实例调用继承父类初始化函数
        super(TestHttp, self).__init__(methodName)  # 超继承,继承父类里面的初始化函数
        # 改写父类
        self.url = url
        self.data = data
        self.method = method
        self.expected = expected

    def test_api(self):  # 接口用例
        # 测试用例只能通过初始化传参,不能通过测试用例传参,测试用例只能有一个参数self
        res = HttpRequest().http_request(self.url, self.data, self.method, getattr(GetData, 'Cookie'))
        if res.cookies:  # 如果cookie有的话,那么就会更新COOKIE,setattr()函数可以直接将类里面的属性做修改
            setattr(GetData, 'Cookie', res.cookies)
        print(res.json())
        try:
            self.assertEqual(self.expected, res.json()['code'])
        except AttributeError as e:
            print('test_api‘s error is{0}!!!!!'.format(e))
            raise e

    def tearDown(self):
        print('用例执行完毕!!!!!')
步骤四:创建测试数据excel
from openpyxl import load_workbook


class DoExcel:
    def __init__(self, file_name, sheet_name):
        self.file_name = file_name
        self.sheet_name = sheet_name

    def get_data(self):
        wb = load_workbook(self.file_name)
        sheet = wb[self.sheet_name]
        test_data = []

        for i in range(1, sheet.max_row + 1):
            sub_data = {}
            sub_data['method'] = sheet.cell(i, 1).value
            sub_data['url'] = sheet.cell(i, 2).value
            sub_data['data'] = sheet.cell(i, 3).value
            sub_data['expected'] = sheet.cell(i, 4).value

            test_data.append(sub_data)

        return test_data  # 获取返回的数据


if __name__ == '__main__':
    # 打印出返回值:实例调用方法接收返回值
    print(DoExcel('excel名.xlsx', 'excel中sheet页面名').get_data())
步骤五:执行用例,获取测试报告
import unittest
import HTMLTestRunnerNew
from class_013.class_excel_001.class_home_work.test_http import TestHttp
from class_013.class_excel_001.class_home_work.do_excel import DoExcel


test_data =DoExcel('nuannuan.xlsx', 'nuannuan_03').get_data()

# 创建实例,存储用例,加载数据
suite = unittest.TestSuite()
# 实例的方式去加载用例:suite.addTest(实例(参数))
for item in test_data:   # 遍历数据传参
    # UnicodeEncodeError: 'latin-1' codec can't encode characters in position 28-29: Body ('查询') is not valid Latin-1. Use body.encode('utf - 8') if you want to send it encoded in UTF-8.——>解决这个问题可以使用eval将item['data']装换成原本的数据类型,也可以在http_request模块在data参数后面添加.encode('utf-8')
    suite.addTest(TestHttp('test_api', item['url'], eval(item['data']), item['method'], item['expected']))

with open('test_kt_report.html', 'wb') as file:
    runner = HTMLTestRunnerNew.HTMLTestRunner(stream=file, verbosity=2, title='python“课堂派”单元测试报告,excel形式加载测试用例参数', description='报告描述:自动化课堂派测试报告', tester='暖暖')
    runner.run(suite)
 方法二:

步骤一:创建一个http_request请求
import requests


class HttpRequest:
    def http_request(self, url, data, method, cookie=None):
        if method == 'post':
            # res = requests.post(url, data.encode('utf-8'), cookies=cookie)
            res = requests.post(url, data, cookies=cookie)
        elif method == 'get':

            res = requests.get(url, data, cookies=cookie)
        return res
步骤二:创建一个反射测试类
class GetData:
    Cookie = None  # 存储cookie,初始值None
步骤三:创建测试用例测试类
import unittest

from class_013.class_excel_001.class_home_work.http_request_001 import HttpRequest
from class_013.class_excel_001.class_home_work.get_data import GetData


class TestHttp(unittest.TestCase):

    def setUp(self):  # 初始化,属性可以被实例调用,可以被类函数里面调用
        pass

    # 通过初始化函数来传参
    def __init__(self, methodName, method,url, data,  expected):
        # 实例调用继承父类初始化函数
        super(TestHttp, self).__init__(methodName)  # 超继承,继承父类里面的初始化函数
        # 改写父类
        self.url = url
        self.data = data
        self.method = method
        self.expected = expected

    def test_api(self):  # 接口用例
        # 测试用例只能通过初始化传参,不能通过测试用例传参,测试用例只能有一个参数self
        res = HttpRequest().http_request(self.url, self.data, self.method, getattr(GetData, 'Cookie'))
        if res.cookies:  # 如果cookie有的话,那么就会更新COOKIE,setattr()函数可以直接将类里面的属性做修改
            setattr(GetData, 'Cookie', res.cookies)
        print(res.json())
        try:
            self.assertEqual(self.expected, res.json()['code'])
        except AttributeError as e:
            print('test_api‘s error is{0}!!!!!'.format(e))
            raise e

    def tearDown(self):
        print('用例执行完毕!!!!!')
步骤四:创建测试数据excel
from openpyxl import load_workbook


class DoExcel:
    def __init__(self, file_name, sheet_name):
        self.file_name = file_name
        self.sheet_name = sheet_name
        # 拿到表单名,获取表单对象
        self.sheet_obj = load_workbook(self.file_name)[sheet_name]
        # 获取表单最大行数
        self.max_row = self.sheet_obj.max_row

    def get_data(self, i, j):
        # 根据传入的坐标来获取值
        return self.sheet_obj.cell(i, j).value


if __name__ == '__main__':
    # 打印出返回值:实例调用方法接收返回值
    print(DoExcel('excel名.xlsx', 'excel名中sheet页名').get_data(1, 1))
步骤五:执行用例,获取测试报告
import unittest
import HTMLTestRunnerNew
from class_013.class_excel_001.class_home_work.test_http import TestHttp
from class_013.class_excel_001.class_home_work.do_excel import DoExcel


test_data =DoExcel('nuannuan.xlsx', 'nuannuan_03').get_data()

# 创建实例,存储用例,加载数据
suite = unittest.TestSuite()
# 实例的方式去加载用例:suite.addTest(实例(参数))
for item in test_data:   # 遍历数据传参
    # UnicodeEncodeError: 'latin-1' codec can't encode characters in position 28-29: Body ('查询') is not valid Latin-1. Use body.encode('utf - 8') if you want to send it encoded in UTF-8.——>解决这个问题可以使用eval将item['data']装换成原本的数据类型,也可以在http_request模块在data参数后面添加.encode('utf-8')
    suite.addTest(TestHttp('test_api', item['url'], eval(item['data']), item['method'], item['expected']))

with open('test_kt_report.html', 'wb') as file:
    runner = HTMLTestRunnerNew.HTMLTestRunner(stream=file, verbosity=2, title='python“课堂派”单元测试报告,excel形式加载测试用例参数', description='报告描述:自动化课堂派测试报告', tester='暖暖')
    runner.run(suite)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值