1. 程式人生 > >接口測試第三階段代碼

接口測試第三階段代碼

ret 發送 .com sta request ner 註冊 字符串 cookies

目錄結構:

技術分享圖片

目標:

代碼分類管理。

common. package 放公共代碼

test_data 文件夾放所有測試數據,api.xlsx,case.config

test_result 文件夾放測試結果,report.(html報告)log(日誌文件)

目標一、實現接口路徑的讀取

目標二、發送郵件

目標三:加入日誌

目標四、實現登錄後充值,獲取cookies

目標一、讀取路徑首先講文件的絕對路徑獲取出來

1)相對路徑:不建議使用,不靈活,當文件位置更改或更換其他電腦設備,代碼運行不了的風險

2)絕對路徑:建議使用

新增project_path.py,代碼內容如下

__author__ = ‘林越‘
__author__ = ‘zz‘
# 讀取文件路徑
import os
# print(os.path.split(os.path.split(os.path.realpath(__file__))[0])[0])
# a = os.path.os.path.realpath(__file__) # 獲取當前文件的絕對路徑
# b = (os.path.split(os.path.os.path.realpath(__file__))[0]) # 拆分路徑後,字符串取值。

Project_path = (os.path.split(os.path.split(os.path.realpath(__file__))[0])[0])

# print(Project_path)

case_config_path = os.path.join(Project_path, "test_data", "case.config") # 拼接地址
# print(case_config_path)

html_path = os.path.join(Project_path, "test_result","report", "test_result.html")
# print(html_path)

test_data_path = os.path.join(Project_path,"test_data", "api.xlsx")
# print(test_data_path)


test_log_path = os.path.join(Project_path,"test_data", "my_log.txt")
# print(test_log_path)

路徑獲取到了,需要變更文件中路徑。(標紅的是變更處)

read_config.py 配置文件更改:

from configparser import ConfigParser
from class_2019_API_unnitest.common import project_path


class ReadConfig:

def read_config(self, filename, section, option):

cf = ConfigParser()
cf.read(filename)
value = cf.get(section, option)
return value


if __name__ == ‘__main__‘:

res = ReadConfig().read_config(project_path.case_config_path, "CONFIG", "button")
res2 = ReadConfig().read_config(project_path.case_config_path, "CONFIG", "case_id_list")
print(res2)

test_api.py文件路徑更改
import unittest

from ddt import ddt, data
from class_2019_API_unnitest.common.new_do_excle import DoExcl
from class_2019_API_unnitest.common.http_request import HttpMethod
from class_2019_API_unnitest.common.read_config import ReadConfig
from class_2019_API_unnitest.common import project_path
from class_2019_API_unnitest.common.my_log import MyLog
button = ReadConfig().read_config(project_path.case_config_path, "CONFIG", "button")
case_id_list = ReadConfig().read_config(project_path.case_config_path, "CONFIG", "case_id_list")
test_data = DoExcl(project_path.test_data_path).get_data(button, case_id_list)
print(button)

logger = MyLog()
COOKIES = None # 聲明一個全局變量
@ddt
class TestApi(unittest.TestCase):

def setUp(self):

self.t = DoExcl(project_path.test_data_path)
logger.info("開始測試")

@data(*test_data)
def test_api(self, data_item):
global COOKIES
logger.info("正在執行第{0}條測試用例{1}".format(data_item[‘id‘],data_item[‘description‘]))
logger.info("測試數據是{0}".format(data_item[‘param‘]))

res = HttpMethod().http_request(data_item[‘url‘], eval(data_item[‘param‘]), data_item[‘HttpMethod‘], COOKIES) # eval()函數將字符串轉換成字典

if res.cookies:
COOKIES = res.cookies

logger.info("測試結果是:{0}".format(res.json()))

try:
self.assertEqual(str(data_item["ExpectedResult"]),res.json()[‘code‘])
TestResult = ‘PASS‘
except AssertionError as e:
TestResult = ‘failed‘
raise e
finally:
self.t.write_back(data_item["id"]+1, res.json()[‘code‘], TestResult)

def tearDown(self):
# print("測試結束了")
logger.info("測試結束了")

