直接就要彪代碼了,有點快了!這只是針對速成的朋友,要是想要認真學習,就去夢老師那裏進行細緻的學習
老規矩,依舊是從下往上開始
Config.config.ini
[environment]
browser = 1
switch = 0
用戶名 = username
[test]
url = https://www.baidu.com/
[prod]
url = http://www.youdao.com/
yonghuming = username
[yonghu]
[sender]
username = 測試
email = 發送郵箱
password = 發送郵箱密碼
[addressed]
user1 = 接收郵箱
famework
base_page.py
import configparser
from Logs.log import log1
from selenium import webdriver
import getcwd
import os
import time
path = getcwd.get_cwd()
config_path = os.path.join(path, 'Config/config.ini')
class BasePage():
def config_options(self,section):
'''讀取配置文件某section下所有鍵'''
config = configparser.ConfigParser()
config.read(config_path,encoding="utf-8-sig")
username = config.options(section)
return username
def get_addkey(self,user):
'''遍歷獲得配置文件收件人email'''
sum = 0
L = []
for i in user:
if sum < len(user):
emails = self.config_get(i,'addressed')
L.append(emails)
sum += 1
return L
def open_browser(self,driver):
'''打開瀏覽器'''
browser = self.config_get('browser','environment')
log1.info('讀取瀏覽器配置')
url = self.config_get('url')
log1.info('讀取url:%s' % url)
try:
if browser == str(0) :
driver = webdriver.Chrome()
log1.info('打開的瀏覽器爲谷歌')
elif browser == str(1) :
driver = webdriver.Firefox()
log1.info('打開的瀏覽器爲火狐')
driver.get(url)
driver.maximize_window()
log1.info('瀏覽器最大化')
driver.implicitly_wait(10)
log1.info('設置靜態等待時間10秒')
return driver
except BaseException:
log1.error('瀏覽器打開報錯')
def config_get(self,key,section=None):
'''讀取配置文件字段的值並返回'''
config = configparser.ConfigParser()
config.read(config_path,encoding="utf-8-sig")
switch = config.get('environment', 'switch')
if section==None and switch == str(0):
section = 'test'
elif section==None and switch == str(1):
section = 'prod'
config_get = config.get(section,key)
return config_get
def config_write(self,key = None,value = None,section = None):
'''往配置文件寫入鍵值'''
config = configparser.ConfigParser()
config.read(config_path,encoding="utf-8-sig")
switch = config.get('environment', 'switch')
if section == None and switch == str(0):
section = 'test'
elif section == None and switch == str(1):
section = 'prod'
'''
原版
if key is not None and value is not None:
config.set(section,key,value)
log1.info('在section:%s下寫入%s=%s' %(section,key,value))
with open(config_path,'w',encoding='utf-8')as f :
config.write(f)
else:
config.add_section(section)
log1.info('新增section:%s' % section)
with open(config_path,'w',encoding='utf-8')as f :
config.write(f)'''
if config.has_section(section) == True :
'''我的'''
if key is not None and value is not None:
config.set(section,key,value)
log1.info('在section:%s下寫入%s=%s' %(section,key,value))
with open(config_path,'w',encoding='utf-8')as f :
config.write(f)
else:
print('youle')
log1.info('新增section:%s已存在哦' % section)
with open(config_path,'w',encoding='utf-8')as f :
config.write(f)
elif config.has_section(section) == False:
config.add_section(section)
log1.info('新增section:%s' % section)
with open(config_path,'w',encoding='utf-8')as f :
config.write(f)
def config_delete(self,key = None,section = None):
'''刪除配置文件字段'''
config = configparser.ConfigParser()
config.read(config_path,encoding="utf-8-sig")
switch = config.get('environment', 'switch')
if section == None and switch == str(0):
section = 'test'
elif section == None and switch == str(1):
section = 'prod'
if key is not None :
config.remove_option(section,key)
log1.info('刪除section:%s下key爲:%s的記錄' % (section,key))
with open(config_path,'w',encoding='utf-8')as f :
config.write(f)
print('1')
else:
config.remove_section(section)
log1.info('刪除section:%s' % section)
with open(config_path,'w',encoding='utf-8')as f :
config.write(f)
print('122')
def __init__(self,driver):
'''與測試方法對應'''
self.driver = driver
def jin_frame(self,selector):
'''進入frame'''
element = self.find_element(selector)
self.driver.switch_to.frame(element)
print("進入farm成功")
def exit_frame(self):
'''退出'''
self.driver.switch_to.default_content()
def find_element(self,selector):#元素定位
'''元素定位'''
by = selector[0]
value = selector[1]
element = None
if by =='id' or by =='name' or by == 'class' or by == 'tag' or by =='link' or by =='text' or by =='css' or by == 'xpath' or by == 'text':
if by == 'id':
element = self.driver.find_element_by_id(value)
elif by == 'name':
element = self.driver.find_element_by_name(value)
elif by == 'class':
element = self.driver.find_element_by_class_name(value)
elif by == 'tag':
element = self.driver.find_element_by_tag_name(value)
elif by == 'link':
element = self.driver.find_element_by_link_text(value)
elif by == 'text':
element = self.driver.find_element_by_partial_link_text(value)
elif by == 'css':
element = self.driver.find_element_by_css_selector(value)
elif by == 'xpath':
element = self.driver.find_element_by_xpath(value)
else:
print('沒有找到元素')
print(element.is_displayed())
return element
else:
print('輸入的元素定位方式錯誤')
def get_img(self):##
'''截圖'''
path = os.path.join(getcwd.get_cwd(),'screenshots/')#拼接截圖保存路徑
rq = time.strftime('%Y%m%d%H%M', time.localtime(time.time()))#按格式獲取當前時間
screen_name = path + rq + '.png'#拼接截圖文件名
print(screen_name)
try:
self.driver.get_screenshot_as_file(screen_name)
log1.info("截圖保存成功")
except BaseException:
log1.error("截圖失敗",exc_info = 1)
def send(self,selector,value):
'''寫'''
element=self.find_element(selector)#調用封裝的定位元素方法
try:
element.send_keys(value)
print('輸入的內容%s' % value)
except BaseException:
print('error')
def type(self,selector,value):
'''輸入內容'''
element=self.find_element(selector)
element.clear()
log1.info('清空輸入內容')
try:
element.send_keys(value)
log1.info('輸入的內容:%s' % value)
except BaseException:
log1.error('內容輸入報錯',exc_info = 1)
self.get_img()
def click(self,selector):
'''點擊元素'''
element = self.find_element(selector)
try:
element.click()
log1.info('點擊元素成功')
except BaseException:
log1.error('點擊元素報錯',exc_info = 1)
self.get_img()
def sleep(self,secondes):
'''強制暫停'''
time.sleep(secondes)
log1.info('暫停%d秒' % secondes)
def get_title(self):
'''獲取title'''
title = self.driver.title
log1.info('當前窗口的title是:%s' % title)
return title
def quit(self):
self.driver.quit()
log1.info('關閉瀏覽器')
def dangqianwangye(self):
'''獲取句柄,並轉進來'''
sreach_window=self.driver.current_window_handle
print(sreach_window)
log1.info('當前句首:%s' % sreach_window)
return sreach_window
entrance.py
'''
Created on 2019年4月26日
@author: NULL
'''
'''
import text.text
import unittest
if __name__ == "__main__":
suite = unittest.TestSuite()
suite.addTest(text.text.test_baidu('test_baisu'))
runner = unittest.TextTestRunner()
runner.run(suite)
'''
from famework.my_email import mail
import text.text
import text.test_baidu_new
import unittest
import getcwd
import os
import HTMLTestRunnerCN
if __name__ == "__main__":
suite = unittest.TestSuite()
suite.addTest(text.text.test_baidu('test_baisu'))
suite.addTest(text.test_baidu_new.test_baidu_new('test_new'))
path = getcwd.get_cwd()
file_path = os.path.join(path,'report/xxxUI自動化測試報告.html')
fp = open(file_path,'wb')
runner = HTMLTestRunnerCN.HTMLTestReportCN(
stream = fp,
title = 'xxxUI自動化測試報告',
description = '報告中描述部分',
tester = '測試者'
)
runner.run(suite)
fp.close()
mail()
my_email.py另一種寫法是的,我還沒實行。有會的大佬可以寫一下。密碼不是自己的密碼
'''
Created on 2019年4月30日
@author: NULL
'''
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
from email.mime.multipart import MIMEMultipart
import getcwd
import os
from Logs.log import log1
from famework.base_page import BasePage
import time
rq = time.strftime('%Y%m%d', time.localtime(time.time()))#獲取本地時間 轉換成日期
my_mail = BasePage(driver=1)
sender = my_mail.config_get('email','sender') # 發件人郵箱賬號
password = my_mail.config_get('password','sender') # 發件人郵箱密碼
usernmae = my_mail.config_get('username','sender') #發件人姓名
users = my_mail.config_options('addressed') #收件人
addressed_eamils = my_mail.get_addkey(users) #收件人郵箱
path = getcwd.get_cwd()
file = os.path.join(path, 'report/xxxUI自動化測試報告.html')
def mail():
try:
# 創建一個帶附件的實例
message = MIMEMultipart()
message['From']=formataddr([usernmae,sender]) # 括號裏的對應發件人郵箱暱稱、發件人郵箱賬號
log1.info('發件人姓名:%s' % usernmae)
log1.info('發件人郵箱:%s' % sender)
message['To']=';'.join(addressed_eamils) # 括號裏的對應收件人郵箱暱稱、收件人郵箱賬號
log1.info('收件人郵箱:' + ';'.join(addressed_eamils))
message['Subject']=rq + "xxxUI自動化測試報告.html" # 郵件的主題,也可以說是標題
# 郵件正文內容
message.attach(MIMEText('附件爲xxxUI自動化測試報告.html', 'plain', 'utf-8'))
# 構造附件1,傳送當前目錄下的 test.txt 文件
att1 = MIMEText(open(file, 'rb').read(), 'base64', 'utf-8')
log1.info('讀取附件')
att1["Content-Type"] = 'application/octet-stream'
# 這裏的filename可以任意寫,寫什麼名字,郵件中顯示什麼名字
att1.add_header("Content-Disposition", "attachment", filename=("gbk", "", "xxxUI自動化測試報告.html"))
# 附件名稱非中文時的寫法
# att["Content-Disposition"] = 'attachment; filename="test.html")'
message.attach(att1)
log1.info('添加附件')
server = smtplib.SMTP_SSL("smtp.qq.com", 465) # 發件人郵箱中的SMTP服務器,端口是25
log1.info('連接QQ郵箱smtp服務')
server.login(sender,password) # 括號中對應的是發件人郵箱賬號、郵箱密碼
log1.info('連接成功')
server.sendmail(sender, addressed_eamils, message.as_string()) # 括號中對應的是發件人郵箱賬號、收件人郵箱賬號、發送郵件
server.quit() # 關閉連接
log1.info("郵件發送成功")
except Exception:
log1.error("郵件發送失敗",exc_info=1)
'''另一種寫法'''
'''’
#發郵件的庫
import smtplib
#郵件文本
from email.mime.text import MIMEText
#SMTP服務器
SMTPSever = "smtp.163.com"
#發郵件的地址
sender = ""
#發送者郵箱的密碼(授權碼)
passwd = ""
#設置發送的內容
message = "你好"
#轉換成郵件文本
msg = MIMEText(message)
#標題
msg["Subject"] = "來自帥哥的問候"
#發送者
msg["From"] = sender
#創建SMTP服務器
mailSever = smtplib.SMTP(SMTPSever,25)
#登錄郵箱
mailSever.login(sender,passwd)
#發送郵件
mailSever.sendmail(sender,["接受的郵箱"],msg.as_string())
#退出郵箱
mailSever.quit()'''
logs.log.py
#-*- coding: UTF-8 -*-
import logging
import time
import os
import getcwd
def get_log(logger_name):
#創建一個logger
logger= logging.getLogger(logger_name)
logger.setLevel(logging.INFO)
#設置日誌存放路徑,日誌文件名
#獲取本地時間,轉換爲設置的格式
rq = time.strftime('%Y%m%d%H%M',time.localtime(time.time()))
#設置所有日誌和錯誤日誌的存放路徑
path = getcwd.get_cwd()
#通過getcwd.py文件的絕對路徑來拼接日誌存放路徑
all_log_path = os.path.join(path,'Logs/All_Logs/')
error_log_path = os.path.join(path,'Logs/Error_Logs/')
#設置日誌文件名
all_log_name = all_log_path + rq +'.log'
error_log_name = error_log_path + rq +'.log'
#創建handler
#創建一個handler寫入所有日誌
fh = logging.FileHandler(all_log_name)
fh.setLevel(logging.INFO)
#創建一個handler寫入錯誤日誌
eh = logging.FileHandler(error_log_name)
eh.setLevel(logging.ERROR)
#創建一個handler輸出到控制檯
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
#定義日誌輸出格式
#以時間-日誌器名稱-日誌級別-日誌內容的形式展示
all_log_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
#以時間-日誌器名稱-日誌級別-文件名-函數行號-錯誤內容
error_log_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(module)s - %(lineno)s - %(message)s')
#將定義好的輸出形式添加到handler
fh.setFormatter(all_log_formatter)
ch.setFormatter(all_log_formatter)
eh.setFormatter(error_log_formatter)
#給logger添加handler
logger.addHandler(fh)
logger.addHandler(eh)
logger.addHandler(ch)
return logger
log1 = get_log("selenium")
後續,下一篇文章補上