一.變動
1.增加文本文檔SendToUserinfo.txt 用來保存郵件接收者的信息。
2.修改測試報告文件名稱格式並添加reprot目錄保存測試報告。
3.添加代碼注釋,更方便閱讀。
二.項目目錄
三.代碼
login_test.py
import time
from selenium import webdriver
from webinfo import webinfo
from userinfo import userinfo
from log_file import login_log
from send_email import send_mail_init_info
# account = '[email protected]'
def open_web():
''' :return:web句柄 '''
driver = webdriver.Chrome()
driver.maximize_window()
return driver
def load_url(driver,ele_dict):
''' :param driver: web主頁面句柄 :param ele_dict: web信息字典(從文件中讀取) :return: 無 '''
driver.get(ele_dict['Turl'])
time.sleep(5)
def find_element(driver,ele_dict):
''' :param driver: web句柄 :param ele_dict: web信息字典(從文件中讀取) :return: 返回找到的元素 '''
driver.find_element_by_class_name(ele_dict['image_id']).click()
if 'text_id' in ele_dict:
driver.find_element_by_link_text(u'登錄').click()
user_id = driver.find_element_by_id(ele_dict['userid'])
pwd_id = driver.find_element_by_id(ele_dict['pwdid'])
login_id = driver.find_element_by_id(ele_dict['loginid'])
return user_id,pwd_id,login_id
def send_val(ele_tuple,arg):
''' :param ele_tuple: web元素 :param arg: 可變長參數,接收用戶名和密碼 :return: 無 '''
# input userinfo
listkey = ['uname','pwd']
i = 0
for key in listkey:
ele_tuple[i].send_keys('')
ele_tuple[i].clear()
ele_tuple[i].send_keys(arg[key])
i+=1
ele_tuple[2].click()
# 判斷登錄是否成功,並寫入測試報告
def check_login(driver,ele_dict,log,userlist):
''' :param driver: web句柄 :param ele_dict: 讀取到的元素信息(文件中讀到的) :param log: login_log對象 :param userlist: 用戶信息(文件中讀取) :return: False or Ture '''
result = False
time.sleep(3)
try:
err = driver.find_element_by_id(ele_dict['error'])
driver.save_screenshot(err.text+'.png')
log.log_write(u'賬號:%s 密碼:%s 提示信息:%s:failed\n' %(userlist['uname'],userlist['pwd'],err.text))
print('username or password error')
except:
print('login success!')
log.log_write(u'賬號:%s 密碼:%s :passed\n'%(userlist['uname'],userlist['pwd']))
#login_out(driver,ele_dict)
return True
return result
# 登錄
def login_out(driver,ele_dict):
time.sleep(5)
driver.find_element_by_class_name(ele_dict['logout']).click()
''' def screen_shot(err): i = 0 save_path = r'D:\pythondcode\capture' capturename = '\\'+str(i)+'.png' wholepath = save_path+capturename if Path(save_path).is_dir(): pass else: Path(save_path).mkdir() while Path(save_path).exists(): i+=1 capturename = '\\'+str(i)+'.png' wholepath = save_path + capturename err.screenshot(wholepath) '''
def login_test():
# 調用日志文件,並進行類的實例化
log = login_log()
# 調用send_mail_init_info中的read_SendToUserinfo_file方法,並實例化
msg = send_mail_init_info.read_SendToUserinfo_file(r'G:\suitUIUnittestDemo\SendToUserinfo.txt')
# 調用整個send_mail_init_info類方法,並實例化
sendmail = send_mail_init_info('smtp.qq.com','[email protected]','gifhhsbgqyovbhhc','[email protected]',msg)
#ele_dict = {'url': 'http://www.maiziedu.com/', 'text_id': '登錄', 'user_id': 'id_account_l', 'pwd_id': 'id_password_l'
#, 'login_id': 'login_btn','image_id':'close-windows-btn7','error_id':'login-form-tips'}
# 調用webinfo文件,並調用webinfo方法,實例化函數方法
ele_dict = webinfo(r'G:\suitUIUnittestDemo\webinfo.txt')
# 調用userinfo文件,並調用userinfo方法,實例化函數方法
# user_list=[{'uname':account,'pwd':pwd}]
user_list = userinfo(r'G:\suitUIUnittestDemo\userinfo.txt')
# 實例化驅動,調用open_web
driver = open_web()
# 調用load_url方法,並從實例化webinfo(ele_dict)獲取返回的ele_dict['Turl']數據
# load url
load_url(driver,ele_dict)
# 調用find_element方法,入參調用時候webinfo(ele_dict),獲取返回的定位信息
# find element
ele_tuple = find_element(driver,ele_dict)
# 調用日志文件,調用log_write方法
# send values
ftitle = time.strftime('%Y-%m-%d', time.gmtime())
log.log_write(U'\t\t\t%s登錄系統測試報告\n' % (ftitle))
# 循環用戶測試數據
for userlist in user_list:
# 調用send_val方法,ele_tuple參數是獲取到的實例化ele_dict的定位信息值,
# 參數userlist是調用userinfo文件並實例化函數user_list內的值數據
send_val(ele_tuple,userlist)
# 調用check_login方法
# check login success or failed
result = check_login(driver,ele_dict,log,userlist)
if result:
# 調用login_out方法
login_out(driver,ele_dict)
time.sleep(3)
ele_tuple = find_element(driver,ele_dict)
time.sleep(3)
# 調用日志文件實例化中的check_login方法
log.log_close()
# 調用整個send_mail_init_info類並實例化sendmail,且調用send_email方法,
# 並且調用日志文件log實例化調用filename自定義文件格式,發送報告到指定的郵箱
sendmail.send_email(log.filename)
driver.quit()
if __name__ == '__main__':
login_test()
log_fiile.py
# 測試輸出報告
import time
# 測試報告輸出接口
class login_log(object):
filename = './report/' + time.strftime('%Y-%m-%d %H_%M_%S') + '.txt'
def __init__(self,path='./report/',mode='w'):
#filename = path + time.strftime('%Y-%m-%d %H_%M_%S') +'.txt'
self.log = open(self.filename,mode)
def log_write(self,msg):
self.log.write(msg)
def log_close(self):
self.log.close()
if __name__ == '__main__':
log = login_log()
log.log_write('xiaochao11520')
mas = log.filename
print(mas)
log.log_close()
send_email.py
# 通過郵件發送測試報告
import smtplib
from email.mime.text import MIMEText
from email.header import Header
# 郵件發送接口
class send_mail_init_info(object):
'''郵件配置信息'''
def __init__(self,server,fromuser,frompassword,sender,receiver):
self.server = server
self.fromuser = fromuser
self.frompassword = frompassword
self.sender = sender
self.receiver = receiver
'''配置郵件發送者等信息'''
def send_email(self,filename):
# 打開報告文件讀取文件內容
#filename = './report/'+ time.strftime('%Y-%m-%d %H_%M_%S')
f = open(filename,'r')
file_msg = f.read()
print(filename)
print(file_msg)
f.close()
# 郵件服務器
smtpserver = self.server
# 發件人用戶名和密碼
user = self.fromuser
password = self.frompassword
# 發件人
sender = self.sender
# 收件人
receiver = self.receiver
# 郵件主題
subject = 'Python test report'
# 郵件設置
msg = MIMEText(file_msg,'html','utf-8')
msg['subject'] = Header(subject,'utf-8')
msg['from'] = sender
# 連接服務器,登錄服務器,發送郵件
self.smtp = smtplib.SMTP()
self.smtp.connect(smtpserver)
self.smtp.login(user,password)
try:
self.smtp.sendmail(sender, receiver, msg.as_string())
except Exception as e:
print('send failed', e)
else:
print('send success!')
def __del__(self):
self.smtp.quit()
# 從文件中讀取郵件接收人信息
def read_SendToUserinfo_file(filename):
''' :param filename: 讀取接收郵件人信息 :return: 接手郵件人信息 '''
open_file = open(filename)
read_msg = open_file.read()
return read_msg
if __name__ == '__main__':
#send_email('./report/2018-07-16 13_09_21.txt')
read_msg = send_mail_init_info.read_SendToUserinfo_file(r'G:\suitUIUnittestDemo\SendToUserinfo.txt')
sendmail = send_mail_init_info('smtp.qq.com','[email protected]','gifhhsbgqyovbhhc','[email protected]',read_msg)
sendmail.send_email('./report/2018-07-16 13_09_21.txt')
1.剛測試def read_SendToUserinfo_file(filename) 方法有點問題,現在修改一下
def read_SendToUserinfo_file(filename):
''' :param filename: 讀取接收郵件人信息 :return: 接手郵件人信息 '''
open_file = open(filename)
#read_msg = open_file.read()
#return read_msg
for line in open_file:
msg = [i.strip() for i in line.split(',')]
print(msg)
return msg
SendToUserinfo.txt
[email protected],[email protected]