目標二:生成測試報告,發送郵件到郵箱
拓展知識點:賬號授權碼獲取方式
在common中,新增一個send_emali.py 模版,已經寫好的
run.py文件中倒入引用:
import unittest
from class_2019_API_unnitest.common import test_api
from class_2019_API_unnitest.common import project_path
from class_2019_API_unnitest.common.send_email import sendEmail
import HTMLTestRunnerNew

suite = unittest.TestSuite()
loader = unittest.TestLoader()
suite.addTest(loader.loadTestsFromModule(test_api))
with open (project_path.html_path, "wb+") as file:
runner = HTMLTestRunnerNew.HTMLTestRunner(file, title=‘測試報告‘, description=‘軟件測試‘, tester=‘林越‘)
runner.run(suite)

# sendEmail().send_email("[email protected]",project_path.html_path)

目標三:生成日誌(現在日誌文件沒有寫入到文件中)??
在common中新增my_log.py文件,模版是老師已經寫好的
在http_request.py文件中倒入並引用
在test_api.py文件中倒入並引導

目標四:實現登錄後充值
拓展知識:
了解什麽是:cookies,session,token
{}字典獲取不到cookies,返回值不能是字典或者列表。。
http_requst.py
import requests
from class_2019_API_unnitest.common.my_log import MyLog
logger = MyLog()


class HttpMethod:

def http_request(self,url,param,http_method, cookies): # 傳遞cookies參數
if http_method.upper() ==‘POST‘:

try:

res = requests.post(url, param, cookies = cookies) # 傳遞cookies參數
logger.info("正在進行post請求")
except Exception as e:
logger.error("post註冊請求出錯,錯誤是{}".format(e))
# print("post註冊請求出錯,錯誤是{}".format(e))

else:

try:
res = requests.get(url, param, cookies = cookies) # 傳遞cookies參數
logger.info("正在進行get請求")
except Exception as e:
logger.error("post註冊請求出錯,錯誤是{}".format(e))

return res # 增加返回值,在請求正常的情況下有返回值

test_api.py
import unittest

from ddt import ddt, data
from class_2019_API_unnitest.common.new_do_excle import DoExcl
from class_2019_API_unnitest.common.http_request import HttpMethod
from class_2019_API_unnitest.common.read_config import ReadConfig
from class_2019_API_unnitest.common import project_path
from class_2019_API_unnitest.common.my_log import MyLog
button = ReadConfig().read_config(project_path.case_config_path, "CONFIG", "button")
case_id_list = ReadConfig().read_config(project_path.case_config_path, "CONFIG", "case_id_list")
test_data = DoExcl(project_path.test_data_path).get_data(button, case_id_list)
print(button)

logger = MyLog()
COOKIES = None # 聲明一個全局變量
@ddt
class TestApi(unittest.TestCase):

def setUp(self):

self.t = DoExcl(project_path.test_data_path)
logger.info("開始測試")

@data(*test_data)
def test_api(self, data_item):
global COOKIES
logger.info("正在執行第{0}條測試用例{1}".format(data_item[‘id‘],data_item[‘description‘]))
logger.info("測試數據是{0}".format(data_item[‘param‘]))

res = HttpMethod().http_request(data_item[‘url‘], eval(data_item[‘param‘]), data_item[‘HttpMethod‘], COOKIES) # eval()函數將字符串轉換成字典

if res.cookies: # http_request.py返回的res可以獲取到cookies,如果res.cookies為真,COOKIES = res.cookies 為假,COOKIES=NONE
COOKIES = res.cookies # 在用戶登錄後就會獲取到cookies,在充值

logger.info("測試結果是:{0}".format(res.json()))

try:
self.assertEqual(str(data_item["ExpectedResult"]),res.json()[‘code‘])
TestResult = ‘PASS‘
except AssertionError as e:
TestResult = ‘failed‘
raise e
finally:
self.t.write_back(data_item["id"]+1, res.json()[‘code‘], TestResult)

def tearDown(self):
# print("測試結束了")
logger.info("測試結束了")

 
 

接口測試第三階段代碼