python接口自動化測試二十五:執行所有用例,並生成HTML測試報告


 

 

 

 

import requests
import unittest

class TestQQ(unittest.TestCase):
    
'''測試QQ號接口'''      # 此注釋將展示到測試報告的測試組類

    def test_qq(self):
        
'''測試QQ號碼,正確的appkey'''      # 此注釋將展示到測試報告的用例標題
        url 'http://japi.juhe.cn/qqevaluate/qq'
        
par {
                
'key''8dbee1fcd8627fb6699bce7b986adc45',
                'qq''907728701'
              
}
        
# 發送post請求
        r requests.post(url, params=par)
        
print(r.text)     # 獲取返回的結果
        result r.json()['reason']
        
print(result)
        
# 斷言
        self.assertTrue('success' == result)    # 斷言:'success' == result
        self.assertTrue('success' in r.text)    # 斷言:'success' 在 r.text的返回內容里面
        self.assertIn('success', r.text)        # 斷言:'success' 在 r.text的返回內容里面
        # 斷言:'success' == result
        self.assertEqual('success', result, msg='失敗的時候,打印這里')


    
def test_qq_appker_error(self):
        
'''測試QQ號碼,錯誤的appkey'''      # 此注釋將展示到測試報告的用例標題
        url 'http://japi.juhe.cn/qqevaluate/qq'
        
par {
                
'key''8dbee1fcd8627fb6699bce7b986adc45',
                'qq''907728701'
              
}
        
# 發送post請求
        r requests.post(url, params=par)
        
print(r.text)     # 獲取返回的結果
        result r.json()['reason']
        
print(result)
        
# 斷言
        self.assertTrue('success' == result)    # 斷言:'success' == result
        self.assertTrue('success' in r.text)    # 斷言:'success' 在 r.text的返回內容里面
        self.assertIn('success', r.text)        # 斷言:'success' 在 r.text的返回內容里面
        # 斷言:'success' == result
        self.assertEqual('success', result, msg='失敗的時候,打印這里')

if __name__ == '__main__':
    
unittest.main

 

 

import requests
import unittest

class TestWeather(unittest.TestCase):
   
'''測試天氣預報接口'''       # 此注釋將展示到測試報告的測試組類
    def test_Weather(self):
       
'''可用次數超限'''         # 此注釋將展示到測試報告的用例標題
        url = "http://v.juhe.cn/weather/index"
       
par = {
           
"cityname": "深圳",  # 城市名或城市ID,如:"蘇州",需要utf8 urlencode
            "dtype": "json",     # 返回數據格式:json或xml,默認json
            "format": "1",       # 未來7天預報(future)兩種返回格式,1或2,默認1
            "key": "80b4d4e1d870d257d3344fcf2d08f64a"    # key須申請
              }
       
r = requests.get(url, params=par)
       
print(r.text)     # 獲取返回的結果
        result = r.json()['reason']
       
print(result)
       
# 斷言
        self.assertEqual('reason', result)
       
self.assertIn('reason', r.text)
       
self.assertTrue('reason'in r.text)

   
def test_Weather_appkey_error(self):
       
'''錯誤的key'''        # 此注釋將展示到測試報告的用例標題
        url = "http://v.juhe.cn/weather/index"
       
par = {
           
"cityname": "深圳",  # 城市名或城市ID,如:"蘇州",需要utf8 urlencode
            "dtype": "json",     # 返回數據格式:json或xml,默認json
            "format": "1",       # 未來7天預報(future)兩種返回格式,1或2,默認1
            "key": "8dfghfhgfhgfh"    # key須申請
              }
       
r = requests.get(url, params=par)
       
print(r.text)     # 獲取返回的結果
        result = r.json()['reason']
       
print(result)
       
# 斷言
        self.assertEqual('reason', result)
       
self.assertIn('reason', r.text)
       
self.assertTrue('reason'in r.text)

 

 

# run_all_case
import unittest
import os
# 從工程下面的第一層開始導入
from common.HtmlTestRunner import HTMLTestRunner
# 用例存放的路徑
# startdir = 'D:\PycharmProjects\interface\case'  # 絕對路徑,容易出錯

# 獲取當前腳本的路徑
curPath = os.path.dirname(os.path.realpath(__file__))     # 獲取文件路徑
startdir = os.path.join(curPath, 'case')    # 測試用例路徑
# 獲取測試報告:'report.html'路徑
reportPath = os.path.join(curPath, 'report', 'report.html')

# 匹配規則
rule = 'test*.py'
discover = unittest.defaultTestLoader.discover(startdir, rule)
print(discover)

