多测师肖sir_高级金牌讲师_第2个月po教学之实战(002)
一、框架的基本结构
案例展示结果:
(1)生成报告
邮箱报告:
=============================================================
步骤:
一、总框架:
1.1建项目,新建6个包以及public中两个包:pages和utils
1.2 public中的两个子包pages包和utils包
第一个包:config包(存放配置文件)
在config包下新建;两个文件,分别是config.ini 和 globalconnfig.py
配置文件的格式一般是:ini,xlsx,conf,csv
1、新建config.ini 文件
填写conconfig中的数:在跑自动化的过程中有一些参数:url、username,pwd
2、新建globalconfig包
填写所有包的绝对路径
第二步:
public中的utils中新建Readconfigini
读取配置文件的作用
from configparser import ConfigParser #导入类
from bbs_framework.config.globalconfig import config
import os
class ReadConfigIni:
def __init__(self,filename):
self.cf = ConfigParser() #创建ConfigParser类的对象
self.cf.read(filename)
def get_ini_data(self,section, option):
'''或者ini后缀结尾的文件内容'''
value = self.cf.get(section, option)
return value
read_conf = ReadConfigIni(os.path.join(config,‘config.ini’))
#print r.get_ini_data(‘path’,‘project_path’)
#print r.get_ini_data(‘env’,‘url’)
data包:
存放测试数据
方法:
在public下的utils中新建 ReadExcel .py
#coding=utf-8
‘’’
1.在dos窗口用pip install xlrd ==》下载xlrd模块
2.这个xlrd模块是用来读取Excel表格的
‘’’
import xlrd
from bbs_framework.config.globalconfig import *
#拿到了data.xlsx文件的绝对路径和文件名称
datapath = os.path.join(data,‘data.xlsx’)
class ReadExcel:
def init(self,filename,sheetname):
‘’‘打开Excel表格工作薄、拿到self.workbook对象’’’
self.workbook = xlrd.open_workbook(filename)
#选择具体的sheet页面
self.sheet_name = self.workbook.sheet_by_name(sheetname)
def read_excel(self,rowx, colx):
‘’‘封装一个读取Excel文件的工具方法’’’
value = self.sheet_name.cell(rowx, colx).value
return value
r = ReadExcel(datapath,‘Sheet1’)
print (r.read_excel(1,0)) #通过索引值拿到url地址 http://discuz.e70w.com/
print(r.read_excel(1,1)) #通过索引值拿到账号:admin
#练习:拿到账号和密码 #通过索引值拿密码:
举例:也可以直接使用data.ini
======================================
public包中的pages下
新建一个.py文件:BasePage.py 和PageElement.py
#coding=utf-8
‘’’
把所有页面公共公开的方法都封装在BasePage这个基类当中
‘’’
import unittest
from selenium import webdriver
dirver=webdriver.Chrome()
class BasePage(unittest.TestCase):
@classmethod
def set_driver(cls,driver): #设置driver对象、保证所有的用例用的是同一个driver对象
cls.driver = driver
#driver = webdriver.Chrome()
@classmethod
def get_driver(cls): #单例模式
return cls.driver #拿到driver对象、保证登录、发帖等等是同一个driver对象
@classmethod
def find_element(cls,element):
type = element[0]
value = element[1]
if type == 'id':
elem = cls.driver.find_element_by_id(value)
elif type == 'class':
elem = cls.driver.find_element_by_class_name(value)
elif type == 'xpath':
elem = cls.driver.find_element_by_xpath(value)
elif type == 'link_text':
elem = cls.driver.find_element_by_link_text(value)
elif type == 'css':
elem = cls.driver.find_element_by_css_selector(value)
else:
raise NameError('please input correct params')
return elem
@classmethod
def send_keys(cls,elem,text): #cls.driver.find_element_by_id(value)
# return cls.find_element(elem).send_keys(text)
return elem.send_keys(text)
@classmethod
def click(cls,elem):
elem.click()
@classmethod
def close(cls):
return cls.driver.close()
@classmethod
def get_text(cls,elem):
return BasePage.find_element(elem).text
@classmethod
def go_home(cls,elem):
'''回到首页'''
value = BasePage.find_element(elem)
BasePage.click(value)
if name == ‘main’:
m = BasePage()
baidu_input = (‘id’, ‘kw’) # ==>page object设计模式
elem = m.find_element(baidu_input)
PageElement.py
#coding=utf-8
class PageElement:
#登录元素定位
userName = (‘id’, ‘ls_username’)
passWord = (‘id’, ‘ls_password’)
loginBtn = (‘css’, ‘.pn’)
loginOut = (‘xpath’, ‘//*[@id=“um”]/p[1]/a[7]’)
#模块管理元素定位
module_management = ('link_text','模块管理')
submitBtn = ('xpath','//*[@id="submit"]/strong')
#回到首页
index = ('xpath','//*[@id="mn_forum"]/a')
以上参数定位方法和页面属性
==========================================
report包
run包
新建一个run_all.py文件
from bbs_framework.config.globalconfig import *
from bbs_framework.public.utils.HTMLTestRunner3_New import HTMLTestRunner
from bbs_framework.public.utils.mail3 import SendMail
import time
import unittest
#定义生成报告的文件名称
now = time.strftime(’%Y-%m-%d-%H-%M-%S’)
filename = report + ‘\’ + str(now) + ‘_ui_report.html’
def auto_run():
‘’‘封装一个运行用例并且生成报告的工具函数’’’
discover = unittest.defaultTestLoader.discover(start_dir=testcase,pattern=‘test_*.py’)
f = open(filename,‘wb’)
runner = HTMLTestRunner(stream=f,
title=u’discuz项目ui自动化测试报告’,
description=u’用例执行如下:’,
tester=u’肖sir’)
runner.run(discover)
f.close()
def send_mail():
sm = SendMail(send_msg=filename,attachment=filename)
sm.send_mail()
if name == ‘main’:
auto_run() #运行用例
send_mail() #发送邮件
testcase 包
建两个.py 文件 test_login.py和test_module_management.py
test_login.py
#coding=utf-8
from bbs_framework.public.pages.BasePage import BasePage
from bbs_framework.public.utils.ReadConfigIni import ReadConfigIni
from bbs_framework.public.pages.PageElement import PageElement as p
from bbs_framework.config.globalconfig import *
from selenium import webdriver
import unittest
import os
read= ReadConfigIni(os.path.join(config,‘config.ini’))
url = read.get_ini_data(‘env’,‘url’) #http://discuz.e70w.com/
username = read.get_ini_data(‘env’,‘username’) #admin
password = read.get_ini_data(‘env’,‘password’) #mN3BzsaeAd
#from selenium import webdriver
driver = webdriver.Chrome()
class TestLogin(BasePage):
@classmethod
def setUpClass(cls):
'''创建driver对象'''
driver = webdriver.Chrome()
BasePage.set_driver(driver) #所有的用例都需要继承BasePage
@classmethod
def tearDownClass(cls):
'''回到discuz论坛的首页'''
BasePage.go_home(p.index)
def test001_login(self):
driver = BasePage.get_driver() #拿到谷歌浏览器对象
driver.get(url)
driver.maximize_window()
driver.implicitly_wait(20)
#1.输入账号
elem = BasePage.find_element(p.userName)
BasePage.send_keys(elem,username)
#2.输入密码
elem = BasePage.find_element(p.passWord)
BasePage.send_keys(elem,password)
#3.点击登录
elem = BasePage.find_element(p.loginBtn)
BasePage.click(elem)
#4.进行断言
value = BasePage.get_text(p.loginOut)
assert value == '退出'
if name == ‘main’:
unittest.main()
test_module_management.py
#coding=utf-8
from bbs_framework.public.pages.BasePage import BasePage
from bbs_framework.public.pages.PageElement import PageElement as p
class TestModuleManagement(BasePage):
@classmethod
def setUpClass(cls):
pass
@classmethod
def tearDownClass(cls):
‘’‘回到discuz论坛的首页’’’
BasePage.go_home(p.index)
def test001_module_management(self):
elem = BasePage.find_element(p.module_management)
BasePage.click(elem)
value = BasePage.get_text(p.submitBtn)
assert value == ‘提交’
===============================================
在utils中添加报告模板和邮件模板
邮件模板:
#coding=utf-8
import smtplib
from email.mime.text import MIMEText
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
import os
class SendMail:
def init(self, send_msg,
smtpserver=“smtp.163.com”, sender=“15949613302@163.com”, #15949613302@163.com
psw=“KPHYSPDXOUFWENEU”, receiver=“15949613302@163.com”, #psw这个为授权码
port=25, attachment=None):
# self.reportfile = reportfile
self.send_msg = send_msg
self.smtpserver = smtpserver
self.sender = sender
self.psw = psw
self.receiver = receiver
self.port = port
self.attachment = attachment
def send_mail(self):
"""发送最新的测试报告内容"""
#打开测试报告,读取测试报告内容
with open(self.send_msg, "rb") as f:
mail_boday = f.read()
#定义邮件
msg = MIMEMultipart()
msg['subject'] = Header(u"自动化测试报告", 'utf-8')
msg['From'] = Header(self.sender, 'utf-8')
msg['To'] = self.receiver
#添加附件
if self.attachment != None:
file_name = self.attachment.split(os.path.sep)[-1]
att = MIMEText(open(self.attachment, "rb").read(), "base64", "utf-8")
att["Content-Type"] = "application/octet-stream"
att.add_header('Content-Disposition', 'attachment', filename = file_name)
msg.attach(att)
body = MIMEText(mail_boday, _subtype="html", _charset='utf-8')
msg.attach(body)
smtp = smtplib.SMTP()
smtp.set_debuglevel(1)
smtp.connect(self.smtpserver, self.port)
#用户登录并发送邮件
smtp.login(self.sender, self.psw)
smtp.sendmail(self.sender, self.receiver, msg.as_string())
smtp.quit()
=================================================
然后查看报告和邮件
本文地址:https://blog.csdn.net/m0_47403059/article/details/113972090