python - requests从excel中获取测试用例数据

 

 

HttpRequests.py

 1 #-*- coding:utf-8 -*-
 2 
 3 
 4 import requests
 5 class HttpRequests():
 6     def http_requests(self,url,params,http_mothed,cookies=None):
 7         if http_mothed=='get':
 8             res=requests.get(url,params,cookies=cookies)
 9             return res
10         else:
11             res=requests.post(url,params,cookies=cookies)
12             return res

 

test_HttpRequests.py

 1 #-*- coding:utf-8 -*-
 2 
 3 #存放测试用例
 4 import unittest
 5 from study_181130_request.HttpRequests import HttpRequests
 6 
 7 
 8 COOKIES=None
 9 
10 class TestHttpRequests(unittest.TestCase):
11 
12 
13     def setUp(self):
14         # self.url='http://47.107.168.87:8080/futureloan/mvc/api/member/login'
15         pass
16 
17     def __init__(self,url,params,http_method,excepted,methodName):#初始化传参;用初始化函数一定要记得去看看父类里面有没有初始化函数,如果有,需要超继承
18 
19         self.params=params#请求的数据
20         self.http_method=http_method#请求方法
21         self.url=url
22         self.excepted=excepted
23         super(TestHttpRequests,self).__init__(methodName)#超继承
24 
25 
26     def test_api(self):#登录成功 :手机号正确、密码正确;用例里面不可以传参数
27         global COOKIES#声明全局变量
28         res=HttpRequests().http_requests(self.url,self.params,self.http_method,COOKIES)
29         try:
30             self.assertEqual(self.excepted,res.json()['msg'])
31         except AssertionError as e:
32             print('断言结果是:{}'.format(e))
33             raise e
34 
35         if res.cookies:
36             COOKIES=res.cookies#当res.cookies非空时,修改COOKIES的值

 

test_runner.py

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


import unittest
import HTMLTestRunnerNew
from study_181130_request.test_HttpRequests import TestHttpRequests
from study_181130_request.read_excel import TestExcel

test_data=TestExcel().get_TestExcel()

suit=unittest.TestSuite()##装用例的地方
for item in test_data:
    suit.addTest(TestHttpRequests(item['url'],eval(item['params']),item['http_method'],item['excepted'],'test_api'))#创建实例的方法来添加用

#执行用例
with open('test_api.html','bw+') as file:
    Runner=HTMLTestRunnerNew.HTMLTestRunner(stream=file,verbosity=2,
                                            title='HTTP请求作业-单元测试报告',description='测试一下HTTP请求',tester='huimin'
                                            )
    Runner.run(suit)

 

read_excel.py

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

from openpyxl import load_workbook


class TestExcel():

    def get_TestExcel(self):
        workbook = load_workbook('http_requests.xlsx')#打开表
        sheet = workbook['Sheet1']#定位表单

        test_data = []#把所有行的数据放到列表中

        for i in range(2,sheet.max_row+1):
            sub_data = {}#把每行的数据放到字典中
            for j in range(1,sheet.max_column+1):

                sub_data[sheet.cell(1,j).value] = sheet.cell(i,j).value

            test_data.append(sub_data)#拼接每行单元格的数据

        return test_data

 

测试报告:

 

posted @ 2018-12-09 19:53  赵小丫  阅读(2379)  评论(1编辑  收藏  举报