一、项目结构
1、新建一个工程(一定要创建工程),工程名称自己定义,如:UiAutoTest
2、在工程下创建以下几个 pakage 包:
二、实例如下
1、config 包下的文件
"""
config.py:存放所有的配置文件、如:项目路径
"""
project_path = "D:/pycharm/StudyUiAutoTest"
"""
globalconfig.py:存放所有的目录路径
"""
import os
from config import conf
data_path = os.path.join(conf.project_path,"data","data.xlsx") #data.xlsx文件绝对路径
# print(data_path)
case_path = os.path.join(conf.project_path,"testcases") #用例存放路径
# print(case_path)
report_path = os.path.join(conf.project_path,"report") #报告存放路径
# print(report_path)
2、data 包下的文件
3、public / pages 包下的文件
"""
MethodBaseClass.py:封装所有页面的公共方法,页面定位/操作方法
"""
class MethodBase():
def __init__(self,dirver):
self.driver = dirver
def find_element(self,locator):
mode = locator[0]
value = locator[1]
try:
if mode == "id" or mode == "Id" or mode == "ID":
elem = self.driver.find_element_by_id(value)
elif mode == "name" or mode == "Name" or mode == "NAME":
elem = self.driver.find_element_by_name(value)
elif mode == "xpath" or mode == "Xpath" or mode == "XPATH":
elem = self.driver.find_element_by_xpath(value)
elif mode == "link" or mode == "Link" or mode == "LINK":
elem = self.driver.find_element_by_link_text(value)
elif mode == "class" or mode == "Class" or mode == "CLASS":
elem = self.driver.find_element_by_class_name(value)
else:
raise NameError("mode error!")
except Exception:
raise NameError("{} not found!".format(locator))
else:
return elem
def click(self,element):
element.click()
def send_keys(self,element,text):
element.send_keys(text)
def get_title(self):
return self.driver.title
def get_text(self,element):
return element.text
def maximizewindow(self):
self.driver.maximize_window()
def get_url(self,url):
self.driver.get(url)
def wait(self,sec):
self.driver.implicitly_wait(sec)
def Quit(self):
self.driver.quit()
"""
PageElement.py:所有的页面元素封装
"""
class Elenmet():
#百度首页
input_box = ("id","kw")
search_button = ("id","su")
baidu_logo = ("id","result_logo")
4、public / utils 包下的文件
"""
getExcelValue.py 封装 Excel 中获取到的数据
"""
from public.utils.ReadExcel import ReadExcel
class GetValue():
def getPython(self):
return ReadExcel("Sheet1").getValue(1,0)
def getJava(self):
return ReadExcel("Sheet1").getValue(2,0)
def getHtml(self):
return ReadExcel("Sheet1").getValue(3,0)
def getUrl(self):
return ReadExcel("Sheet1").getValue(1,1)
"""
ReadExcel.py 封装读取Excel文件操作
"""
import xlrd
from config.globalconf import *
class ReadExcel():
def __init__(self,sheetName):
workBook = xlrd.open_workbook(data_path)
self.workSheet = workBook.sheet_by_name(sheetName)
def getValue(self,rowx,cols):
value = self.workSheet.cell(rowx,cols).value
return value
if __name__ == '__main__':
print(ReadExcel("Sheet1").getValue(2,0))
"""
email.py 配置收发邮件
"""
from email.mime.text import MIMEText
from email.header import Header
import smtplib
import time
import os
def send_mail(new_report):
f = open(new_report, "rb")
mail_body = f.read()
f.close()
username = "[email protected]" #发件箱用户名
password = "gekzdyrczcloghbx" #发件箱密码(授权码)
sender = "[email protected]" #发件人邮箱
receiver = ["[email protected]"] #收件人邮箱
# 邮件正文是MIMEText
msg = MIMEText(mail_body, "html", "utf-8")
# 邮件对象
msg["Subject"] = Header("自动化测试报告", "utf-8").encode()
msg["From"] = Header(u"测试机 <%s>"%sender)
msg["To"] = Header("测试负责人 <%s>"%receiver)
msg["date"] = time.strftime("%a,%d %b %Y %H:%M:%S %z")
#发送邮件
smtp = smtplib.SMTP()
smtp.connect("smtp.qq.com") # 邮箱服务器
smtp.login(username, password) # 登录邮箱
smtp.sendmail(sender, receiver, msg.as_string()) # 发送者和接收者
smtp.quit()
print("邮件已发出!注意查收。")
# ======查找测试目录,找到最新生成的测试报告文件======
def new_report(test_report):
lists = os.listdir(test_report) # 列出目录的下所有文件和文件夹保存到lists
lists.sort(key=lambda fn: os.path.getmtime(test_report + "\\" + fn)) # 按时间排序
file_new = os.path.join(test_report, lists[-1]) # 获取最新的文件保存到file_new
return file_new
5、run_all 包下的文件
import unittest
from config.globalconf import *
import HTMLTestRunner
import time
from public.utils.email import *
now_time = time.strftime("%Y-%m-%d_%H-%M-%S") #获取格式化时间
filepath = report_path + "/" + str(now_time) + "TestReport.html" # 拼接测试报告路径和名称
def run_all_case():
dis = unittest.defaultTestLoader.discover(case_path,"case*.py")
f = open(filepath,"wb")
runner = HTMLTestRunner.HTMLTestRunner(stream=f)
runner.run(dis)
if __name__ == '__main__':
run_all_case()
report = new_report(report_path)
send_mail(report)
6、TestCase 包下文件
from public.page.MethodBaseClass import MethodBase
from selenium import webdriver
from public.utils.getExcelValue import GetValue
from public.page.PageElement import Elenmet as E
import time
import unittest
import sys
class Test_Case(unittest.TestCase):
"""
测试用例
"""
@classmethod
def setUpClass(cls) -> None:
url = GetValue().getUrl()
driver = webdriver.Chrome()
cls.dr = MethodBase(driver)
cls.dr.get_url(url)
cls.dr.wait(10)
cls.dr.maximizewindow()
time.sleep(1)
@classmethod
def tearDownClass(cls) -> None:
time.sleep(2)
cls.dr.Quit()
def tearDown(self) -> None:
time.sleep(2)
baiduLogo = self.dr.find_element(E.baidu_logo)
self.dr.click(baiduLogo)
def testpython(self):
inputBox = self.dr.find_element(E.input_box) #定位输入框
text = GetValue().getPython()
self.dr.send_keys(inputBox,text) #输入操作
seachButton = self.dr.find_element(E.search_button) #定位百度一下按钮
self.dr.click(seachButton) #点击百度一下
time.sleep(1)
title = self.dr.get_title() #获取title断言
self.assertIn(text,title,msg="Testcase {} error".format(sys._getframe().f_code.co_name)) #出现异常时带入用例名称
def testjava(self):
inputBox = self.dr.find_element(E.input_box)
text = GetValue().getJava()
self.dr.send_keys(inputBox,text)
seachButton = self.dr.find_element(E.search_button)
self.dr.click(seachButton)
time.sleep(1)
title = self.dr.get_title()
self.assertIn(text, title, msg="Testcase {} error".format(sys._getframe().f_code.co_name))
def testhtml(self):
inputBox = self.dr.find_element(E.input_box)
text = GetValue().getHtml()
self.dr.send_keys(inputBox,text)
seachButton = self.dr.find_element(E.search_button)
self.dr.click(seachButton)
time.sleep(1)
title = self.dr.get_title()
self.assertIn(text, title, msg="Testcase {} error".format(sys._getframe().f_code.co_name))
if __name__ == '__main__':
unittest.main()