日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

python接口测试-项目实践(八) 完成的接口类和执行脚本

發(fā)布時(shí)間:2024/9/5 python 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python接口测试-项目实践(八) 完成的接口类和执行脚本 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

脫敏后腳本

?

projectapi.py: 項(xiàng)目接口類

# -*- coding:utf-8 -*- """ xx項(xiàng)目接口類 2018-11 dinghanhua """import requests import re import pymssql#region 工具類函數(shù) def findinfo_from_apiquerystockdetailinfo(str1,str2):"""從str1中找第一個(gè)"str2":...后面的值:param str1::param str2::return: str2對(duì)應(yīng)的值"""pattern1 = '"'+str2 + '":(.*?),"' #左右邊界result = re.search(pattern1, str1) #正則匹配if result:result = result.group(1).replace('"','')return resultdef get_last_value_of_key(resultlist,key):'''從二維數(shù)組取第一行的元素對(duì)應(yīng)的最后一行的值:param resultlist::param key::return: value'''for i in range(0,len(resultlist[0])):if key == resultlist[0][i]: #第一行中找到對(duì)應(yīng)字段名的索引result = resultlist[-1][i]return result #返回?cái)?shù)組最后一行對(duì)應(yīng)的值def round_test(data,i=0):'''四舍五入,解決round(7.35)=7.3的問題:param data::param i: 保留的位數(shù),默認(rèn)保留一位小數(shù):return:'''if isinstance(i,int): #i是整數(shù)raise Exception('the second param must be int')else:mi = 10**if = data*mi - int(data*mi)if f >=0.5:res = (int(data*mi)+1)/mielif f <=-0.5:res = (int(data*mi-1))/mielse:res = int(data*mi)/miif i<=0:res = int(res)return res # endregionclass ProjectApi:def api_querystockdetailinfo(self,stockcode):"""請(qǐng)求并提取股票基本信息接口數(shù)據(jù):param stockcode::return: 截取信息dict"""api = 'http://testdomain/querystockdetailinfo?stockcode={stockcode}'.format(stockcode = stockcode)response = requests.get(api)result = response.text.replace(r'\n','').replace('\\', '') # 去掉特殊字符\n,\result_dict = {'stockcode': stockcode}#股票名稱result_dict['StockName'] = findinfo_from_apiquerystockdetailinfo(result, 'StockName')if result_dict['StockName']: #股票名稱存在繼續(xù)處理其他字段,否則報(bào)錯(cuò)并返回# 公司概要 #剔除公司概要中“公司”“公司是”、“公司是一家”高度重復(fù)的內(nèi)容overviewvalue = result_dict['OverviewValue'] = findinfo_from_apiquerystockdetailinfo(result, 'OverviewValue')if overviewvalue.startswith('公司是一家'):result_dict['OverviewValue'] = overviewvalue[5:]elif overviewvalue.startswith('公司是'):result_dict['OverviewValue'] = overviewvalue[3:]elif overviewvalue.startswith('公司'):result_dict['OverviewValue'] = overviewvalue[2:]if not overviewvalue.endswith('。'): #判斷最后是否有句號(hào),沒有加一個(gè)result_dict['OverviewValue'] += '。'# 市值typecap = findinfo_from_apiquerystockdetailinfo(result, 'TypeCap')dictcap = {'1': '巨盤', '2': '大盤', '3': '中盤', '4': '小盤', '5': '微盤'}result_dict['TypeCap'] = dictcap[typecap]# 風(fēng)格TypeStyle = result_dict['TypeStyle'] = findinfo_from_apiquerystockdetailinfo(result, 'TypeStyle')dictstyle = {'1': '成長(zhǎng)', '2': '價(jià)值', '3': '周期', '4': '題材', '5': '高價(jià)值'}if len(TypeStyle) == 1:result_dict['TypeStyle'] = dictstyle[TypeStyle]elif len(TypeStyle) >1:typestylelist = TypeStyle.split(',') #風(fēng)格可能有多個(gè)for t in range(len(typestylelist)):typestylelist[t] = dictstyle[typestylelist[t]]result_dict['TypeStyle'] = '、'.join(typestylelist)# 生命周期 LifecycleValue 生命周期(單選,例:1);(1初創(chuàng)期、2成長(zhǎng)期、3成熟期、4衰退期)")LifecycleValue = findinfo_from_apiquerystockdetailinfo(result, 'LifecycleValue')dictlifecycle = {'1': '初創(chuàng)期', '2': '成長(zhǎng)期', '3': '成熟期', '4': '衰退期', '5': '周期底部', '6': '周期頂部', '7': '周期向下', '8': '周期向上'}if LifecycleValue:result_dict['LifecycleValue'] = dictlifecycle[LifecycleValue]# 估值 ScoreTTM 估值(分值1~5,>=4 偏低, <=2 偏高,其他適中)")ScoreTTM = findinfo_from_apiquerystockdetailinfo(result, 'ScoreTTM')if ScoreTTM:if float(ScoreTTM) >= 4:result_dict['ScoreTTM'] = '偏低'elif ScoreTTM and float(ScoreTTM) <= 2:result_dict['ScoreTTM'] = '偏高'else:result_dict['ScoreTTM'] = '適中'# 成長(zhǎng)指數(shù) ScoreGrowing 成長(zhǎng)指數(shù)(分值1~5,>=4 高, <=2 低,其他中)')ScoreGrowing = findinfo_from_apiquerystockdetailinfo(result, 'ScoreGrowing')if ScoreGrowing:if float(ScoreGrowing) >= 4:result_dict['ScoreGrowing'] = ''elif float(ScoreGrowing) <= 2:result_dict['ScoreGrowing'] = ''else:result_dict['ScoreGrowing'] = ''else:result_dict['ScoreGrowing']=''# 盈利能力ScoreProfit = findinfo_from_apiquerystockdetailinfo(result, 'ScoreProfit') # ' ScoreProfit 盈利能力(分值1~5,>=4 高, <=2 低,其他中)' )if ScoreProfit:if float(ScoreProfit) >= 4:result_dict['ScoreProfit'] = ''elif float(ScoreProfit) <= 2:result_dict['ScoreProfit'] = ''else:result_dict['ScoreProfit'] = ''else:result_dict['ScoreProfit']=''return result_dictdef api_finance(self,stockcode):"""請(qǐng)求并提取財(cái)務(wù)數(shù)據(jù):param stockcode::return: dict"""api = 'http://testdomain/finance?stockcode={stockcode}'.format(stockcode = stockcode)response = requests.get(api)response.encoding = 'utf-8-sig'result = response.json()['data'][0]['result'] # 轉(zhuǎn)化為二位數(shù)組result_dict = {'stockcode': stockcode} #存儲(chǔ)返回結(jié)果if len(result) <3: #說明股票沒數(shù)據(jù)return result_dict# 當(dāng)期報(bào)告期result_dict['EndDate'] = get_last_value_of_key(result, 'EndDate')# 預(yù)測(cè)收益報(bào)告期ReportPeriod = get_last_value_of_key(result, 'ReportPeriod')dictreportperoid = {'03/31': '一季度', '06/30': '上半年', '09/30': '前三季度', '12/31': '本年度'}if ReportPeriod and ReportPeriod != result_dict['EndDate']: #預(yù)測(cè)收益報(bào)告期不等于當(dāng)期報(bào)告期ReportPeriod = get_last_value_of_key(result, 'ReportPeriod')[5:10]result_dict['ReportPeriod'] = dictreportperoid[ReportPeriod]else:result_dict['ReportPeriod'] = ''# 預(yù)測(cè)業(yè)績(jī)情況PerformanceType = get_last_value_of_key(result, 'PerformanceType')result_dict['PerformanceType'] = PerformanceType# 預(yù)測(cè)業(yè)績(jī)比例result_dict['PerformanceTypeRange'] = get_last_value_of_key(result, 'PerformanceTypeRange')# 營(yíng)業(yè)收入增長(zhǎng)率result_dict['OperatingRevenueYoY'] = get_last_value_of_key(result, 'OperatingRevenueYoY')# 營(yíng)業(yè)利潤(rùn)增長(zhǎng)率result_dict['NetProfitYoY'] = get_last_value_of_key(result, 'NetProfitYoY')# 凈資產(chǎn)收益率result_dict['ROE'] = get_last_value_of_key(result, 'ROE')# 毛利率result_dict['SalesGrossMargin'] = get_last_value_of_key(result, 'SalesGrossMargin')return result_dictdef api_quote(self,stockcode):"""請(qǐng)求并提取PETTM:param stockcode::return: dict"""api = 'http://testdomain/quote?stockcode={stockcode}'.format(stockcode=stockcode)response = requests.get(api)response.encoding = 'utf-8-sig'result = response.json()['data'][0]['result'] # 轉(zhuǎn)化為二位數(shù)組result_dict = {'stockcode':stockcode}if len(result) <3: #說明股票沒數(shù)據(jù)return result_dictresult_dict['PETTM'] = get_last_value_of_key(result, 'PE1')return result_dictdef result_of_3sourceapi(self,stockcode):"""拼接3個(gè)接口取出的字串:param stockcode::return:"""result_stockdetailinfo = self.api_querystockdetailinfo(stockcode)if result_stockdetailinfo['StockName']: #如果股票名稱存在,執(zhí)行后續(xù)步驟result_finance = self.api_finance(stockcode)result_quote = self.api_quote(stockcode)#顯示三個(gè)接口結(jié)果#print(result_stockdetailinfo)#print(result_finance)#print(result_quote)#空值、精度處理OperatingRevenueYoY = round_test(float(result_finance['OperatingRevenueYoY']),1)NetProfitYoY = round_test(float(result_finance['NetProfitYoY']),1)if result_finance['ReportPeriod'] ==''\or result_finance['PerformanceType'] == ''\or result_finance['PerformanceTypeRange'] == '':ReportPeriod = PerformanceType = PerformanceTypeRange = ''else:ReportPeriod = ',預(yù)計(jì)' + result_finance['ReportPeriod']PerformanceType = '業(yè)績(jī)' + result_finance['PerformanceType']PerformanceTypeRange = result_finance['PerformanceTypeRange']if result_finance['ROE']:ROE = ',凈資產(chǎn)收益率:{0}%'.format(round_test(float(result_finance['ROE']),1))else:ROE = ''if result_finance['SalesGrossMargin']:SalesGrossMargin = ',毛利率:{0}%'.format(round_test(float(result_finance['SalesGrossMargin']),1))else:SalesGrossMargin = ''result = '{OverviewValue} {TypeCap}{TypeStyle}股,處于{LifecycleValue}。' \'估值{ScoreTTM},PE(TTM):{PETTM};' \'成長(zhǎng)性{ScoreGrowing},當(dāng)期營(yíng)收增長(zhǎng):{OperatingRevenueYoY}%,當(dāng)期利潤(rùn)增長(zhǎng):{NetProfitYoY}%;' \'盈利能力{ScoreProfit}{ROE}{SalesGrossMargin}{ReportPeriod}{PerformanceType}{PerformanceTypeRange}。'\.format(OverviewValue = result_stockdetailinfo['OverviewValue'],TypeCap = result_stockdetailinfo['TypeCap'],TypeStyle = result_stockdetailinfo['TypeStyle'],LifecycleValue = result_stockdetailinfo['LifecycleValue'],ScoreTTM = result_stockdetailinfo['ScoreTTM'],PETTM = round_test(float(result_quote['PETTM'])),ScoreGrowing = result_stockdetailinfo['ScoreGrowing'],OperatingRevenueYoY = OperatingRevenueYoY,NetProfitYoY = NetProfitYoY,ScoreProfit = result_stockdetailinfo['ScoreProfit'],ROE = ROE,SalesGrossMargin=SalesGrossMargin,ReportPeriod = ReportPeriod,PerformanceType = PerformanceType,PerformanceTypeRange = PerformanceTypeRange)return resultelse:return '不存在該股票數(shù)據(jù)'def api_of_dev(self,stockcodelist,cookie,page=0,domain='testdomain.cn'):"""獲取開發(fā)接口數(shù)據(jù):param 股票列表;cookie;domain默認(rèn)線上:return: 股票代碼及數(shù)據(jù)"""headers = {'Cookie':cookie}url = 'http://{domain}/getstockbypage?StockCodeList={stockcodelist}&PageIndex={page}&PageSize=10'.format(stockcodelist = stockcodelist,domain = domain,page=page)response = requests.get(url, headers=headers)jsonstr = response.json()# 轉(zhuǎn)成json,取出messagemessage = jsonstr['Message']dict_result = {}if message:for ele in message:stockcode = ele['StockCode']content = ele['Content'] # 實(shí)際結(jié)果nickname = ele['NickName'] #發(fā)布者if nickname == 'project000':dict_result[stockcode] = contentreturn dict_resultdef compare_vs_devapi(self,stockcodelist,cookie,page=0,domain='testdomain.cn'):"""開發(fā)接口數(shù)據(jù)與接口拼接數(shù)據(jù)對(duì)比:return: bool"""diff_list = [] # 存儲(chǔ)不一致的股票代碼 resultofdev = self.api_of_dev(stockcodelist,cookie,page,domain) #請(qǐng)求開發(fā)接口if resultofdev: #如果開發(fā)結(jié)果不為空for stock,actual in resultofdev.items():expected = self.result_of_3sourceapi(stock) #數(shù)據(jù)源拼接結(jié)果'''去掉pe(ttm)對(duì)比'''beginindex = actual.find('PE(TTM)')endindex = actual.find('', beginindex)actual_result = actual[:beginindex] + actual[endindex:]beginindex = expected.find('PE(TTM)')endindex = expected.find('', beginindex)expected_result = expected[:beginindex] + expected[endindex:]if actual_result != expected_result: #預(yù)期實(shí)際對(duì)比print(stock)print('開發(fā):',actual_result)print('預(yù)期:',expected_result)diff_list.append(stock)else:print(stock,'一致(不含PETTM)')if diff_list: #異常股票列表不為空則輸出;空則提示全部一致print('不一致的股票列表:', diff_list)return Falseelse:print('對(duì)比結(jié)果:數(shù)據(jù)一致')return Trueelse:print('接口沒有數(shù)據(jù)')return Truedef compare_vs_database(self,count=10):"""比較數(shù)據(jù)庫數(shù)據(jù)與數(shù)據(jù)源拼接字串:param count:對(duì)比股票數(shù)量,default=10:return:True 一致;False 不一致"""diff_list = [] # 存儲(chǔ)不一致的股票代碼 with pymssql.connect(server='192.168.1.1', user='sa', password='sa',database='test_db') as myconnect:with myconnect.cursor(as_dict=True) as cursor:cursor.execute("""SELECT top {count} StockCode,StockName,content FROM [test_db].[dbo].[table] where NickName ='project000' and isvalid = 1 and IsDeleted =0 order by createtime desc""".format(count=count))for row in cursor:stockcode = row['StockCode']actual = row['content']expected = self.result_of_3sourceapi(stockcode) # 數(shù)據(jù)源拼接結(jié)果'''去掉pe(ttm)對(duì)比'''beginindex = actual.find('PE(TTM)')endindex = actual.find('', beginindex)actual_result = actual[:beginindex] + actual[endindex:]beginindex = expected.find('PE(TTM)')endindex = expected.find('', beginindex)expected_result = expected[:beginindex] + expected[endindex:]if actual_result != expected_result: # 預(yù)期實(shí)際對(duì)比print(stockcode)print('開發(fā):', actual_result)print('預(yù)期:', expected_result)diff_list.append(stockcode)else:print(stockcode, '一致(不含PETTM)')if diff_list:print('不一致的股票列表:', diff_list)return Falseelse:print('對(duì)比結(jié)果:數(shù)據(jù)全部一致')return True

