def generate_testcases(self, read_path, write_path0, write_path1): # 生成排列组合的测试用例和测试用例解释标签 excel = ReadExcel(read_path) s0, s1, title0 = excel.read_and_save_cols_excel() # 将测试用例排列组合 datagroup = s0 permutations = Permutations(datagroup) # 用ss0列表存储排列组合的测试用例 ss0 = [] ss0.append([title for title in title0[::2]]) ss0[1:] = permutations.assemble() print(ss0) # 将测试用例结束排列组合 datagroup1 = s1 permutations1 = Permutations(datagroup1) # 用ss1列表存储排列组合的测试用例解释标签 ss1 = [] ss1.append([title1 for title1 in title0[1::2]]) ss1[1:] = permutations1.assemble() print(ss1) # 将生成的测试用例写入excel中 Writedata(write_path0).data_write(write_path0, ss0) Writedata(write_path1).data_write(write_path1, ss1) testcases = ExcelToDic().getExcelData(write_path0, 'Sheet1') return testcases
def __init__(self): self.d = ReadExcel() self.datalist2 = self.d.read() self.urlstr = self.datalist2[0][1] self.payload = eval(self.datalist2[0][4]) self.method = self.datalist2[0][3] self.expect = self.datalist2[0][5] print(self.datalist2)
def dataForDDT(): global file_path, sheet_name project_path = (os.path.split(os.path.dirname(__file__)))[0] file_path = os.path.join(project_path, Constant.EXCEL_NAME) sheet_name = 'checkQQOnline' filter_para = ["caseName","remarks", "para_QQ", "expectedCode"] RE = ReadExcel(file_path, sheet_name, filter_para) RE.getExcelData() filter_data = RE.filterData() return tuple(filter_data) # 要把列表转换为元组,ddt数据源是个tuple类型
def test_permutations(self): excel = ReadExcel('../test/data_origin/test_read_excel.xlsx') s0, s1 = excel.read_and_save_cols_excel() # 将测试用例排列组合 datagroup = s0 permutations = Permutations(datagroup) # 用ss0列表存储排列组合的测试用例 ss0 = permutations.assemble() print(ss0) # 将测试用例结束排列组合 datagroup1 = s1 permutations1 = Permutations(datagroup1) # 用ss1列表存储排列组合的测试用例 ss1 = permutations1.assemble() print(ss1)
def test_api(self, data): expect_result = int(data['expect_result'].split(':')[1]) # 获取token 并放在yaml上 token = get_token() print('yaml中的token:%s' % token) data = str(data).replace("#{token}", token) print('login_token:%s' % data) re = SendRequests().sendRequests(self.s, eval(data), baseUrl) true_status = int(re['status']) if true_status == 1: #获取token 并放在yaml上 orderNo = re['data'] print('orderNo:%s' % orderNo) with open(ypath, 'w', encoding='utf-8') as f: yaml.dump(orderNo, f) self.assertEqual(expect_result, true_status, '实际返回数据为:%s' % re) lines = ReadExcel().get_lines() for line in len(lines): ReadExcel().write_cell_value(path, "createorder", line, 16, re)
class ConfigHttp(): def __init__(self): self.d = ReadExcel() self.datalist2 = self.d.read() self.urlstr = self.datalist2[0][1] self.payload = eval(self.datalist2[0][4]) self.method = self.datalist2[0][3] self.expect = self.datalist2[0][5] print(self.datalist2) def run(self, data): if str(data) == str(self.expect): print('success') else: print('fail')
def readExcel_new(self): testData = ReadExcel.readExcel( "E:\\有课树测试项目\\yan_个人项目集合\\fukun_apitest\\data\\arm_apiTest.xlsx", "Sheet1") print(testData) st1 = testData[0]["body"] st = eval(st1) keys = st.keys() ticket, userName = Armlogin().login() funVersion = rt.funVersion() for key in keys: if st[key] == "${operator}": st[key] = userName if st[key] == "${ticket}": st[key] = ticket if st[key] == "${funVersion}": st[key] = funVersion return st
if apiData["body"] == "": body_data = None else: body_data = eval(apiData["body"]) type = apiData["type"] v = False if type == "json": body = json.dumps(body_data) if type == "data": body = body_data else: body = body_data #发送请求 re = s.request(method=method,url=url,headers=h,params=par,data=body,verify=v) return re except Exception as e: print(e) if __name__ == '__main__': urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) s = requests.session() testData = ReadExcel.readExcel("elive_apiTest.xlsx", "Sheet1") response = SendRequests().sendRequests(s,testData[3]) print(response.json())
def __init__(self,excel_name,sheet_name): self.excel_name = excel_name self.sheet_name = sheet_name self.readConfig = ReadConfig() self.readExcel = ReadExcel(excel_name,sheet_name)
class ReadCase: def __init__(self,excel_name,sheet_name): self.excel_name = excel_name self.sheet_name = sheet_name self.readConfig = ReadConfig() self.readExcel = ReadExcel(excel_name,sheet_name) def set_excel_name(self,excel_name): self.excel_name = excel_name def set_sheet_name(self,sheet_name): self.sheet_name = sheet_name def get_sheet_name(self): return self.sheet_name def get_excel_name(self): return self.excel_name # 根据用例名称获取接口地址,协议+host+port+path def get_interface_url(self,case_name,no_online=True,is_serv=True): if no_online and is_serv: try: new_url = self.readConfig.get_service_dev('scheme') + '://' + self.readConfig.get_service_dev( 'host') + ':' + self.readConfig.get_service_dev( 'port') + self.get_path(case_name) return new_url except Exception as e: print(e) print("线上服务用例名称不存在或输入错误,请检查") elif no_online and is_serv==False: try: new_url = self.readConfig.get_h5app_dev('scheme') + '://' + self.readConfig.get_h5app_dev( 'host') + ':' + self.readConfig.get_h5app_dev( 'port') + self.get_path(case_name) return new_url except Exception as e: print(e) print("线上h5app用例名称不存在或输入错误,请检查") elif no_online==False and is_serv: try: new_url = self.readConfig.get_service_online('scheme') + '://' + self.readConfig.get_service_online( 'host') + ':' + self.readConfig.get_service_online('port') + self.get_path(case_name) return new_url except Exception as e: print(e) print("dev服务用例名称不存在或输入错误,请检查") elif no_online==False and is_serv==False: try: new_url = self.readConfig.get_h5app_online('scheme') + '://' + self.readConfig.get_h5app_online( 'host') + ':' + self.readConfig.get_h5app_online('port') + self.get_path(case_name) return new_url except Exception as e: print(e) print("dev服务用例名称不存在或输入错误,请检查") else: print('未知错误') # def get_interface_url(self, case_name, is_online=True): # if is_online: # try: # new_url = self.readConfig.get_h5app_dev('scheme') + '://' + self.readConfig.get_h5app_dev('host') + ":" + self.readConfig.get_h5app_dev('port') + self.get_path(case_name) # # print(new_url) # return new_url # except Exception as e: # print(e) # print("用例名称不存在2,或输入错误,请检查!!!") # else: # try: # new_url = self.readConfig.get_http('scheme') + '://' + self.readConfig.get_http('host') + ":" + self.readConfig.get_http('port') + self.get_path(case_name) # return new_url # except Exception as e: # print(e) # print("用例名称不存在1,或输入错误,请检查!!!") def get_interface_data(self,case_name): try: for i in range(0,self.readExcel.nrows): row_value = self.readExcel.get_excel()[i][0] if case_name ==row_value: return self.readExcel.get_excel()[i][2] except Exception as e: print(e) print("data对应用例名称不存在,或输入错误,请检查") def get_interface_headers(self,case_name): try: for i in range(0,self.readExcel.nrows): row_value = self.readExcel.get_excel()[i][0] if case_name == row_value: headers = self.readExcel.get_excel()[i][3] headers_dict = json.loads(headers) return headers_dict except Exception as e: print(e) print("Headers不存在或输入错误,请检查") # 根据用例名称返回这个用例所对应的path路径 def get_path(self,case_name): for i in range(0,self.readExcel.nrows-1): row_value = self.readExcel.get_excel()[i][0] if case_name == row_value: return self.readExcel.get_excel()[i][1] def get_method(self,case_name): try: for i in range(0,self.readExcel.nrows): row_value = self.readExcel.get_excel()[i][0] if case_name == row_value: return self.readExcel.get_excel()[i][4] except Exception as e: print(e) print("method对应用例名称不存在或输入错误,请检查")
# coding:utf-8 import unittest import requests import json import HTMLTestRunner from ddt import ddt, data, unpack from common.readExcel import ReadExcel from common.sendRequest import SendRequests testdata = ReadExcel.readExcel( "F:\\pythonPjo\\testExcelCase\\data\\login.xlsx", "test") #print("testdate=", testdata) @ddt class excelTest(unittest.TestCase): def setUp(self): print('开始接口测试') def tearDown(self): print('完成接口测试') @data(*testdata) #@unpack def test_login(self, data): """登录""" r = SendRequests.sendRequests( data, "F:\\pythonPjo\\testExcelCase\\data\\login.xlsx") SendRequests.write_result( r, "F:\\pythonPjo\\testExcelCase\\data\\login.xlsx")
import os, sys import unittest, requests, ddt from config import setting from common.readExcel import ReadExcel from common.sendRequests import SendRequests from common.writeExcel import writeExcel import common.log log = common.log.logger sys.path.append(os.path.dirname(os.path.dirname(__file__))) test_data = ReadExcel(setting.SOURCE_FILE, "Sheet1").read_data() @ddt.ddt class Test_API(unittest.TestCase): #执行测试用例前的fixture def setUp(self): self.session = requests.session() # 执行测试用例后的fixture def tearDown(self): pass @ddt.data(*test_data) def test_api(self, data): rowNum = int(data["ID"].split("_")[2]) log.info("执行测试用例:%s", "正在执行用例->{0}".format(data["ID"])) log.info("请求方式: {0},请求URL: {1}".format(data['method'], data['url'])) log.info("请求参数: {0}".format(data['params']))
h = eval(h) if isinstance(h, str) else h h["Authorization"] = GetJWT().getJWT() requester = Requester(method, url, h, par, body, file_data, publice_params) try: if method == "post": resp = requester.setPost(self.s) elif method == "put": resp = requester.setPut(self.s) elif method == "get": resp = requester.setGet(self.s) else: response_data = {"result": "ERROR"} return response_data reContent.append(resp.text) except ReadTimeout: response_data = {"result": "TimeOut"} return response_data except Exception as e: print(e) print(reContent) return reContent if __name__ == '__main__': testData = ReadExcel("/Users/shuiguowei/Practice/BackEnd/ApiAutoTest/data/testdemo.xlsx", "Sheet1").readExcel() response = SendRequests().sendRequests(testData)
def test_something2(self): t = ReadExcel() data = t.readExcel( 'C:\\Users\\01384526\\PycharmProjects\\RequestsApi\\Data\\ExcelData\\TestCase.xlsx' ) print(data)
from common.readExcel import ReadExcel import os, yaml import unittest, requests from readConfig import ReadConfig from common.read_token import get_token from ddt import ddt, data from common.readRequests import SendRequests baseUrl = ReadConfig().get_config('HTTP', "newurl") path = os.path.join(os.path.dirname(os.getcwd()), 'resource', 'test_api1.xlsx') testcast = ReadExcel.readExcel(path, 'createorder') #获取根目录 ypath = os.path.join(os.path.dirname(os.getcwd()), 'common', 'order.yaml') print('根目录为:%s' % ypath) @ddt class TestOrderPage(unittest.TestCase): def setUp(self): self.s = requests.session() def tearDown(self): pass @data(*testcast) def test_api(self, data): expect_result = int(data['expect_result'].split(':')[1]) # 获取token 并放在yaml上 token = get_token() print('yaml中的token:%s' % token)
else: par = eval(apiData["params"]) if apiData["headers"] == "": h = None else: h = eval(apiData["headers"]) if apiData["body"] == "": body_data = None else: body_data = eval(apiData["body"]) ytype = apiData["ytype"] v = False if ytype == "json": body = json.dumps(body_data) if ytype == "data": body = body_data else: body = body_data #发送请求 re = s.request(method=method,url=url,headers=h,params=par,data=body,verify=v) return re if __name__ == '__main__': s = requests.session() testData = ReadExcel.readExcel("E:\\有棵树测试项目\\yan_个人项目集合\\fukun_apitest\\data\\arm_apiTest.xlsx","Sheet1") response = SendRequests().sendRequests(s,testData[0]) print(response)
# -*- coding:utf-8 -*- import unittest import requests, urllib3 from ddt import ddt, data, unpack from common.sendRequests import SendRequests from common.readExcel import ReadExcel testData = ReadExcel.readExcel( "C:\\Users\\Magic\\PycharmProjects\\easylive_api\\data\\elive_apiTest.xlsx", "Sheet1") @ddt class Test1(unittest.TestCase): def setUp(self): self.s = requests.session() def tearDown(self): pass @data(*testData) def test_login_api(self, data): urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) re = SendRequests().sendRequests(self.s, data) print("re:", re.text) #切割字符串取后面的部分 expect_result1 = str(data["expect_result"]) #转换为字符串
@site: @software: PyCharm @file: case_01.py @time: 2019/8/28 10:58 """ import unittest import requests import ddt from common.sendSingelRequest import SendSingelRequests from common.readExcel import ReadExcel import os from conf import test_path import json # 配置文件里读取表格数据 Data = ReadExcel(test_path.path1, "Sheet1").readExcel() ApplicatonData = ReadExcel(test_path.path2, "Sheet1").readExcel() @ddt.ddt class Test_api(unittest.TestCase): """测试框架使用Unittest和DDT相结合的方式""" def setUp(self): pass # print("测试前环境与数据准备") # @ddt.data(*Data) # def test_ddt(self, data): # print(data) @ddt.data(*Data)
from common.readExcel import ReadExcel import os import unittest, requests from readConfig import ReadConfig import yaml from ddt import ddt, data from common.readRequests import SendRequests baseUrl = ReadConfig().get_config('HTTP', "newurl") path = os.path.join(os.path.dirname(os.getcwd()), 'resource', 'test_api1.xlsx') testcast = ReadExcel.readExcel(path, 'login') #获取根目录 ypath = os.path.join(os.path.dirname(os.getcwd()), 'common', 'token.yaml') print('根目录为:%s' % ypath) @ddt class DdtTest(unittest.TestCase): def setUp(self): self.s = requests.session() def tearDown(self): pass @data(*testcast) def test_api(self, data): re = SendRequests().sendRequests(self.s, data, baseUrl) true_status = int(re['status']) if true_status == 1:
3-断言接口 相等=success 不等=fail 4.写入Excel ''' import ddt import requests import unittest from ddt import ddt, data, unpack from common.readExcel import ReadExcel from common.configHttp import ConfigHttp re = ReadExcel() datelist = re.getdict() print(datelist) @ddt class TestCase(unittest.TestCase): @data(*datelist) @unpack def testrun(self, id, interfaceUrl, name, Method, value, expect, real, status): print('----', id, interfaceUrl, name, Method, value, expect, real, status) ch = ConfigHttp(interfaceUrl, value, Method, expect) realError = ch.run()
from common.readExcel import ReadExcel import os import unittest, requests from common.read_token import get_token from ddt import ddt, data from common.readRequests import SendRequests path = os.path.join(os.path.dirname(os.getcwd()), 'resource', 'test_api2.xlsx') testcast = ReadExcel.readExcel(path, 'userinfo') @ddt class TestUserInfo(unittest.TestCase): def setUp(self): self.s = requests.session() def tearDown(self): pass @data(*testcast) def test_api(self, data): expect_result = data['expect_result'].split(':')[1] # 获取token 并放在yaml上 token = get_token() print('yaml中的token:%s' % token) data = str(data).replace("#{token}", token) print('login_token:%s' % data) re = SendRequests().sendRequests(self.s, eval(data)) true_status = int(re['status']) print('ddt中数据为:%s' % true_status) self.assertEqual(true_status, int(expect_result), '实际返回数据为:%s' % re)
#! /usr/bin/env python # -*- coding:utf-8 -*- import unittest import requests from ddt import ddt, data, unpack from common.sendRequests import SendRequests from common.readExcel import ReadExcel import os path = os.path.dirname(os.getcwd()) + "\\data\\arm_apiTest.xlsx" testData = ReadExcel.readExcel(path, "Sheet1") # testData = testData_o[0] # print(testData) @ddt class Test1(unittest.TestCase): def setUp(self): self.s = requests.session() def tearDown(self): pass @data(*testData) def test_loginarm_api(self, data): re = SendRequests().sendRequests(self.s, data) print(re.json()["state"]) #切割字符串取后面的部分
def test_read_excel(self): excel = ReadExcel("../test/data_origin/test_read_excel.xlsx") s0, s1 = excel.read_and_save_cols_excel() print(s0, s1)
from common.readExcel import ReadExcel import os import unittest, requests from common.read_token import get_token from ddt import ddt, data from common.readRequests import SendRequests path = os.path.join(os.path.dirname(os.getcwd()), 'resource', 'test_api1.xlsx') testcast = ReadExcel.readExcel(path, 'orderpage') @ddt class TestOrderPage(unittest.TestCase): def setUp(self): self.s = requests.session() def tearDown(self): pass @data(*testcast) def test_api(self, data): expect_result = int(data['expect_result'].split(':')[1]) # 获取token 并放在yaml上 token = get_token() print('yaml中的token:%s' % token) data = str(data).replace("#{token}", token) print('login_token:%s' % data) re = SendRequests().sendRequests(self.s, eval(data)) true_status = int(re['status']) self.assertEqual(expect_result, true_status, '实际返回数据为:%s' % re)
4-从接口请求的结果中,提取需要断言的字段errorCode 5-将实际提取的errorCode和excel中预期的进行比较 5.1-相同即通过,succes 5.2-不同即失败,fail 6-将接口断言得到的结果写入excel """ import unittest,requests from common.readExcel import ReadExcel from ddt import ddt,data,unpack from common.configHttp import ConfigHttp from common.writeExcel import WriteExcel re = ReadExcel() testdata = re.getdata() @ddt class TestCase(unittest.TestCase): # 2-提取测试数据内的method方法 @data(*testdata) @unpack def test_run(self,id,interfaceUrl,name,Method,value,expect,real,status): method = Method url = interfaceUrl value = value expect = expect id = id ch = ConfigHttp(url, value, method) status_code,real_errorcode =ch.run()