One . Preface
1. The project is a test of our company's internal system , Only internal network access , The external network is not accessible
2. ask :
2.1. The external network is not accessible , The code doesn't work either , It depends on what the project is for .
2.2. How to learn this project .
2.3. How to learn automated testing (Python+Selenium).
3. answer :
3.1. The code doesn't matter , I hope that after watching this project completely , I will have ideas and ideas , Learn the framework and design ideas of this project , Apply these to your own projects , So the goal is achieved ( Some of the common methods involved in the project can be run separately , You can use it in your own projects ).
3.2. First of all, I hope you can learn this project with a goal :
a. Directory structure of the project ( What's in each catalog ).
b. How the project uses the framework ( This project uses unittest frame ).
c. How design patterns are applied in this project ( Application of this project page object Design patterns ).
3. personally
3.1. If there is no programming foundation , It is suggested to learn a programming language first , Including the construction of the environment , Write your own code , Think more about problems , This will definitely deepen my impression . If you have a certain programming foundation, look directly at Python Basic grammar and selenium Just ok.
3.2. Build your own framework , A practical project , At this time, you will find that you still have a lot of things that won't , So here comes the line , Learn where you can't , Learn and write , Until your project is finished , Once again, you will find that you will be a lot , Of course not, there are more things, because your ideas are gradually broadened , You think of being unattended , The idea of integration and so on .
3.3. You can participate in the training of training institutions , To be honest, there are more and more training institutions , In my opinion, the teachers in some institutions are not up to standard , Because what they teach is the foundation, there is not much content to improve , But one thing is good , You can systematically learn a series of automation knowledge .
Two . Project brief introduction
1. Project name :** The company's e-retail membership system
2. Project purpose : Realize the automatic test execution of e-retail member system project
3. Project version :v1.0
3、 ... and . Project directory
Retail_TestPro
docs# Store project related documents
01 test plan
02 Test outline
03 The test case
04 Test report
05 Test progress
06 Technical documentation
07 Test request
package# Store third party plug-ins
HTMLTestRunner.py
retail
config
__init__.py
conf.py# Read the configuration file to get the project and directory path And get the path of all the directory files you want to use
config.ini# The path to store the project and directory
data
TestData
__init__.py
elementDate.xlsx# Store all the element information and test data in the project
mail_receiver.txt# Store the recipient information of the mail
report# Test report
image
Fail# Store a screenshot of a use case when it fails to execute
Pass# Store the screenshot of the successful execution of the use case
Log# Store... In the execution process of the use case log Information
TestReport# Store test reports generated after test case execution
test_case# Test case information
models # Store some public methods
doconfini.py# read configuration file
doexcel.py# read excel file
driver.py# Deposit driver
log.py# Generate log
myunittest.py# Inherit unittest.Testcase
sendmail.py# Send E-mail
strhandle.py# string manipulation
Tcinfo.py# Basic information of test case
Testreport.py# Test report
page_obj# Test module
Activerule_page.py
Base_page.py
Company_page.py
Createrule_page.py
Memberquery_page.py
Modifypw_page.py
Pointquery_page.py
ActiveRuleTc.py
CompanyQueryTc.py
CreateRuleTc.py
LoginTc.py
MemberQueryTc.py
ModifyPwTc.py
PointQueryTc.py
runTc.py# Execute test case
Four . Project environment
1.python 36
2.pip insatll selenium
3.PyCharm 2017.2.4
4.Windows 10 10.0
5.HTMLTestRunner.py
5、 ... and . The project framework
1.unittest Unit test framework
2.pageobject Design patterns
3.UI Object library thinking
6、 ... and . Project design
1. A module ( The page of the project under test ) Corresponding to one py File and a test class ( The test file )
2. Every test page ( System page ) Store page elements and functions involved in this page in
3. Each use case is combined into a test class to generate a py file
7、 ... and . Project objectives
1. When writing an automated test project, you must think about the functions of the script , Whether a large number of modification scripts are required when page elements are frequently changed , And whether to modify the script when testing different data , Then I can think of these initial goals .
1.1. Generate test case execution result report
1.2. Generate test case execution log
1.3. If the execution of the use case fails or the e-mail report is automatically sent after the execution is completed
1.4. Capture the picture when the use case fails or succeeds
1.5. Data driven ( Read test data , Reduce script maintenance costs )
8、 ... and . Project code
config.ini
# Store items and paths
[project]
project_path = G:\Petrochina_Retail_Test_Project
conf.py
import os
import sys
from retail.test_case.models.doconfIni import DoConfIni
# Get the current path
currPath= \
os.path.split(os.path.realpath(__file__))[0]
print(currPath)
# Read the configuration file to get the project path
readConfig = \
DoConfIni()
print(readConfig)
proPath = \
readConfig.getConfValue(os.path.join(currPath,'config.ini'),'project','project_path')
print(proPath)
# Get log path
logPath= \
os.path.join(proPath,'retail','report','Log')
print(logPath)
# Test case path
tcPath = \
os.path.join(proPath,'retail','test_case')
print(tcPath)
# Get report path
reportPath= \
os.path.join(proPath,'retail','report','TestReport')
print(reportPath)
# Get test data path
dataPath= \
os.path.join(proPath,'retail','data','TestData')
print(dataPath)
# Save the screenshot path
# Error screenshots
failImagePath = os.path.join(proPath, 'retail', 'report', 'image','fail')
print(failImagePath)
# Screenshot of success
passImagePath = os.path.join(proPath, 'retail', 'report', 'image','pass')
print(passImagePath)
# The name of the called function
funcName = sys._getframe().f_code.co_name
print(funcName)
# Line number of the called function
funcNo = sys._getframe().f_back.f_lineno
print(funcNo)
# The file name of the called function
funcFile= sys._getframe().f_code.co_filename
print(funcFile)
2.elementData.xlsx # Store all test data and elements
3.mail_receiver.txt# Store the account number of the email recipient , You can add multiple accounts to ‘,’ Division of no.
**@qq.com
4. Public methods models The following file methods
doconfini.py
import logging
import configparser
from retail.config.conf import *
from retail.test_case.models.log import Logger
log = Logger(__name__, CmdLevel=logging.INFO, FileLevel=logging.INFO)
class DoConfIni(object):
def __init__(self):
""" :param filename: """
self.cf = configparser.ConfigParser()
# from ini Read data in file
def getConfValue(self,filename,section,name):
""" :param config: :param name: :return: """
try:
self.cf.read(filename)
value = self.cf.get(section,name)
except Exception as e:
log.logger.exception('read file [%s] for [%s] failed , did not get the value' %(filename,section))
raise e
else:
log.logger.info('read excel value [%s] successed! ' %value)
return value
# towards ini Write data in file
def writeConfValue(self,filename, section, name, value):
""" :param section: section :param name: value name :param value: value :return: none """
try:
self.cf.add_section(section)
self.cf.set(section, name, value)
self.cf.write(open(filename, 'w'))
except Exception :
log.logger.exception('section %s has been exist!' %section)
raise configparser.DuplicateSectionError(section)
else:
log.logger.info('write section'+section+'with value '+value+' successed!')
if __name__ == '__main__':
file_path = currPath
print(file_path)
read_config = DoConfIni()
value = read_config.getConfValue(os.path.join(currPath,'config.ini'),'project','project_path')
print(value)
read_config.writeConfValue(os.path.join(currPath,'config.ini'),'tesesection', 'name', 'hello word')
doexcel.py
import xlrd
import os
import logging
from retail.config import conf
from retail.test_case.models.log import Logger
log = Logger(__name__, CmdLevel=logging.INFO, FileLevel=logging.INFO)
class ReadExcel(object):
def __init__(self,fileName='elementDate.xlsx',sheetName='elementsInfo'):
""" :param fileName: :param sheetName: """
try:
self.dataFile = os.path.join(conf.dataPath, fileName)
self.workBook = xlrd.open_workbook(self.dataFile)
self.sheetName = self.workBook.sheet_by_name(sheetName)
except Exception:
log.logger.exception('init class ReadExcel fail', exc_info=True)
raise
else:
log.logger.info('initing class ReadExcel')
# read excel Data in
def readExcel(self,rownum,colnum):
""" :param rownum: :param colnum: :return: """
try:
value = self.sheetName.cell(rownum,colnum).value
except Exception:
log.logger.exception('read value from excel file fail', exc_info=True)
raise
else:
log.logger.info('reading value [%s] from excel file [%s] completed' %(value, self.dataFile))
return value
if __name__ == '__main__':
cellValue = ReadExcel().readExcel(1,3)
print((cellValue))
log.py
import logging
import time
class Logger(object):
def __init__(self,logger, CmdLevel=logging.INFO, FileLevel=logging.INFO):
""" :param logger: :param CmdLevel: :param FileLevel: :return: """
self.logger = logging.getLogger(logger)
self.logger.setLevel(logging.DEBUG) # Set the default level of log output
# Log output format
fmt = logging.Formatter('%(asctime)s - %(filename)s:[%(lineno)s] - [%(levelname)s] - %(message)s')
# Log file name
#self.LogFileName = os.path.join(conf.log_path, "{0}.log".format(time.strftime("%Y-%m-%d")))# %H_%M_%S
currTime = time.strftime("%Y-%m-%d")
self.LogFileName = r'D:\Petrochina_Retail_Test_Project\retail\report\Log\log'+currTime+'.log'
# Set console output
#sh = logging.StreamHandler()
#sh.setFormatter(fmt)
#sh.setLevel(CmdLevel)# The level of logging
# Set file output
fh = logging.FileHandler(self.LogFileName)
fh.setFormatter(fmt)
fh.setLevel(FileLevel) # The level of logging
#self.logger.addHandler(sh)
self.logger.addHandler(fh)
def debug(self, message):
""" :param message: :return: """
self.logger.debug(message)
def info(self,message):
""" :param message: :return: """
self.logger.info(message)
def warn(self,message):
""" :param message: :return: """
self.logger.warning(message)
def error(self,message):
""" :param message: :return: """
self.logger.error(message)
def criti(self,message):
""" :param message: :return: """
self.logger.critical(message)
if __name__ == '__main__':
logger = Logger("fox",CmdLevel=logging.DEBUG, FileLevel=logging.DEBUG)
logger.logger.debug("debug")
#ERROR,log journal error
logger.logger.log(logging.ERROR,'%(module)s %(info)s',{
'module':'log journal ','info':'error'})
sendmail.py
import smtplib
from email.mime.text import MIMEText
from email.header import Header
import os
from retail.config import conf
from retail.test_case.models.log import Logger
log = Logger(__name__)
# Email sending interface
class SendMail(object):
''' Mail configuration information '''
def __init__(self,
receiver,
subject='Retail System test report ',
server='smtp.qq.com',
fromuser='[email protected]',
frompassword='gifhhsbgqyovbhhc',
sender='[email protected]'):
""" :param receiver: :param subject: :param server: :param fromuser: :param frompassword: :param sender: :return: """
self._server = server
self._fromuser = fromuser
self._frompassword = frompassword
self._sender = sender
self._receiver = receiver
self._subject = subject
def sendEmail(self, fileName):
""" :param fileName: :return: """
# Open the report file and read the contents of the file
try:
f = open(os.path.join(conf.reportPath, fileName), 'rb')
fileMsg = f.read()
except Exception:
log.logger.exception('open or read file [%s] failed,No such file or directory: %s' %(fileName, conf.reportPath))
log.logger.info('open and read file [%s] successed!' %fileName)
else:
f.close()
# Email subject
subject = 'Python test report'
# Email Settings
msg = MIMEText(fileMsg, 'html', 'utf-8')
msg['subject'] = Header(subject, 'utf-8')
msg['from'] = self._sender
# Connect to server , logon server , Send E-mail
try:
smtp = smtplib.SMTP()
smtp.connect(self._server)
smtp.login(self._fromuser, self._frompassword)
except Exception:
log.logger.exception('connect [%s] server failed or username and password incorrect!' %smtp)
else:
log.logger.info('email server [%s] login success!' %smtp)
try:
smtp.sendmail(self._sender, self._receiver, msg.as_string())
except Exception:
log.logger.exception('send email failed!')
else:
log.logger.info('send email successed!')
# Read the recipient information from the file
def getReceiverInfo(fileName):
''' :param filename: Read recipient information :return: Recipient information '''
try:
openFile = open(os.path.join(conf.dataPath, fileName))
except Exception:
log.logger.exception('open or read file [%s] failed,No such file or directory: %s' %(fileName, conf.dataPath))
else:
log.logger.info('open file [%s] successed!' %fileName)
for line in openFile:
msg = [i.strip() for i in line.split(',')]
log.logger.info('reading [%s] and got receiver value is [%s]' %(fileName, msg))
return msg
if __name__ == '__main__':
readMsg = getReceiverInfo('mail_receiver.txt')
#readMsg = SendMail.getReceiverInfo('mail_receiver.txt')
sendmail = SendMail(readMsg)
sendmail.sendEmail('2018-09-21 17_44_04.html')
strhandle.py
import logging
from retail.test_case.models.log import Logger
log = Logger(__name__, CmdLevel=logging.INFO, FileLevel=logging.INFO)
def strhandle(str):
""" :param str: :return: """
# Initialization character 、 Numbers 、 Space 、 Count of special characters
try:
lowerCase = 0
upperCase = 0
number = 0
other = 0
for stritem in str:
# If there are lowercase letters in the string , So the number of lowercase letters +1
if stritem.islower():
lowerCase += 1
# If there are numbers in the string , So the number of numbers +1
elif stritem.isdigit():
number += 1
# Capital
elif stritem.isupper():
upperCase +=1
# If there are spaces in the string , So the number of spaces +1
else:
other += 1
return lowerCase, upperCase, number, other
except Exception as e:
log.logger.exception('string handle error , please check!', exc_info=True)
raise e
if __name__=='__main__':
list = ['qwert','erwer']
lowercase, uppercase, number, other = strhandle(list[0])
print (u" The lowercase letters in the string are :%d" %lowercase)
print (u" The big letters in the string are :%d" %uppercase)
print (u" The numbers in the string are :%d" %number)
print (u" The special characters in this string are :%d" %other)
testreport.py
import time
import logging
import unittest
from BeautifulReport import BeautifulReport
import HTMLTestRunner
from retail.config import conf
from retail.test_case.models.log import Logger
log = Logger(__name__, CmdLevel=logging.INFO, FileLevel=logging.INFO)
# use HTMLTestRunner Implementation test report
def testreport():
currTime = time.strftime('%Y-%m-%d %H_%M_%S')
fileName = conf.reportPath + r'\report' + currTime + '.html'
try:
fp = open(fileName, 'wb')
except Exception :
log.logger.exception('[%s] open error cause Failed to generate test report' %fileName)
else:
runner = HTMLTestRunner.HTMLTestRunner\
(stream=fp, title=u'Retail sys Test report ',
description=u' processor :Intel(R) Core(TM) ''i5-6200U CPU @ 2030GHz 2.40 GHz 'u' Memory :8G System type : 64 position edition : windows 10 Family Chinese ')
log.logger.info('successed to generate test report [%s]' %fileName)
return runner, fp, fileName
def addTc(TCpath = conf.tcPath, rule = '*TC.py'):
""" :param TCpath: Test case storage path :param rule: Matching test case files :return: test suite """
discover = unittest.defaultTestLoader.discover(TCpath, rule)
return discover
# use BeautifulReport Module implementation test report
def runTc(discover):
""" :param discover: test suite :return: """
currTime = time.strftime('%Y-%m-%d %H_%M_%S')
fileName = currTime+'.html'
try:
result = BeautifulReport(discover)
result.report(filename=fileName, description=' Test report ', log_path=conf.reportPath)
except Exception:
log.logger.exception('Failed to generate test report', exc_info=True)
else:
log.logger.info('successed to generate test report [%s]' % fileName)
return fileName
if __name__ == '__main__':
testreport()
suite = addTc(rule = '*TC.py')
runTc(suite)
driver.py
from selenium import webdriver
import logging
import sys
from retail.test_case.models.log import Logger
log = Logger(__name__, CmdLevel=logging.INFO, FileLevel=logging.INFO)
class WDriver(object):
def fireFoxDriver(self):
try:
self.driver = webdriver.Firefox()
except Exception as e:
log.logger.exception('FireFoxDriverServer.exe executable needs to be in PATH. Please download!', exc_info=True)
raise e
else:
log.logger.info('%s:found the Firefox driver [%s] successed !' %(sys._getframe().f_code.co_name,self.driver))
return self.driver
# chrom driver
def chromeDriver(self):
try:
#option = webdriver.ChromeOptions() # Implementation does not open browser perform web Automated test scripts
#option.add_argument('headless')#
#self.driver = webdriver.Chrome(chrome_options=option)
self.driver = webdriver.Chrome()
except Exception as e:
log.logger.exception('ChromeDriverServer.exe executable needs to be in PATH. Please download!',exc_info=True)
raise e
else:
log.logger.info('%s:found the chrome driver [%s] successed !' % (sys._getframe().f_code.co_name, self.driver))
return self.driver
# Ie driver
def ieDriver(self):
try:
self.driver = webdriver.Ie()
except Exception as e:
log.logger.exception('IEDriverServer.exe executable needs to be in PATH. Please download!',exc_info=True)
raise e
else:
log.logger.info('%s:found the IE driver [%s] successed !' % (sys._getframe().f_code.co_name, self.driver))
return self.driver
if __name__ == '__main__':
WDrive=WDriver()
WDrive.fireFoxDriver()
myunittest.py
from retail.test_case.models.driver import WDriver
import logging
import unittest
from retail.test_case.page_obj.login_page import LoginPage
from retail.test_case.models.log import Logger
from selenium import webdriver
log = Logger(__name__, CmdLevel=logging.INFO, FileLevel=logging.INFO)
class MyunitTest(unittest.TestCase):
@classmethod
# A test class ( file ) Execute once to open the browser , Save the time to open the browser once per use case
def setUpClass(cls):
#cls.driver = WDriver().fireFoxDriver()
cls.driver = WDriver().chromeDriver()
cls.driver.maximize_window()
log.logger.info('opened the browser successed!')
def setUp(self):
self.login = LoginPage(self.driver)
self.login.open()
log.logger.info('************************starting run test cases************************')
def tearDown(self):
self.driver.refresh()
log.logger.info('************************test case run completed************************')
@classmethod
def tearDownClass(cls):
cls.driver.quit()
log.logger.info('quit the browser success!')
if __name__ == '__main__':
unittest.main()
Nine . All the public methods needed have been written , Later, we need other methods to add . Let's start writing test cases , Because of the use of PageObject Pattern , So we need to design a basepage page , All pages or modules inherit this basepage,basepage Mainly write all the pages of the public method .
base_page.py
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import os
import logging
import sys
from retail.test_case.models.log import Logger
from retail.config import conf
from retail.test_case.models.doexcel import ReadExcel
# Store all the element data of the system
eleData = ReadExcel()
# Login module test data
testLoginData = ReadExcel('elementDate.xlsx', 'userNamePw')
# Modify password module test data
modifyPwData = ReadExcel('elementDate.xlsx', 'modifyPw')
queryData = ReadExcel('elementDate.xlsx', 'queryData')
log = Logger(__name__, CmdLevel=logging.INFO, FileLevel=logging.INFO)
class BasePage(object):
""" The main menu """
menuList = \
[(By.LINK_TEXT, eleData.readExcel(7, 3)), # Rights management
(By.LINK_TEXT, eleData.readExcel(8, 3)), # Member profile
(By.LINK_TEXT, eleData.readExcel(9, 3)), # Points consumption query
(By.LINK_TEXT, eleData.readExcel(10, 3)), # Function demonstration
(By.LINK_TEXT, eleData.readExcel(11, 3)), # To do work
(By.LINK_TEXT, eleData.readExcel(12, 3)), # report form
(By.LINK_TEXT, eleData.readExcel(13, 3)), # The rule of points / Activity query
(By.LINK_TEXT, eleData.readExcel(14, 3))] # The rule of points / Activity application
def __init__(self, driver,url='http://11.11.164.134:9081/rmms/modules/ep.rmms.portal/login/login.jsp'):
self.driver = driver
self.base_url = url
def _open(self,url):
try:
self.driver.get(url)
self.driver.implicitly_wait(10)
except Exception as e:
log.logger.exception(e, exc_info=True)
raise ValueError('%s address access error, please check!' %url)
else:
log.logger.info('%s is accessing address %s at line[46]' %(sys._getframe().f_code.co_name,url))
def open(self):
self._open(self.base_url)
log.logger.info('%s loading successed!' %self.base_url)
return self.base_url
# *loc Represents any number of positional parameters
def findElement(self, *loc):
""" Find a single element """
try:
WebDriverWait(self.driver,10).until(EC.visibility_of_element_located(loc))
#log.logger.info('The page of %s had already find the element %s'%(self,loc))
#return self.driver.find_element(*loc)
except Exception as e:
log.logger.exception('finding element timeout!, details' ,exc_info=True)
raise e
else:
log.logger.info('The page of %s had already find the element %s' % (self, loc))
return self.driver.find_element(*loc)
def findElements(self, *loc):
""" Find a set of elements """
try:
WebDriverWait(self.driver,10).until(EC.visibility_of_element_located(loc))
#log.logger.info('The page of %s had already find the element %s' % (self, loc))
#return self.driver.find_elements(*loc)
except Exception as e:
log.logger.exception('finding element timeout!, details', exc_info=True)
raise e
else:
log.logger.info('The page of %s had already find the element %s' % (self, loc))
return self.driver.find_elements(*loc)
def inputValue(self, inputBox, value):
""" Later modify other pages directly call this function """
inputB = self.findElement(*inputBox)
try:
inputB.clear()
inputB.send_keys(value)
except Exception as e:
log.logger.exception('typing value error!', exc_info=True)
raise e
else:
log.logger.info('inputValue:[%s] is receiveing value [%s]' % (inputBox, value))
# Get element data
def getValue(self, *loc):
element = self.findElement(*loc)
try:
value = element.text
#return value
except Exception:
#element = self.find_element_re(*loc) # 2018.09.21 for log
value = element.get_attribute('value')
log.logger.info('reading the element [%s] value [%s]' % (loc, value))
return value
except:
log.logger.exception('read value failed', exc_info=True)
raise Exception
else:
log.logger.info('reading the element [%s] value [%s]' % (loc,value))
return value
def getValues(self, *loc):
value_list = []
try:
for element in self.findElements(*loc):
value = element.text
value_list.append(value)
except Exception as e:
log.logger.exception('read value failed', exc_info=True)
raise e
else:
log.logger.info('reading the element [%s] value [%s]'% (loc,value_list))
return value_list
# perform js Script
def jScript(self,src):
try:
self.driver.excute_script(src)
except Exception as e:
log.logger.exception('execute js script [%s] failed ' %src)
raise e
else:
log.logger.info('execute js script [%s] successed ' %src)
# Determine whether an element exists
def isElementExist(self, element):
try:
WebDriverWait(self.driver, 10).until(EC.visibility_of_element_located(element))
except:
#log.logger.exception('The element [%s] not exist', exc_info=True)
return False
else:
#log.logger.info('The element [%s] have existed!' %element)
return True
# Screenshot
def saveScreenShot(self, filename):
list_value = []
list = filename.split('.')
for value in list:
list_value.append(value)
if list_value[1] == 'png' or list_value[1] == 'jpg' or list_value[1] == 'PNG' or list_value[1] == 'JPG':
if 'fail' in list_value[0].split('_'):
try:
self.driver.save_screenshot(os.path.join(conf.failImagePath, filename))
except Exception:
log.logger.exception('save screenshot failed !', exc_info=True)
else:
log.logger.info('the file [%s] save screenshot successed under [%s]' % (filename, conf.failImagePath))
elif 'pass' in list_value[0]:
try:
self.driver.save_screenshot(os.path.join(conf.passImagePath, filename))
except Exception:
log.logger.exception('save screenshot failed !', exc_info=True)
else:
log.logger.info('the file [%s] save screenshot successed under [%s]' % (filename, conf.passImagePath))
else:
log.logger.info('save screenshot failed due to [%s] format incorrect' %filename)
else:
log.logger.info('the file name of [%s] format incorrect cause save screenshot failed, please check!' % filename)
# Accept the error box
def accept(self, *loc):
self.findElement(*loc).click()
log.logger.info('closed the error information fram successed!')
if __name__ == '__main__':
pass
1. The login page
login_page.py
from selenium.webdriver.common.by import By
import logging
import sys
from retail.test_case.page_obj.base_page import BasePage, eleData, testLoginData
from retail.test_case.models.log import Logger
log = Logger(__name__, CmdLevel=logging.INFO, FileLevel=logging.INFO)
class LoginPage(BasePage):
""" user name , password , The login button , Save information , Error message """
userNameEle = (By.ID, eleData.readExcel(1, 3))
passWordEle = (By.ID, eleData.readExcel(2, 3))
loginBtnEle = (By.ID, eleData.readExcel(3, 3))
saveInfoEle = (By.NAME, eleData.readExcel(4, 3))
errorMessage = (By.ID, eleData.readExcel(5, 3))
quitBtn = (By.ID, eleData.readExcel(6, 3))
# User name and password
unpwData = \
[[testLoginData.readExcel(1, 0), testLoginData.readExcel(1, 1)], # The right user name and the right password
[testLoginData.readExcel(2, 0), testLoginData.readExcel(2, 1)], # Wrong user name and correct password
[testLoginData.readExcel(3, 0), testLoginData.readExcel(3, 1)], # Empty user name and correct password
[testLoginData.readExcel(4, 0), testLoginData.readExcel(4, 1)], # Wrong user name and wrong password
[testLoginData.readExcel(5, 0), testLoginData.readExcel(5, 1)], # Correct user name and empty password
[testLoginData.readExcel(6, 0), testLoginData.readExcel(6, 1)], # Correct user name and wrong password
[testLoginData.readExcel(7, 0), testLoginData.readExcel(7, 1)]] # Empty user name and password
# The login button
def clickLoginBtn(self):
element = self.findElement(*self.loginBtnEle)
element.click()
log.logger.info('%s ,logining....!' % sys._getframe().f_code.co_name)
# Prompt when login fails
def getFailedText(self):
info = self.findElement(*self.errorMessage).text
log.logger.info('login failed : %s' %info)
return info
# Pop up when login fails alert
def handleAlert(self):
try:
alert = self.driver.switch_to_alert()
text = alert.text
alert.accept()
except Exception:
log.logger.exception('handle alert failed, please check the details' ,exc_info=True)
raise
else:
log.logger.info('login failed ,%s handle alert successed alert info: %s!' %(sys._getframe().f_code.co_name, text))
return text
# Unified login function
def loginFunc(self, username='rmln', password='[email protected]#'):
self.inputValue(self.userNameEle, username)
self.inputValue(self.passWordEle, password)
self.clickLoginBtn()
# Clear input box data
def clearValue(self, element):
empty = self.findElement(*element)
empty.clear()
log.logger.info('emptying value.......')
# sign out
def quit(self):
self.findElement(*self.quitBtn).click()
log.logger.info('quit')
if __name__ == '__main__':
pass
2. Login test cases
LoginTc.py
import unittest
import time
import logging
import sys
from retail.test_case.models.myunittest import MyunitTest
from retail.test_case.models.log import Logger
log = Logger(__name__, CmdLevel=logging.INFO, FileLevel=logging.INFO)
class Login_TC(MyunitTest):
""" Login module test case """
def test_login_success_correct_username_password(self):
""" The user name is correct , The password is correct , Login successful """
self.login.loginFunc()
# Get current url Address
currUrl = self.driver.current_url
try:
self.assertIn('main', currUrl, 'main not in current url!')
except Exception:
self.login.saveScreenShot('correct_username_password_fail.png')
raise
else:
self.login.saveScreenShot('correct_username_password_pass.png')
log.logger.info('%s->run completed! please check the test report' % (sys._getframe().f_code.co_name))
def test_login_failed_incorrect_username(self):
""" User name error , The password is correct , Login failed """
self.login.loginFunc(self.login.unpwData[1][0], self.login.unpwData[1][1])
failText = self.login.getFailedText()
self.assertEqual(u' Wrong user name or password , Please re-enter !', failText, u' The prompt message is wrong ')
log.logger.info('%s->run completed! please check the test report' % (sys._getframe().f_code.co_name))
def test_login_failed_incorrect_password(self):
""" The user name is correct , Wrong password , Login failed """
self.login.loginFunc(self.login.unpwData[5][0], self.login.unpwData[5][1])
failText = self.login.getFailedText()
self.assertEqual(u' Wrong user name or password , Please re-enter !', failText, u' The prompt message is wrong ')
log.logger.info('%s->run completed! please check the test report' % (sys._getframe().f_code.co_name))
def test_login_failed_username_password_blank(self):
""" User name is empty , The password is empty. , Login failed """
self.login.loginFunc(self.login.unpwData[6][0], self.login.unpwData[6][1])
failText = self.login.handleAlert() # obtain alert A reminder of
self.assertEqual(u' Please fill in the user name ', failText, u' The prompt message is wrong ')
log.logger.info('%s->run completed! please check the test report' % (sys._getframe().f_code.co_name))
def test_login_failed_password_blank(self):
""" The user name is correct , The password is empty. , Login failed """
self.login.loginFunc(self.login.unpwData[4][0], self.login.unpwData[4][1])
failText = self.login.handleAlert() # obtain alert A reminder of
self.assertEqual(u' Please fill in the user password ', failText, u' The prompt message is wrong ')
log.logger.info('%s->run completed! please check the test report' % (sys._getframe().f_code.co_name))
def test_login_failed_unpw_incorrect(self):
""" User name error , Wrong password , Login failed """
self.login.loginFunc(self.login.unpwData[3][0], self.login.unpwData[4][0])
failText = self.login.getFailedText()
self.assertEqual (u' Wrong user name or password , Please re-enter !', failText, 'failed')
log.logger.info('%s->run completed! please check the test report' % (sys._getframe().f_code.co_name))
def test_login(self):
""" Loop test login function """
for listitem in self.login.unpwData:
self.login.inputValue(self.login.userNameEle,listitem[0])
time.sleep(2)
self.login.inputValue(self.login.passWordEle,listitem[1])
time.sleep(2)
self.login.clickLoginBtn()
time.sleep(2)
if listitem[0] =='rmln' and listitem[1] == '[email protected]#':
currUrl = self.driver.current_url
self.assertIn ('main' , currUrl)
self.login.quit()
elif listitem[0] == 'rmln' and listitem[1] != '[email protected]#':
if listitem[1] == '':
failText = self.login.handleAlert() # obtain alert A reminder of
self.assertEqual(u' Please fill in the user password ', failText, u' The prompt message is wrong ')
else:
failText = self.login.getFailedText()
self.assertEqual(u' Wrong user name or password , Please re-enter !', failText, u' The prompt message is wrong ')
elif listitem[0] != 'rmln' and listitem[1] == '[email protected]#':
if listitem[0]=='':
failText = self.login.handleAlert() # obtain alert A reminder of
self.assertEqual(u' Please fill in the user name ', failText, u' The prompt message is wrong ')
else:
failText = self.login.getFailedText()
self.assertEqual(u' Wrong user name or password , Please re-enter !', failText, u' The prompt message is wrong ')
elif listitem[0] == listitem[1] == '':
failText = self.login.handleAlert() # obtain alert A reminder of
self.assertEqual(u' Please fill in the user name ', failText, ' The prompt message is wrong ')
else:
failText = self.login.getFailedText()
self.assertEqual(u' Wrong user name or password , Please re-enter !', failText, u' The prompt message is wrong ')
log.logger.info('%s->run completed! please check the test report' % (sys._getframe().f_code.co_name))
if __name__ == '__main__':
unittest.main()
3. Change password page
modifypw_page.py
import logging
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from retail.test_case.page_obj.base_page import BasePage, eleData, modifyPwData
from retail.test_case.models.log import Logger
log = Logger(__name__, CmdLevel=logging.INFO, FileLevel=logging.INFO)
class PrimaryMenu(BasePage):
""" Password data """
pwdList = \
[[modifyPwData.readExcel(1, 0), modifyPwData.readExcel(1, 1), modifyPwData.readExcel(1, 2)],
[modifyPwData.readExcel(2, 0), modifyPwData.readExcel(2, 1), modifyPwData.readExcel(2, 2)],
[modifyPwData.readExcel(3, 0), modifyPwData.readExcel(3, 1), modifyPwData.readExcel(3, 2)],
[modifyPwData.readExcel(4, 0), modifyPwData.readExcel(4, 1), modifyPwData.readExcel(4, 2)],
[modifyPwData.readExcel(5, 0), modifyPwData.readExcel(5, 1), modifyPwData.readExcel(5, 2)]]
""" Rights management drop down menu """
menuPersonal = (By.LINK_TEXT, eleData.readExcel(15, 3))
menuModifyPwd = (By.LINK_TEXT, eleData.readExcel(16, 3))
""" Password change """
oldPwd = (By.ID, eleData.readExcel(17, 3))
newPwd = (By.ID, eleData.readExcel(18, 3))
commitPwd = (By.ID, eleData.readExcel(19, 3))
""" Error box and OK """
errMessage = (By.XPATH, eleData.readExcel(20, 3))
closeBtn = (By.CSS_SELECTOR, eleData.readExcel(21, 3))
""" Password description """
readMe = (By.ID, eleData.readExcel(22, 3))
""" preservation """
saveBtn = (By.XPATH, eleData.readExcel(23, 3))
# The main menu
def findMenu(self,*menuList):
return self.findElement(*menuList)
# Old password input box
def inputOldPw(self, oldPwd=''):
try:
self.findElement(*self.oldPwd).clear()
self.findElement(*self.oldPwd).send_keys(oldPwd)
except Exception:
log.logger.exception('input Pw [%s] for oldPw [%s] fail' %(oldPwd, self.oldPwd))
raise
else:
log.logger.info('inputing Pw [%s] for oldPw [%s] ' % (oldPwd, self.oldPwd))
# New password input box
def inputNewPw(self, newPwd=''):
try:
self.findElement(*self.newPwd).clear()
self.findElement(*self.newPwd).send_keys(newPwd)
except Exception:
log.logger.exception('input Pw [%s] for newPw [%s] fail' % (newPwd, self.newPwd))
raise
else:
log.logger.info('inputing Pw [%s] for newPw [%s] ' % (newPwd, self.newPwd))
# Confirm password input box
def inputConfirmPw(self, confirmPwd=''):
try:
self.findElement(*self.commitPwd).clear()
self.findElement(*self.commitPwd).send_keys(confirmPwd)
except Exception:
log.logger.exception('input Pw [%s] for commitPw [%s] fail' %(confirmPwd, self.commitPwd))
raise
else:
log.logger.info('inputing Pw [%s] for commitPw [%s] ' %(confirmPwd, self.commitPwd))
# preservation
def saveButton(self):
try:
self.driver.implicitly_wait(5)
clickbutton = self.findElement(*self.saveBtn)
time.sleep(1)
clickbutton.click()
except Exception:
log.logger.exception('click save button fail')
raise
else:
log.logger.info('clciking the button')
# Change password function menu
def modifyPwMenu(self):
try:
self.findElement(*self.menuList[0]).click()
self.findElement(*self.menuPersonal).click()
self.findElement(*self.menuModifyPwd).click()
except Exception:
log.logger.exception('not found menu [%s]-[%s]-[%s]' %(self.menuList[0], self.menuPersonal, self.menuModifyPwd))
raise
else:
log.logger.info('finding menu [%s]-[%s]-[%s]' %(self.menuList[0], self.menuPersonal, self.menuModifyPwd))
self.driver.implicitly_wait(2)
# Change Password
def modifyPw(self, list):
try:
self.inputOldPw(list[0])
self.inputNewPw(list[1])
self.inputConfirmPw(list[2])
self.saveButton()
except Exception:
log.logger.exception('input oldpw/newpw/commitpw [%s]/[%s]/[%s] fail' %(list[0], list[1], list[2]))
raise
else:
log.logger.info('modifing pw [%s]/[%s]/[%s]' %(list[0], list[1], list[2]))
# Error box
def errorDialog(self, commit_btn = (By.ID,'unieap_form_Button_1_unieap_input')):
""" :type commit_btn: Yuan Zu """
try:
messages_frame = self.findElement(*self.errMessage)
text = messages_frame.text
element = self.findElement(*commit_btn)
time.sleep(2)
action = ActionChains(self.driver)
action.move_to_element(element).perform()
time.sleep(2)
element.click()
# Release the mouse
action.reset_actions()
except Exception:
log.logger.exception('close errMsgFram [%s] or get text [%s]fail' %(self.errMessage))
raise
else:
log.logger.info('close errMsgFram [%s] and get text [%s] success' %(self.errMessage, text))
return text
# Close the prompt box
def closeErrMsg(self, element):
try:
ele = self.findElement(*element)
action = ActionChains(self.driver)
action.move_to_element(ele).perform()
time.sleep(2)
ele.click()
action.reset_actions()
except Exception:
log.logger.exception('close the err msg ifram fail', exc_info=True)
raise
else:
log.logger.info('closing the err msg ifram success!')
if __name__ == '__main__':
pass
4. Modify password test case
ModifyPw.py
import time
from retail.test_case.models.myunittest import MyunitTest
from retail.test_case.page_obj.modifypw_page import PrimaryMenu
from retail.test_case.models.strhandle import strhandle
class ModifyPw_TC(MyunitTest):
""" Rights management / Personal settings / Password modification module test case """
def test_menu_is_display(self):
""" Main menu check """
self.login.loginFunc()
menu = PrimaryMenu(self.driver)
time.sleep(4)
num = 0
# Loop through and assert that the menu is correct
for menu_item in menu.menuList:
self.assertEqual(menu.menuList[num][1],(menu.findMenu(*menu_item).text),u' The menu doesn't exist ')
num=num+1
def test_modify_password_len(self):
""" The old password is not empty , The new password is less than 4 position , Confirm that the password is not empty , Failed to change password , Pop up tips """
self.login.loginFunc()
menu = PrimaryMenu(self.driver)
# Find the change password page
menu.modifyPwMenu()
# Change Password
menu.modifyPw(menu.pwdList[0])
text = menu.errorDialog(menu.closeBtn)
# If the length of the password is not satisfied, the message will be asserted
self.assertIn(u' The password length is at least 4 position !', text, u' The prompt message is wrong ')
def test_modify_password_strebgth(self):
""" The old password is not empty , The new password is longer than 4 And it's not strong enough , Confirm that the password is not empty , Failed to change password , Pop up tips """
self.login.loginFunc()
menu = PrimaryMenu(self.driver)
menu.modifyPwMenu() # Find the change password page
menu.modifyPw(menu.pwdList[1]) # Change Password
text = menu.errorDialog(menu.closeBtn)
# When the password strength is not satisfied, the assertion prompt message
self.assertIn(u' The password is not strong enough , Please re-enter the password !', text, u' The password is not strong enough , Please re-enter the password !')
def test_modify_password_incorrect(self):
""" The old password is incorrect. It is not empty , The new password is equal to the confirmation password and meets the conditions , Failed to change password , Pop up tips """
self.login.loginFunc()
menu = PrimaryMenu(self.driver)
menu.modifyPwMenu() # Find the change password page
menu.modifyPw(menu.pwdList[2]) # Change Password
text = menu.errorDialog(menu.closeBtn)
# The new password and the confirmation code do not assert the prompt message at the same time
self.assertIn(u' Old password input error !', text, u' Old password input error !')
def test_modify_password_difference(self):
""" The old password is not empty , The new password is not the same as the confirmation password and the new password meets the conditions , Failed to change password , Pop up tips """
self.login.loginFunc()
menu = PrimaryMenu(self.driver)
# Find the change password page
menu.modifyPwMenu()
# Change Password
menu.modifyPw(menu.pwdList[3])
text = menu.errorDialog(menu.closeBtn)
# The new password and the confirmation code do not assert the prompt message at the same time
self.assertIn(u' The new password entered twice is different !', text, u' The new password entered twice is different !')
def test_modify_password_all_blank(self):
""" Old password , New password , Confirm that the password is empty , Failed to change password , Pop up tips """
self.login.loginFunc()
menu = PrimaryMenu(self.driver)
menu.modifyPwMenu() # Find the change password page
menu.modifyPw(menu.pwdList[4]) # Change Password
text = menu.errorDialog(menu.closeBtn)
# Assertion prompt when all passwords are empty
self.assertIn(u' The value of this entry cannot be empty !', text, u' The value of this entry cannot be empty !')
def test_modify_password(self):
""" Loop check prompt message """
self.login.loginFunc()
menu = PrimaryMenu(self.driver)
# Find the change password page
menu.modifyPwMenu()
error_list = []
for list in range(len(menu.pwdList)):
menu.modifyPw(menu.pwdList[list])
if menu.isElementExist(menu.errMessage):
# Here only judge whether there is a prompt box pop-up , If so, the modification failed , No or other prompt box is modified successfully by default
text = menu.errorDialog(menu.closeBtn)
error_list.append(text)
else:
self.assertTrue(menu.isElementExist(*menu.errMessage), 'error fram not exist, please open bug')
self.assertEqual(u' The password length is at least 4 position !',error_list[0],'log infomation error!')
self.assertEqual(u' The password is not strong enough , Please re-enter the password !', error_list[1], 'log infomation error!')
self.assertEqual(u' Old password input error !', error_list[2], 'log infomation error!')
self.assertEqual(u' The new password entered twice is different !', error_list[3], 'log infomation error!')
self.assertEqual(u' The value of this entry cannot be empty !', error_list[4], 'log infomation error!')
def test_modifypw(self):
""" Loop test password modification function """
# Sign in
self.login.loginFunc()
menu = PrimaryMenu(self.driver)
# Find the change password page
menu.modifyPwMenu()
for item in menu.pwdList:
menu.modifyPw(item)
# If there is a prompt box Then assert whether the prompt information is correct
if menu.isElementExist(menu.errMessage):
# New password length check
if item[0] != '' and len(item[1]) < 4 and item[2] !='':
text = menu.errorDialog(menu.closeBtn)
try:
self.assertEqual(u' The password length is at least 4 position !',text,'the message incorrect!')
except Exception:
menu.saveScreenShot(u'fail_ Password length .png')
raise
# New password strength check ['a', 'qwert', 'qwert']
elif item[0] != '' and len(item[1]) >= 4 and item[2] !='':
lowercase, uppercase, number, other=strhandle(item[1])
# A lowercase letter Capitalization
if lowercase > 0 and uppercase > 0 and number == 0 and other == 0:
text = menu.errorDialog(menu.closeBtn)
self.assertIn(u' The password is not strong enough , Please re-enter the password !', text, u' The password is not strong enough , Please re-enter the password !')
# Capitalization Special characters
elif uppercase > 0 and other > 0 and number == 0 and lowercase == 0:
text = menu.errorDialog(menu.closeBtn)
self.assertIn(u' The password is not strong enough , Please re-enter the password !', text, u' The password is not strong enough , Please re-enter the password !')
# A lowercase letter Special characters
elif lowercase >0 and other > 0 and number == 0 and uppercase == 0:
text = menu.errorDialog(menu.closeBtn)
self.assertIn(u' The password is not strong enough , Please re-enter the password !', text, u' The password is not strong enough , Please re-enter the password !')
# Capitalization Numbers
elif lowercase == 0 and other == 0 and number > 0 and uppercase > 0:
text = menu.errorDialog(menu.closeBtn)
self.assertIn(u' The password is not strong enough , Please re-enter the password !', text, u' The password is not strong enough , Please re-enter the password !')
# A lowercase letter Numbers
elif lowercase > 0 and other == 0 and number > 0 and uppercase == 0:
text = menu.errorDialog(menu.closeBtn)
self.assertIn(u' The password is not strong enough , Please re-enter the password !', text, u' The password is not strong enough , Please re-enter the password !')
elif lowercase > 0 and other == 0 and number == 0 and uppercase == 0:
text = menu.errorDialog(menu.closeBtn)
self.assertIn(u' The password is not strong enough , Please re-enter the password !', text, u' The password is not strong enough , Please re-enter the password !')
elif lowercase == 0 and other > 0 and number == 0 and uppercase == 0:
text = menu.errorDialog(menu.closeBtn)
self.assertIn(u' The password is not strong enough , Please re-enter the password !', text, u' The password is not strong enough , Please re-enter the password !')
elif lowercase == 0 and other == 0 and number > 0 and uppercase == 0:
text = menu.errorDialog(menu.closeBtn)
self.assertIn(u' The password is not strong enough , Please re-enter the password !', text, u' The password is not strong enough , Please re-enter the password !')
elif lowercase == 0 and other == 0 and number == 0 and uppercase > 0:
text = menu.errorDialog(menu.closeBtn)
self.assertIn(u' The password is not strong enough , Please re-enter the password !', text, u' The password is not strong enough , Please re-enter the password !')
# >= 4
elif item[0] != '[email protected]#' and item[1] == item[2]:
lowercase, uppercase, number, other = strhandle(item[1])
if (lowercase > 0 and uppercase > 0 and number > 0) or (
lowercase > 0 and uppercase > 0 and other > 0) or (
number > 0 and other > 0 and lowercase > 0) or (
number > 0 and other > 0 and uppercase > 0):
text = menu.errorDialog(menu.closeBtn)
# The new password and the confirmation code do not assert the prompt message at the same time
self.assertIn(u' Old password input error !', text, u' Old password input error !')
# and item[1] >= 4
elif item[0] == '[email protected]#$' and item[1] != item[2]:
lowercase, uppercase, number, other = strhandle(item[1])
if (lowercase > 0 and uppercase > 0 and number > 0) or (
lowercase > 0 and uppercase > 0 and other > 0) or (
number > 0 and other > 0 and lowercase > 0) or (
number > 0 and other > 0 and uppercase > 0):
text = menu.errorDialog(menu.closeBtn)
self.assertIn(u' The new password entered twice is different !', text, u' The new password entered twice is different !')
else:
print('test value incorrect! please check it')
# The input item is null
elif item[0] == '' or item[1] =='' or item[2] =='':
text = menu.errorDialog(menu.closeBtn)
# Assertion prompt when all passwords are empty
self.assertIn(u' The value of this entry cannot be empty !', text, u' The value of this entry cannot be empty !')
else:
self.assertTrue(menu.isElementExist(menu.errMessage), 'error fram not exist, please check the test value or file bug')
if __name__=='__main__':
pass
5. Member profile query page
memberquery_page.py
from retail.test_case.page_obj.base_page import queryData
import time
from selenium.webdriver.common.by import By
import logging
import sys
from retail.test_case.page_obj.modifypw_page import PrimaryMenu, eleData
from retail.test_case.models.log import Logger
log = Logger(__name__, CmdLevel=logging.INFO, FileLevel=logging.INFO)
class MemberQuery(PrimaryMenu):
# Test data : Member code , Membership name , Phone number
valuesList = [queryData.readExcel(1, 1), int(queryData.readExcel(2, 1)), queryData.readExcel(3, 1)]
# Member profile drop down menu
memberMenu = (By.LINK_TEXT, eleData.readExcel(24, 3))
# Member query page 3 A list ( Query criteria , Member information details , Points change details )
uiElements = (By.XPATH, eleData.readExcel(25, 3))
# Member type
memberTypeBtn = (By.ID, eleData.readExcel(26, 3))
# Member type drop-down options
memberTypeNum = [(By.XPATH, eleData.readExcel(27, 3)),
(By.XPATH, eleData.readExcel(28, 3)),
(By.XPATH, eleData.readExcel(29, 3))]
# Membership level
memberLevelBtn = (By.ID, eleData.readExcel(30, 3))
# Member level drop-down options
memberLevelNum = [(By.XPATH, eleData.readExcel(31, 3)),
(By.XPATH, eleData.readExcel(32, 3)),
(By.XPATH, eleData.readExcel(33, 3)),
(By.XPATH, eleData.readExcel(34, 3))]
# Membership number , Membership name , Phone number
memberNumNamePhone = [(By.ID, eleData.readExcel(35, 3)),
(By.ID, eleData.readExcel(36, 3)),
(By.ID, eleData.readExcel(37, 3))]
# Query exception prompt box
# If the query fails, the error prompt box will pop up
qFailerr = (By.XPATH, eleData.readExcel(38, 3))
confirmBtn = (By.XPATH, eleData.readExcel(39, 3))
# Query and reset
queryResetBtn = [(By.ID, eleData.readExcel(40, 3)),
(By.ID, eleData.readExcel(41, 3))]
# Click on member type
def selectMemberType(self):
try:
self.findElement(*self.memberTypeBtn).click()
self.driver.implicitly_wait(2)
except Exception:
log.logger.exception('selecting member type fail ')
raise
else:
log.logger.info('---selecting member type ')
# Click member level
def selectMemberLevel(self):
try:
self.findElement(*self.memberLevelBtn).click()
self.driver.implicitly_wait(2)
except Exception:
log.logger.exception('selecting member level fail ')
raise
else:
log.logger.info('---selecting member level ')
# Search member profile query menu
def memberQueryMenu(self):
self.findElement(*self.menuList[1]).click()
self.findElement(*self.memberMenu).click()
time.sleep(4)
log.logger.info('page [%s] :found the menu [%s] and [%s]' % (
sys._getframe().f_code.co_name, self.menuList[1], self.memberMenu))
# Member type / Member level drop-down options
def memberTypeLevelOption(self, *xpathList):
try:
member_type_level = self.findElement(*xpathList)
text = member_type_level.text
except Exception:
log.logger.exception('get element member type/level item text fail', exc_info=True)
raise
else:
log.logger.info('get element [%s] member type/level item text [%s] fail' % (xpathList, text))
return text, member_type_level
# Click the query and reset button
def cQueryResetBtn(self, *queryResetBtn):
try:
self.findElement(*queryResetBtn).click()
except Exception:
log.logger.exception('query/reset button not click', exc_info=True)
raise
else:
log.logger.info('clicking query/reset button ')
# Enter query criteria
def iQueryCondition(self, numNamePhone, value):
number_name_phone = self.findElement(*numNamePhone)
try:
number_name_phone.clear()
number_name_phone.send_keys(value)
except Exception:
log.logger.exception('input value error', exc_info=True)
raise
else:
log.logger.info('[%s] is typing value [%s] ' % (numNamePhone, value))
# Get the content of the condition input box
def getInputboxValue(self, *memberNumNamePhone):
try:
get_member_number_name_phone_text = self.findElement(*memberNumNamePhone)
text = get_member_number_name_phone_text.get_attribute('value')
except Exception:
log.logger.exception('get value of element fail', exc_info=True)
raise
else:
log.logger.info('get value [%s] of element [%s] success' % (memberNumNamePhone, text))
return text
# Rewriting of reset function
def reset(self):
try:
self.findElement(*self.memberNumNamePhone[0]).clear()
self.findElement(*self.memberNumNamePhone[1]).clear()
self.findElement(*self.memberNumNamePhone[2]).clear()
except Exception:
log.logger.exception('reset fail', exc_info=True)
raise
else:
log.logger.info('reset [%s]-[%s]-[%s] success' % (
self.memberNumNamePhone[0], self.memberNumNamePhone[1], self.memberNumNamePhone[2]))
if __name__ == '__main__':
pass
6. Member file query case
MemberQueryTc.py
import random
import time
from selenium.webdriver.common.action_chains import ActionChains
from retail.test_case.models.myunittest import MyunitTest
from retail.test_case.page_obj.memberquery_page import MemberQuery
class MemberQuery_TC(MyunitTest):
""" Member file query module test case """
#@unittest.skip('dont run the test case')
def test_member_check_ui(self):
""" The member file query page is displayed correctly """
# Instantiate member query page
menu = MemberQuery(self.driver)
self.login.loginFunc()
# Search member profile query menu
menu.memberQueryMenu()
elements = menu.findElements(*menu.uiElements)
ele_list = []
for eles in elements:
if eles.text !='':
ele_list.append(eles.text)
self.assertEqual(u' Query criteria ', ele_list[0])
self.assertEqual(u' Member information details ', ele_list[1])
self.assertEqual(u' Points change details ', ele_list[2])
def test_member_type(self):
""" The member type drop-down list item is correct """
# Instantiate member query page
menu = MemberQuery(self.driver)
# Sign in
self.login.loginFunc()
# Search member profile query menu
menu.memberQueryMenu()
menu.selectMemberType()
list_type = []
# Loop through the member type drop-down list
for member_type in menu.memberTypeNum:
text, memeber_type_level = menu.memberTypeLevelOption(*member_type)
list_type.append(text)
self.assertEqual(u' Individual members ', list_type[0])
self.assertEqual(u' Corporate members ', list_type[1])
self.assertEqual(u' Other ', list_type[2])
def test_member_level(self):
""" The member level drop-down list item is correct """
# Instantiate member query page
menu = MemberQuery(self.driver)
# Sign in
self.login.loginFunc()
# Search member profile query menu
menu.memberQueryMenu()
menu.selectMemberLevel()
list_level = []
# Loop through the member level drop-down list
for member_level in menu.memberLevelNum:
text, memeber_type_level = menu.memberTypeLevelOption(*member_level)
list_level.append(text)
self.assertEqual(u' Standard members ', list_level[0])
self.assertEqual(u' Gold members ', list_level[1])
self.assertEqual(u' Platinum members ', list_level[2])
self.assertEqual(u' Diamond member ', list_level[3])
# ............................................................................................#
# After combining the conditions of the page, click the query button . It's a massive operation , Therefore, the returned data is not checked , Only see if the conditions of this combination can be used normally on the page .
# If the query fails , The system will have a pop-up box to prompt the failure reason , This should be well understood .
# We grab whether this box appears in a certain period of time , If it appears, the query fails , Record the use case results .
# ............................................................................................#
def test_member_query_failed(self):
""" The default condition query is successful """
# Instantiate the member profile query page
menu = MemberQuery(self.driver)
# Sign in
self.login.loginFunc()
# Find the member query page
menu.memberQueryMenu()
# Click on [ Inquire about ]
menu.cQueryResetBtn(*menu.queryResetBtn[0])
# Assertion error box
flag = menu.isElementExist(menu.qFailerr)
# flag by false when , Assert success , No prompt box , Indicates that the default query is successful
self.assertFalse(flag, msg=u' The query fails ')
def test_alone_query_1(self):
""" By member number , Membership name , Mobile phone number single condition query """
# Instantiate the member profile query page
menu = MemberQuery(self.driver)
# Sign in
self.login.loginFunc()
# Find the member profile query page
menu.memberQueryMenu()
for num_name_phone in menu.memberNumNamePhone:
# Reset
menu.reset()
for value in menu.valuesList:
menu.iQueryCondition(num_name_phone,value)
# Click on [ Inquire about ]
menu.cQueryResetBtn(*menu.queryResetBtn[0])
time.sleep(3)
flag = menu.isElementExist(menu.qFailerr)
if flag:
self.assertTrue(flag, u' The prompt box does not exist , The query is successful ')
menu.accept(*menu.confirmBtn)
else:
self.assertFalse(flag, u' The prompt box exists , The query fails ')
def test_alone_query_2(self):
""" Single query by member type """
# Instantiate the member profile query page
menu = MemberQuery(self.driver)
# Sign in
self.login.loginFunc()
# Find the member profile query page
menu.memberQueryMenu()
for me_type in menu.memberTypeNum:
# Click on [ Member type ]
menu.selectMemberType()
# Traverse each drop-down option
text, member_type_level = menu.memberTypeLevelOption(*me_type)
# Move the mouse over the drop-down options
ActionChains(self.driver).move_to_element(member_type_level).perform()
# Select the drop-down option
member_type_level.click()
# Click on [ Inquire about ]
menu.cQueryResetBtn(*menu.queryResetBtn[0])
time.sleep(3)
# Judge whether the query is successful
flag = menu.isElementExist(menu.qFailerr)
self.assertFalse(flag, u' The prompt box exists , The query fails ')
def test_alone_query_3(self):
""" Single query by member level """
# Instantiate the member profile query page
menu = MemberQuery(self.driver)
# Sign in
self.login.loginFunc()
# Find the member profile query page
menu.memberQueryMenu()
for me_level in menu.memberLevelNum:
# Click on [ Membership level ]
menu.selectMemberLevel()
# Traverse each drop-down option
text, member_level = menu.memberTypeLevelOption(*me_level)
# Move the mouse over the drop-down options
ActionChains(self.driver).move_to_element(member_level).perform()
# Select the drop-down option
member_level.click()
# Click on [ Inquire about ]
menu.cQueryResetBtn(*menu.queryResetBtn[0])
time.sleep(3)
# Judge whether the query is successful
flag = menu.isElementExist(menu.qFailerr)
self.assertFalse(flag, u' The prompt box exists , The query is successful ')
def test_reset(self):
""" Reset function verification """
# Instantiate the member profile query page
menu = MemberQuery(self.driver)
# Sign in
self.login.loginFunc()
# Find the member profile query page
menu.memberQueryMenu()
# 3 A condition input box is used to input data randomly
for inputBox in menu.memberNumNamePhone:
menu.iQueryCondition(inputBox,random.choice(menu.valuesList))
# Randomly select one item from the member type drop-down list
menu.selectMemberType()
text_type, member_type = menu.memberTypeLevelOption(*(random.choice(menu.memberTypeNum)))
# Move the mouse over the drop-down options
ActionChains(self.driver).move_to_element(member_type).perform()
member_type.click()
#menu.selectMemberLevel()
#text_level, member_level = menu.memberTypeLevelOption(*(random.choice(menu.member_level_num)))
#ActionChains(self.driver).move_to_element(member_level).perform()
#member_level.click()
# Click on 【 Reset 】
menu.cQueryResetBtn(*menu.queryResetBtn[1])
# Before acquisition 3 The contents of an input box
text_list = []
for input_box in menu.memberNumNamePhone:
text = menu.getInputboxValue(*input_box)
text_list.append(text)
# Get membership type
type_type_text = menu.getInputboxValue(*menu.memberTypeBtn)
text_list.append(type_type_text)
#type_level_text = menu.getInputboxValue(*menu.member_level_btn)
#text_list.append(type_level_text)
# Asserts whether each condition box is empty If it's empty, go through
for get_attr in text_list:
self.assertEqual('',get_attr)
if __name__ == '__main__':
pass
7. Execute test case
7.1.from BeautifulReport import BeautifulReport This report needs to be found online ( A lot of similar test report source code , It is not necessary to use the report template in this case ).
RunTc.py
import unittest
import time
from BeautifulReport import BeautifulReport
from retail.config.conf import *
from retail.test_case.models.testreport import testreport
if __name__ == '__main__':
#currTime = time.strftime('%Y-%m-%d %H_%M_%S')
#filename = currTime + '.html'
# The first test report
#test_suite = unittest.defaultTestLoader.discover(tcPath, pattern='*Tc.py')
#result = BeautifulReport(test_suite)
#result.report(filename= filename, description='test report', log_path=reportPath)
# The second test report
runner, fp, fileName = testreport()
test_suite = unittest.defaultTestLoader.discover(tcPath, pattern='LoginTc.py')
runner.run(test_suite)
fp.close()
Ten . Report display
1. Screenshot : Screenshot of rule creation failure .
2. Screenshot : Screenshot of login success .
3. Use case execution log : Part of the log record .
4. Test report
11、 ... and . summary
1. It's quite a sense of accomplishment to see the results , I didn't send a screenshot of the email , Because I'm an intranet, I don't know why the mail server can't connect , But there's no problem using the Internet to test email sending alone !
2. Just write so much , The use case design ideas of other pages are the same , Because all use cases are independent of each other , So more or less doesn't affect ! To source students can visit my github Download it yourself !