One . change
1. Add text document SendToUserinfo.txt It's used to save information about the recipient of the mail .
2. Modify the test report file name format and add reprot Catalog save test report .
3. Add code comments , Easier to read .
Two . Project directory
3、 ... and . Code
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 Handle '''
driver = webdriver.Chrome()
driver.maximize_window()
return driver
def load_url(driver,ele_dict):
''' :param driver: web Master page handle :param ele_dict: web Information dictionary ( Read from file ) :return: nothing '''
driver.get(ele_dict['Turl'])
time.sleep(5)
def find_element(driver,ele_dict):
''' :param driver: web Handle :param ele_dict: web Information dictionary ( Read from file ) :return: Returns the element found '''
driver.find_element_by_class_name(ele_dict['image_id']).click()
if 'text_id' in ele_dict:
driver.find_element_by_link_text(u' Sign in ').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 Elements :param arg: Variable length parameters , Receive user name and password :return: nothing '''
# 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()
# Judge whether the login is successful , And write the test report
def check_login(driver,ele_dict,log,userlist):
''' :param driver: web Handle :param ele_dict: Read element information ( Read in the file ) :param log: login_log object :param userlist: User information ( File read ) :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' account number :%s password :%s Prompt information :%s:failed\n' %(userlist['uname'],userlist['pwd'],err.text))
print('username or password error')
except:
print('login success!')
log.log_write(u' account number :%s password :%s :passed\n'%(userlist['uname'],userlist['pwd']))
#login_out(driver,ele_dict)
return True
return result
# Sign in
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():
# Call log file , And instantiate the class
log = login_log()
# call send_mail_init_info Medium read_SendToUserinfo_file Method , And instantiate
msg = send_mail_init_info.read_SendToUserinfo_file(r'G:\suitUIUnittestDemo\SendToUserinfo.txt')
# Call the whole send_mail_init_info Class method , And instantiate
sendmail = send_mail_init_info('smtp.qq.com','[email protected]','gifhhsbgqyovbhhc','[email protected]',msg)
#ele_dict = {'url': 'http://www.maiziedu.com/', 'text_id': ' Sign in ', 'user_id': 'id_account_l', 'pwd_id': 'id_password_l'
#, 'login_id': 'login_btn','image_id':'close-windows-btn7','error_id':'login-form-tips'}
# call webinfo file , And call webinfo Method , Instantiate function methods
ele_dict = webinfo(r'G:\suitUIUnittestDemo\webinfo.txt')
# call userinfo file , And call userinfo Method , Instantiate function methods
# user_list=[{'uname':account,'pwd':pwd}]
user_list = userinfo(r'G:\suitUIUnittestDemo\userinfo.txt')
# Instantiate the driver , call open_web
driver = open_web()
# call load_url Method , And instantiate from webinfo(ele_dict) Get the returned ele_dict['Turl'] data
# load url
load_url(driver,ele_dict)
# call find_element Method , When the input parameter is called webinfo(ele_dict), Get the returned location information
# find element
ele_tuple = find_element(driver,ele_dict)
# Call log file , call log_write Method
# send values
ftitle = time.strftime('%Y-%m-%d', time.gmtime())
log.log_write(U'\t\t\t%s Log in to the system test report \n' % (ftitle))
# Cyclic user test data
for userlist in user_list:
# call send_val Method ,ele_tuple Parameters are obtained instantiations ele_dict Location information value of ,
# Parameters userlist Is to call userinfo File and instantiate functions user_list Value data in
send_val(ele_tuple,userlist)
# call check_login Method
# check login success or failed
result = check_login(driver,ele_dict,log,userlist)
if result:
# call login_out Method
login_out(driver,ele_dict)
time.sleep(3)
ele_tuple = find_element(driver,ele_dict)
time.sleep(3)
# Call... In the log file instantiation check_login Method
log.log_close()
# Call the whole send_mail_init_info Class and instantiate sendmail, And call send_email Method ,
# And call the log file log Instantiation call filename Custom file format , Send the report to the specified mailbox
sendmail.send_email(log.filename)
driver.quit()
if __name__ == '__main__':
login_test()
log_fiile.py
# Test output report
import time
# Test report output interface
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
# Send test reports by email
import smtplib
from email.mime.text import MIMEText
from email.header import Header
# Email sending interface
class send_mail_init_info(object):
''' Mail configuration information '''
def __init__(self,server,fromuser,frompassword,sender,receiver):
self.server = server
self.fromuser = fromuser
self.frompassword = frompassword
self.sender = sender
self.receiver = receiver
''' Configure message sender and other information '''
def send_email(self,filename):
# Open the report file and read the contents of the file
#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()
# Mail server
smtpserver = self.server
# Sender username and password
user = self.fromuser
password = self.frompassword
# Sender
sender = self.sender
# The recipient
receiver = self.receiver
# Email subject
subject = 'Python test report'
# Email Settings
msg = MIMEText(file_msg,'html','utf-8')
msg['subject'] = Header(subject,'utf-8')
msg['from'] = sender
# Connect to server , logon server , Send E-mail
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()
# Read the recipient information from the file
def read_SendToUserinfo_file(filename):
''' :param filename: Read recipient information :return: Information about the person who received the mail '''
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. Rigid test def read_SendToUserinfo_file(filename) There is something wrong with the method , Let's change it now
def read_SendToUserinfo_file(filename):
''' :param filename: Read recipient information :return: Information about the person who received the mail '''
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]