?

?

run_test.py 執(zhí)行腳本:

# coding:utf-8 """ 接口測(cè)試執(zhí)行腳本 """import projectapi import unittestclass ApiTest(unittest.TestCase):def setUp(self):self.projectapi1 = projectapi.ProjectApi() # 創(chuàng)建接口對(duì)象def testcase1(self):"""與開發(fā)接口比對(duì)"""stockcodelist = '600000%2C600128%2C600146%2C600165%2C600186'#通過抓包獲取cookiecookie = 'globalid=24A85DEC-AF25-36DD-C774-ED092F705767'testresult = self.projectapi1.compare_vs_devapi(stockcodelist,cookie)self.assertTrue(testresult)def testcase2(self):# 與數(shù)據(jù)庫對(duì)比testresult = self.projectapi1.compare_vs_database(count=10)self.assertTrue(testresult)def testcase3(self):"""手工查詢?cè)瓟?shù)據(jù)和拼接字串"""while True:stockcode = input('輸入股票代碼: ')if stockcode.isdigit() and len(stockcode)==6 and stockcode[:2] in ('00','60','30'):print('數(shù)據(jù)請(qǐng)求中.....')print(self.projectapi1.api_quote(stockcode))print(self.projectapi1.api_finance(stockcode))print(self.projectapi1.api_querystockdetailinfo(stockcode))print(self.projectapi1.result_of_3sourceapi(stockcode))else:print('股票代碼有誤')

?

轉(zhuǎn)載于:https://www.cnblogs.com/dinghanhua/p/10376705.html

總結(jié)

以上是生活随笔為你收集整理的python接口测试-项目实践(八) 完成的接口类和执行脚本的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。