先上代码
#data_test.py
from openpyxl import load_workbook
class Date_test():
@classmethod
def Date_test_1(cls):
"""
配置文件读取模块
:return:
"""
wb = load_workbook("data_test.xlsx")
ws = wb["Sheet1"]
url = 'http://localhost/api'
list1 = []
for i in range(1, ws.max_row + 1):
list = []
for j in range(1, ws.max_column + 1):
if j == 3:
str = url + ws.cell(i, j).value
else:
str = ws.cell(i, j).value
list.append(str)
list1.append(list)
wb.close()
Dict = {}
for i in list1:
str = ",".join(i)
list = []
list = str.split(",",1)
Dict[list[0]] = list[1]
return Dict
def Date_test_2(self,test_function,test_text,x):
"""
运行结果写入模块
:param test_function:
:param test_text:
:param x:
:return:
"""
wb = load_workbook("data_test.xlsx")
ws = wb["Sheet2"]
ws.cell(x,1).value = test_function
ws.cell(x,2).value = test_text
wb.save("data_test.xlsx")
wb.close()
@staticmethod
def Email_Date():
username = "username"
password = "password"
To_Email = "from_email_1,from_email_2"
return username,password,To_Email
#Http_pg.py
import requests
class HTTP_CONSOLE():
def http_console(self,Method,url,parameter,Cookies= None):
if Method == "POST":
result = requests.get(url=url,params=parameter,cookies=Cookies)
elif Method =="GET":
result = requests.post(url=url,data=parameter,cookies=Cookies)
else:
print("请求方式输入错误,目前仅支持POST/GET两种请求方式!")
return result
#test_case.py
from data_test import *
from Http_pg import *
import json
import unittest
class test_case(unittest.TestCase):
@classmethod
def setUp(cls):
cls.Cookie = test_case().test_login()
@classmethod
def tearDown(cls):
print("测试用例执行完毕")
def test_register(self):
str = Date_test.Date_test_1()["register"]
list = str.split(",")
Method = list[0]
url = list[1]
Dict_login = {}
Dict_login["mobilephone"] = eval(list[2])
Dict_login["pwd"] = eval(list[3])
result = HTTP_CONSOLE().http_console(Method=Method, url=url, parameter=Dict_login)
Date_test().Date_test_2(test_function="register",test_text=json.loads(result.text)["msg"],x=1)
# self.assertEqual(json.loads(result.text)["msg"],"注册成功")
self.assertEqual(json.loads(result.text)["msg"],"手机号码已被注册")
def test_login(self):
str = Date_test.Date_test_1()["login"]
list = str.split(",")
Method = list[0]
url = list[1]
Dict_login= {}
Dict_login["mobilephone"] = eval(list[2])
Dict_login["pwd"] = eval(list[3])
result = HTTP_CONSOLE().http_console(Method=Method,url=url,parameter=Dict_login)
self.Cookie = result.cookies
Date_test().Date_test_2(test_function="login", test_text=json.loads(result.text)["msg"],x=2)
self.assertEqual(json.loads(result.text)["msg"],"登录成功")
return self.Cookie
def test_recharge(self):
str = Date_test.Date_test_1()["recharge"]
list = str.split(",")
Method = list[0]
url = list[1]
Dict_login = {}
Dict_login["mobilephone"] = eval(list[2])
Dict_login["amount"] = eval(list[3])
result = HTTP_CONSOLE().http_console(Method=Method, url=url, parameter=Dict_login,Cookies = self.Cookie)
Date_test().Date_test_2(test_function="recharge", test_text=json.loads(result.text)["msg"], x=3)
self.assertEqual(json.loads(result.text)["msg"], "充值成功")
def test_withdraw(self):
str = Date_test.Date_test_1()["withdraw"]
list = str.split(",")
Method = list[0]
url = list[1]
Dict_login = {}
Dict_login["mobilephone"] = eval(list[2])
Dict_login["amount"] = eval(list[3])
result = HTTP_CONSOLE().http_console(Method=Method, url=url, parameter=Dict_login,Cookies = self.Cookie)
Date_test().Date_test_2(test_function="withdraw", test_text=json.loads(result.text)["msg"], x=4)
self.assertEqual(json.loads(result.text)["msg"], "取现成功")
if __name__ == '__main__':
unittest.main()
#Email_test.py
import HTMLTestRunnerNew
from email.mime.text import MIMEText
from email.header import Header
import smtplib
import unittest
import os
from data_test import *
from email.mime.multipart import MIMEMultipart
class Email_Console():
def __init__(self):
self.username, self.password, self.To_Email = Date_test.Email_Date()
def send_main(self, file_new):
"""
发送邮件方法
:param file_new:
:return:
"""
msg = MIMEMultipart("Emaik_TestText")
msg['Subject'] = Header('自动化测试报告', 'utf-8')
msg['From'] = self.username
msg['To'] = self.To_Email
with open(file_new, 'rb') as f:
mail_body = f.read()
msg.attach(MIMEText(mail_body, 'html', 'utf-8'))
with open("result.html", "rb") as f:
mail_attach = f.read()
att1 = MIMEText(mail_attach, 'base64', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'
att1["Content-Disposition"] = 'attachment; filename="report_test.html"'
msg.attach(att1)
with open("data_test.xlsx","rb") as f:
mail_attach = f.read()
att2 = MIMEText(mail_attach, 'base64', 'utf-8')
att2["Content-Type"] = 'application/octet-stream'
att2["Content-Disposition"] = 'attachment; filename="data_test.xlsx"'
msg.attach(att2)
try:
smtp = smtplib.SMTP()
smtp.connect("smtp.163.com", 25)
smtp.login(self.username, self.password)
smtp.sendmail(self.username, self.To_Email.split(","), msg.as_string())
smtp.quit()
except Exception as e:
print("Send Email Failed!!!")
raise e
def new_report(self, testreport):
"""
生成并查找查找最新测试报告方法
:param testreport:
:return:
"""
# 生成测试用例
fp = open("result.html", 'wb')
runner = HTMLTestRunnerNew.HTMLTestRunner(stream=fp, title='2019年4月9日前程贷接口测试报告', description='所有测试情况',
tester="桂马")
discove = unittest.defaultTestLoader.discover(".", pattern="test_*.py")
runner.run(discove)
fp.close()
# 查找测试用例
lists = os.listdir(testreport)
lists.sort(key=lambda fn: os.path.getmtime(testreport + "\\" + fn))
file_new = os.path.join(testreport, lists[-1])
print(file_new)
return file_new
if __name__ == "__main__":
email_test = Email_Console()
file_path = email_test.new_report(os.getcwd()) # 查找新生的报告
email_test.send_main(file_new=file_path) # 调用发邮件模块
注意点:
1.setUp中获取返回cookies值算不上用得好,只能算面前能用,其他方法还有修改TestCase模块中默认值,添加self.Cookie这个值,然后直接用,但我不怎么想使用这个方法,所以放弃了
后记:
后续会陆续更新test_case文件中的测试用例,多写自然就熟悉了