def get_token(self): testdata = ExcelUtil(self.filepath, self.SheetName).dict_data()[0] method = testdata["method"] url = testdata["url"] params = testdata["params"] headers = eval(testdata["header"]) type = testdata["type"] try: bodydata = eval(testdata["body"]) except: bodydata = {} # 判断传data数据还是json if type == "data": body = bodydata elif type == "json": body = bodydata else: body = bodydata verify = False res = self.s.request(method=method, url=url, params=params, headers=headers, json=body, verify=verify) token = res.json()["data"]["token"] return token
def test_bdh_api(self): #获取数据 data,key_names= ExcelUtil(testxlsx).dict_data() #print(key_names) reals=[] count=len(data) print('接口总数',count) suc_num=0 for i in range(len(data)): print('--正在进行接口测试,开始第%d个请求---------------'%(i+1)) datalist=[] datalist=data[i] url="http://"+datalist['url'].strip()+ datalist['path'].strip() datas=datalist['params'] method=datalist['method'] headers={} headers['content-type']=datalist['headers'] if datalist['tokenname']=='BDHAuthorization': tokenname=datalist['tokenname'] headers[tokenname]=datalist['token'] print("-------请求参数-----------------") print(method) print(url) print('header:',headers) print('data',datas) print("-------返回参数-----------------") my_request=ApiRequest(method,url,datas,headers) r=my_request.api_request() print('code',my_request.get_code()) print('response',r.json()) res=r.json() datalist['realresult']=str(r.json()) #期望结果 ex_result=datalist['expectedresult'] AC_result=datalist['realresult'] print('----------------debug--------------') print(type(datalist['realresult']),type(ex_result)) print(ex_result,datalist['realresult']) print(ex_result in datalist['realresult']) if ex_result in AC_result: print('第{0}个接口,{1}:测试成功。\njson数据为:{2}'.format(i + 1, datalist['casename'], r.json())) datalist['result']='测试成功' suc_num=suc_num+1 else: print('第{0}个接口,{1}:测试失败。\njson数据为:{2}'.format(i + 1, datalist['casename'], r.json())) datalist['result']='测试失败' #保存所有数据 reals.append(datalist) #write_datas print("-------正在写入数据,请等待-----------------") write_excel(newfile,reals,key_names) return suc_num,reals,key_names
def test_bdh_api(self): #获取数据 data, key_names = ExcelUtil(testxlsx).dict_data() print(key_names) reals = [] count = len(data) print('count', count) suc_num = 0 for i in range(len(data)): print('----正在进行接口测试,开始第%d个请求---------------' % (i + 1)) datalist = [] datalist = data[i] url = "http://" + datalist['url'].strip() + datalist['path'].strip( ) datas = datalist['params'] method = datalist['method'] headers = {} headers['content-type'] = datalist['headers'] print(method, url, datas, headers) my_request = ApiRequest(method, url, datas, headers) r = my_request.api_request() print('status_code', my_request.get_code()) print('response', r.json()) res = r.json() datalist['realresult'] = r.json() #期望结果 ex_result = datalist['expectedresult'] if ex_result in res: print('{0}、{1}:测试成功。json数据为:{2}'.format( i + 1, datalist['casename'], r.json)) datalist['result'] = '测试成功' suc_num = suc_num + 1 else: print('{0}、{1}:测试失败'.format(i + 1, datalist['casename'])) datalist['result'] = '测试失败' #保存所有数据 reals.append(datalist) #print(datalist) self.suc_num = suc_num self.datas = reals self.key_names = key_names #写入excel #self.write_eccel_datas() return suc_num, reals, key_names
def login(): data = ExcelUtil(HOUSE_MANAGE_EXCEL_PATH, sheetName="获取clientkey").dict_data() print(data[0]) s = requests.session() res = send_requests(s, data[0]) # print(res) # 返回结果x res_text = res["text"] print(res_text) data_text = json.loads(res_text) client_key = data_text["DATA"][0]["OPERATOR"]["CLIENTKEY"] #获取clientkey return client_key # a=login() # print(a)
def get_clientkey(): # global header # try: data = ExcelUtil(HOUSE_MANAGE_EXCEL_PATH, sheetName="获取clientkey").dict_data() print(data[0]) s = requests.session() res = send_requests(s, data[0]) # print(res) # 返回结果x res_text = res["text"] # print(res_text) data_text = json.loads(res_text) client_key = data_text["DATA"][0]["OPERATOR"]["CLIENTKEY"] #获取clientkey # print(client_key) header = json.loads(data[0]['headers']) #json转换成字典 # print(header) # 添加CLIENTKEY到headers中去 header.update({'CLIENTKEY': client_key}) # except Exception as e: # print(e) return header
res['msg'] = '' if testdata['checkpoint'] in res['text']: res['result'] = 'pass' print('用例测试结果:%s--->%s' % (test_nub, res['result'])) else: res['result'] = 'fail' return res except Exception as e: res['msg'] = str(e) return res def write_result(result, filename='result.xlsx'): row_nub = result['rowNum'] wt = Write_excel(filename) wt.write(row_nub, 8, result['statuscode']) wt.write(row_nub, 9, result['times']) wt.write(row_nub, 10, result['error']) wt.write(row_nub, 12, result['result']) wt.write(row_nub, 13, result['msg']) if __name__ == '__main__': data = ExcelUtil('debug_api.xlsx').dict_data() print(data[0]) s = requests.session() res = send_requests(s, data[0]) print(res['statuscode']) copy_excel('debug_api.xlsx', 'result.xlsx') write_result(res, filename='result.xlsx')
import unittest import ddt import os import requests from common.copy_excel import copy_excel, Write_excel from common.readexcel import ExcelUtil from common.api import send_requests, write_result import json #读取test.xlsx文件中的测试数据 current_path = os.path.dirname(os.path.realpath(__file__)) testdata_path = os.path.join(os.path.dirname(current_path), "testdate") testdatafile = os.path.join(testdata_path, "test.xlsx") testdata = ExcelUtil(testdatafile).dict_data() #复制测试数据至report目录下的report.xml文件中 report_path = os.path.join(os.path.dirname(current_path), "report") reportfile = os.path.join(report_path, "report.xlsx") copy_excel(testdatafile, reportfile) #登录信息 loginData = {"username": "******", "password": "******"} @ddt.ddt class Test_api(unittest.TestCase): @classmethod def setUpClass(cls): #登录 cls.s = requests.session() cls.s.request(method="", url="", data=loginData)
# -*- coding:utf-8 -*- from page.login_page import LoginPage from selenium import webdriver import unittest import ddt from common.readexcel import ExcelUtil filepath = "testdata.xlsx" data = ExcelUtil(filepath) testdata = data.dict_data() # 读取数据为list print(testdata) # # 参数和代码分离 # testdata = [ # {"username": "******", "psw": "123456", "result": "admin"}, # {"username": "******", "psw": "123456", "result": ""}, # {"username": "******", "psw": "111111", "result": "admin2"}, # {"username": "******", "psw": "111111", "result": "admin3"}] @ddt.ddt # 测试类前面加上@ddt.ddt class LoginCase(unittest.TestCase): @classmethod def setUpClass(cls): cls.driver = webdriver.Firefox() cls.loginpage = LoginPage(cls.driver) def login_case(self, username, psw): # 登录 self.loginpage.login(username, psw)
def datas(): filepath = "../all_Case/testdata.xlsx" sheetName = "Sheet1" data = ExcelUtil(filepath, sheetName) testdata = data.dict_data() return testdata
if testdata["checkpoint"] in res["text"]: res["result"] = "pass" print("用例测试结果: %s---->%s" % (test_nub, res["result"])) else: res["result"] = "fail" return res except Exception as msg: res["msg"] = str(msg) return res def wirte_result(result, filename="result.xlsx"): # 返回结果的行数row_nub row_nub = result['rowNum'] # 写入statuscode wt = Write_excel(filename) wt.write(row_nub, 8, result['statuscode']) # 写入返回状态码statuscode,第8列 wt.write(row_nub, 9, result['times']) # 耗时 wt.write(row_nub, 10, result['error']) # 状态码非200时的返回信息 wt.write(row_nub, 12, result['result']) wt.write(row_nub, 13, result['msg']) # 抛异常 if __name__ == "__main__": data = ExcelUtil("debug_api.xlsx").dict_data() print(data[0]) s = requests.session() res = send_requests(s, data[0]) copy_excel("debug_api.xlsx", "result.xlsx") wirte_result(res, filename="result.xlsx")
def get_code(self): #获取返回接口的状态码 code = self.api_request().status_code return code def get_json(self): #获取返回信息json数据 json_data = self.api_request().json() return json_data if __name__ == "__main__": #获取数据 filepath = r"E:\mysoft\myworksapce\project\API_py_scripts_demo2\myapidata.xlsx" data = ExcelUtil(filepath).dict_data() count = len(data) print('count', count) for i in range(len(data) - 3): print('----正在进行接口测试,开始第%d个请求---------------' % (i + 1)) datalist = [] datalist = data[0] url = "http://" + datalist['url'].strip() + datalist['path'].strip() datas = datalist['params'] method = datalist['method'] headers = {} headers['content-type'] = datalist['headers'] if datalist['tokenname'] == 'BDHAuthorization': tokenname = datalist['tokenname']
import ddt from pages.login_page import Login, login_url from selenium import webdriver from common.readexcel import ExcelUtil curpath = os.path.dirname(os.path.realpath(__file__)) #os去获取文件logindata.xlsx的路径, filepath = os.path.join(curpath, "logindata.xlsx") #xls的路径写死:"D:\\test1\\Test\\common\\logindata.xlsx" print("logindata的路径%s" % filepath) data = ExcelUtil(filepath, "Sheet1") test_datas = data.dict_data() print(test_datas) ''' test_datas = [ {"user": "******", "psw": "123456", "expect": True}, {"user": "******", "psw": "123456", "expect": False}, {"user": "******", "psw": "123456", "expect": False}, {"user": "******", "psw": "123456", "expect": True}, ] ''' #AttributeError: 'TestLoader' object has no attribute 'makeTest' 鼠标没放到if下运行 @ddt.ddt
#coding:utf-8 import ddt import unittest from case.login import login from common.readexcel import ExcelUtil # 参数和代码分离 # testdata = [ # {"username": "******", "psw": "admin123"}, # {"username": "******", "psw": "yifan123"}, # {"username": "******", "psw": "admin123"}, # {"username": "******", "psw": "kangyong"}, # ] readexcel = ExcelUtil("testdata.xlsx") d11 = readexcel.dict_data() print(d11) @ddt.ddt class Test_login(unittest.TestCase): u''' crm系统登录模块''' def setUp(self): self.host = "https://crm-test.jingdaka.com/api/crm" @ddt.data(*d11) def test_01(self, canshu): u''' 运营主管正确帐号密码登录''' print(canshu) self.username = canshu["username"] self.password = canshu["password"] (self.code, self.roleid) = login.login(self.host, self.username,
from selenium import webdriver from page.login_swsp import Login_swsp import unittest import ddt from common.readexcel import ExcelUtil filepath = "testshuju.xlsx" TesDate=ExcelUtil(filepath).dict_data() @ddt.ddt class Swsp_login(unittest.TestCase): @classmethod def setUpClass(cls): cls.driver=webdriver.Firefox() url="http://10.3.108.25:9001/" cls.driver.get(url) #实例化 cls.log=Login_swsp(cls.driver) @ddt.data(*TesDate) def test001(self,params): print(params) res=self.log.login(params["username"],params["pws"]) except_res=True self.assertEqual(res,except_res) def tearDown(self): self.log.login_out()
import ddt import os import requests from common.base_api import send_requests, write_result from common.readexcel import ExcelUtil from common.writeexcel import copy_excel, Write_excel # 获取demo_api.xlsx路径 curpath = os.path.dirname(os.path.realpath(__file__)) testxlsx = os.path.join(curpath, "demo_api.xlsx") # 复制demo_api.xlsx文件到report下 report_path = os.path.join(os.path.dirname(curpath), "report") reportxlsx = os.path.join(report_path, "result.xlsx") testdata = ExcelUtil(testxlsx).dict_data() @ddt.ddt class Test_api(unittest.TestCase): @classmethod def setUpClass(cls): cls.s = requests.session() # 如果有登录的话,就在这里先登录了 copy_excel(testxlsx, reportxlsx) # 复制xlsx @ddt.data(*testdata) def test_api(self, data): # 先复制excel数据到report res = send_requests(self.s, data)
return res def write_result(result,filename="result.xlsx"): """返回结果行数:row_nub""" print (result) row_nub = result["rowNum"] # #写入statuscode wt = Write_excel(filename) wt.write(row_nub,8,result["statuscode"]) #第八列写入返回状态码 wt.write(row_nub,9,result["times"]) #耗时 wt.write(row_nub,10,result["error"]) #状态码非200时候返回结果 wt.write(row_nub,11,result["result"]) #返回结果是fail还是pass wt.write(row_nub,12,result["msg"]) #抛异常 if __name__=="__main__": data = ExcelUtil("debug_api.xlsx","Sheet1").dict_data() print (data[0]) s = requests.session() res = send_requests(s,data[0]) copy_excel("debug_api.xlsx","debug_api2.xlsx") write_result(res,filename="debug_api2.xlsx")
print("用例测试结果: %s---->%s" % (test_nub, res["result"])) else: res["result"] = "fail" return res except Exception as msg: #print(u'断点2') res["msg"] = str(msg) return res def wirte_result(result, filename="result.xlsx"): row_nub = result['rowNum'] wt = Write_excel(filename) wt.write(row_nub, 8, result['statuscode']) wt.write(row_nub, 9, result['times']) wt.write(row_nub, 10, result['error']) wt.write(row_nub, 12, result['result']) wt.write(row_nub, 13, result['msg']) if __name__ == "__main__": data = ExcelUtil("C:\\Users\Administrator\\PycharmProjects\\PostTest\\Testcase\\demo_api.xlsx", sheetName="Sheet1").dict_data() print(data[0]) s = requests.session() res = send_requests(s,data[0]) print(res) copy_excel("C:\\Users\Administrator\\PycharmProjects\\PostTest\\Testcase\\demo_api.xlsx", "C:\\Users\Administrator\\PycharmProjects\\PostTest\\report\\result.xlsx") wirte_result(res, filename="C:\\Users\Administrator\\PycharmProjects\\PostTest\\report\\result.xlsx")
import unittest import requests import ddt import os from api.qqfortune.qqfortune import QQFortune from common.readexcel import ExcelUtil p = os.path.dirname( os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) filepath = os.path.join(p, "data", "test_data_qqfortune.xlsx") sheetName = "Sheet1" data = ExcelUtil(filepath, sheetName) test_datas = data.dict_data() print(test_datas) @ddt.ddt class TestQQFortune(unittest.TestCase): def setUp(self): self.s = requests.session() self.qq = QQFortune(self.s) def tearDown(self): self.s.close() @ddt.data(*test_datas) def test_qqfortune(self, data): # 1. 准备数据 key = data["key"] qq = data["qq"]
#conding=utf-8 import time import unittest from selenium import webdriver from page.loginpage import LoginPage import ddt from common.readexcel import ExcelUtil filepath = r"C:\Users\ylzx\PycharmProjects\AUTOui\common\testdata.xlsx" data = ExcelUtil(filepath) testdata = (data.dict_data()) print(testdata) # testdata = [ # {"username":"******","pwd":"123456","res":"18612498560"}, # {"username":"******","pwd":"123123","res":"15810662774"} # ] @ddt.ddt class TestLogin(unittest.TestCase): u'''测试登录功能''' #开始 @classmethod def setUpClass(cls): cls.driver = webdriver.Firefox() cls.loginpage = LoginPage(cls.driver) t = time.strftime("%Y-%m-%d %H_%M_%S") print("用例开始执行" + t) #结束 @classmethod
return res def write_result(result, filename): row_num = result["rowNum"] wt = Write_excel(filename) wt.write("I" + str(row_num), result["statuscode"]) wt.write("J" + str(row_num), result["times"]) wt.write("K" + str(row_num), result["error"]) wt.write("M" + str(row_num), result["msg"]) wt.write("L" + str(row_num), result["result"]) wt.write("N" + str(row_num), result["content"]) if __name__ == "__main__": sheetName = "Sheet1" current_path = os.path.dirname(os.path.realpath(__file__)) testdate_path = os.path.join(os.path.dirname(current_path), "testdate") report_path = os.path.join(os.path.dirname(current_path), "report") filePath = os.path.join(testdate_path, "test.xlsx") filePath2 = os.path.join(report_path, "test_report.xlsx") #print(filePath) data = ExcelUtil(filePath, sheetName).dict_data() print(data[0]) s = requests.session() res = send_requests(s, data[1]) #print(res) copy_excel(filePath, filePath2) write_result(res, filePath2)