One . explain : This project adopts the idea of process control , Not quoted unittest&pytest Unit testing framework, etc .
Two . Project introduction
1. Purpose : Test an official website login function module can be used normally .
2. Use cases
2.1. Enter the correct user name and password , Verify successful login
2.2. Enter a user name in the correct format and an incorrect password , Failed to verify login , And the message is correct
2.3. Enter a properly formatted user name and any password , Failed to verify login , And the message is correct
2.4. Both username and password are empty , Failed to verify login , And the message is correct
2.5. One of the user name and password is empty , Failed to verify login , And the message is correct
3. Environmental Science
Windows10 +Python3.6+selenium3.13+Pycharm
3.1. Environment most people will build , Find Baidu if you have anything , Search a basket , ha-ha ! When I first learned, I also had various problems , Fortunately, it has been solved , Thank you for your strong existence ! There is no need to write about how to build the environment , Go straight to the point .
3、 ... and . Script design
1. Purpose
The test script should achieve : Script portability , Script modularization , Test data separation , Output test report, etc
2. Script design pattern
3. Code implementation
3.1. Project directory structure
3.2. notes : The following files are stored in the same directory
login_test.py
# Automatic test case script of the login module of Maizi University
import time
from selenium import webdriver
from webinfo import webinfo
from userinfo import userinfo
from log_file import login_log
from pathlib import Path
from pathlib2 import Path
def open_web():
driver = webdriver.Chrome()
driver.maximize_window()
return driver
def load_url(driver,ele_dict):
# Call instantiation ele_dict, Get the returned specified information value
driver.get(ele_dict['Turl'])
time.sleep(5)
def find_element(driver,ele_dict):
# Call instantiation ele_dict, Get the returned location value of the specified information
# find element
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):
# ele_tuple Parameters are obtained instantiations ele_dict Location information value of
# 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):
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
def login_out(driver,ele_dict):
driver.find_element_by_class_name(ele_dict['logout']).click()
''' def screen_shot(err): i = 0 save_path = r'G:\suitUIUnittestDemo' 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()
#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))
#
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()
driver.quit()
if __name__ == '__main__':
login_test()
log_file.py
# Test output report
import time
class login_log(object):
def __init__(self,path='',mode='w'):
filename = path + time.strftime('%Y-%m-%d',time.gmtime())
self.log = open(path+filename+'.txt',mode)
def log_write(self,msg):
self.log.write(msg)
def log_close(self):
self.log.close()
if __name__ == '__main__':
log = login_log()
ftitle = time.strftime('%Y-%m-%d',time.gmtime())
print(ftitle)
log.log_write('xiaochao11520')
log.log_close()
webinfo.txt
Turl = https://mail.126.com
text_id = Sign in
userid = id_account_l
pwdid = id_password_l
loginid = login_btn
error = login-form-tips
logout = sign_out
image_id = close-windows-btn7
webinfo.py
# Read from a text document web Elements
import codecs
def webinfo(path):
file = codecs.open(path,'r','utf-8')
ele_dict = {
}
for line in file:
result = [ele.strip() for ele in line.split('=')]
ele_dict.update(dict([result]))
return ele_dict
if __name__ == '__main__':
ele_dict = webinfo(r'G:\suitUIUnittestDemo\webinfo.txt')
for key in ele_dict:
print(key,ele_dict[key])
userinfo.txt
uname = linuxxiaochao;pwd=xiaochao11520
uname = 273839363;pwd=xiaochao11520
uname = ;pwd=xiaochao11520
uname = [email protected];pwd=
uname = 2738;pwd=xiaochao
userinfo.py
# Read user information from text documents
import codecs
def userinfo(path):
file = codecs.open(path,'r','utf-8')
user_list = []
for line in file:
user_dict = {
}
result = [ele.strip() for ele in line.split(';')]
for sult in result:
re_sult = [ele.strip() for ele in sult.split('=')]
user_dict.update(dict([re_sult]))
user_list.append(user_dict)
return user_list
if __name__ == '__main__':
user_list = userinfo(r'G:\suitUIUnittestDemo\userinfo.txt')
print(user_list)