# 生成HTML格式的報告
fp = open(reportPath, 'wb'# 把測試報告以二進制的規則寫進“report_report.html”文件中
runner = HTMLTestRunner(fp,
                        title='鍾葉海的接口測試報告',    # 報告標題
                        description='報告如下:',     # 報告的描述
                        verbosity=2,    # 將注釋在測試用例中展示
                        retry=1         # 失敗后,重跑1次(次數可隨意更改)
                        )
runner.run(discover)
fp.close()      # 寫完后關閉HTML報告

# 生成TXT格式的報告
# runner = unittest.TextTestRunner()
# runner .run(discover)

 

 

 

# 運行所有用例,以郵件發送結果

# coding=utf-8
# run_and_send_email
import unittest
import time
from common.HtmlTestRunner import HTMLTestRunner
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib
import os

# ####下面三行代碼python2報告出現亂碼時候可以加上####

# python2須加此三條
# import sys
# reload(sys)
# sys.setdefaultencoding('utf8')

# 這個是優化版執行所有用例並發送報告,分四個步驟
# 第一步加載用例
# 第二步執行用例
# 第三步獲取最新測試報告
# 第四步發送郵箱 (這一步不想執行的話,可以注釋掉最后面那個函數就行)

# 當前腳本所在文件真實路徑
cur_path os.path.dirname(os.path.realpath(__file__))


def add_case(caseName="case", rule="test*.py"):
    
'''第一步:加載所有的測試用例'''
    
case_path os.path.join(cur_path, caseName)  # 用例文件夾
    # 如果不存在這個case文件夾,就自動創建一個
    if not os.path.exists(case_path)os.mkdir(case_path)
    
print("test case path:%s" case_path)
    
# 定義discover方法的參數
    discover unittest.defaultTestLoader.discover(case_path,
                                                   pattern=rule,
                                                   top_level_dir=None)
    
print(discover)
    
return discover


def run_case(all_case, reportName="report"):
    
'''第二步:執行所有的用例, 並把結果寫入HTML測試報告'''
    
now time.strftime("%Y_%m_%d_%H_%M_%S")
    
report_path os.path.join(cur_path, reportName)  # 用例文件夾
    # 如果不存在這個report文件夾,就自動創建一個
    if not os.path.exists(report_path)os.mkdir(report_path)
    
report_abspath os.path.join(report_path, "result.html")
    
print("report path:%s" report_abspath)
    
fp open(report_abspath, "wb")
    
runner HTMLTestRunner(fp,
                            title='報告的標題:這個是我的接口項目',  # 報告標題
                            description='報告如下:',  # 報告的描述
                            verbosity=2,  # 將注釋在測試用例中展示
                            retry=1  # 失敗后,重跑1次(次數可隨意更改)
                            )

    
# 調用add_case函數返回值
    runner.run(all_case)
    
fp.close()


def get_report_file(report_path):
    
'''第三步:獲取最新的測試報告'''
    
lists os.listdir(report_path)
    
lists.sort(key=lambda fnos.path.getmtime(os.path.join(report_path, fn)))
    
print(u'最新測試生成的報告: ' lists[-1])
    
# 找到最新生成的報告文件
    report_file os.path.join(report_path, lists[-1])
    
return report_file


def send_mail(sender, psw, receiver, smtpserver, report_file, port):
    
'''第四步:發送最新的測試報告內容'''
    
with open(report_file, "rb"as f:
        
mail_body f.read()
    
# 定義郵件內容
    msg MIMEMultipart()
    
body MIMEText(mail_body, _subtype='html', _charset='utf-8')
    
msg['Subject'] = u"自動化測試報告"
    
msg["from"] = sender
    msg["to"] = str(receiver)  # 只能字符串
    msg.attach(body)
    
# 添加附件
    att MIMEText(open(report_file, "rb").read()"base64""utf-8")
    
att["Content-Type"] = "application/octet-stream"
    
att["Content-Disposition"] = 'attachment; filename= "report.html"'
    
msg.attach(att)
    
try:
        
smtp smtplib.SMTP()
        
smtp.connect(smtpserver)  # 連服務器
        smtp.login(sender, psw)
    
except:
        
smtp smtplib.SMTP_SSL(smtpserver, port)
        
smtp.login(sender, psw)  # 登錄
    smtp.sendmail(sender, receiver, msg.as_string())
    
smtp.quit()
    
print('test report email has send out !')


if __name__ == "__main__":
    
all_case add_case()  # 1加載用例
    # # 生成測試報告的路徑
    run_case(all_case)  # 2執行用例
    # # 獲取最新的測試報告文件
    report_path os.path.join(cur_path, "report")  # 用例文件夾
    report_file get_report_file(report_path)  # 3獲取最新的測試報告
    # #郵箱配置
    # sender = "yoyo@qq.com"
    # psw = "xxx"
    # smtp_server = "smtp.qq.com"
    # port = 465
    # receiver = "yoyo@qq.com"
    # send_mail(sender, psw, receiver, smtp_server, report_file, port)  # 4最后一步發送報告

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM