Automated test framework

Building of automated testing framework
1. Automated testing framework
(1) Overview:
Automated testing framework is a program framework applied to automated testing. It provides a reusable automated test module, provides the most basic automated test functions (such as opening a browser, clicking links, etc.), or provides an architecture module (such as TestNG) that provides automated test execution and management functions. It is a tool set consisting of one or more automated test basic modules, automated test management modules, automated test statistics modules, etc.
(2) Common patterns
>Data-driven testing framework: an automated testing framework that uses data arrays, test data files, or databases as input to the testing process.
>Keyword-driven testing frameworks: use the manipulated Element objects, operation methods, and operation data values ​​are used as an automated testing framework for testing process input.
>Hybrid testing framework: Data-driven testing framework is added to keyword-driven testing framework
>Behavior-driven testing framework: Support nature Language as an automated testing framework for the description of test cases
(3) Role:
>Can effectively organize and manage test scripts
>Perform data-driven or keyword-driven testing
>The basic test code Encapsulate to reduce the complexity and repeatability of test script writing
>Improve the efficiency of test script maintenance and modification
>Automatically execute test scripts, and automatically publish test reports, providing script support for continuous integration development methods
> br>>Let test engineers who do not have programming ability carry out automated testing work
(4) The design core idea of ​​automated testing framework
Abstract and summarize commonly used script codes or test logic, and then oriented these codes Object design, encapsulate the code that needs to be repeated into public class methods. By calling common class legislation, the complexity of scripts in the test class will be greatly reduced, allowing more testers with weak scripting capabilities to implement automated tests.
The steps to create and implement a Web automation test framework are as follows: 1) According to the manual test cases of the test business, select the test cases that need to be automatically executed
2) According to the test cases that can be automatically executed, analyze The test framework needs to simulate manual operations and high repetitive test procedures or logic
3) The manual operations and high repetitive test logic are implemented in the code, and the encapsulation method is written in the class
4) According to Test the type of business and its own technical capabilities, choose a data-driven framework, a keyword-driven framework, a hybrid framework or a behavior-driven framework
5) After determining the framework model, select the browsers commonly used in the framework, test data processing, and file Operation, database operation, original operation of page elements, log and report and other functions to implement class method encapsulation
6) Perform integration test and system test on framework code, use PageObject mode and TestNG framework (or JUnit) to write test scripts , Use the framework for automated testing, verify that the functions of the framework can meet the needs of automated testing
7) Write commonly used Api documents of automated testing frameworks for others to refer to
8) Train and promote within the test group
> 9) Continuously collect framework usage questions and feedback during the testing process, continuously increase and optimize the functions of the automation framework, continuously enhance the encapsulation effect of complex operations in the framework, and minimize the complexity of writing test scripts.
10) Regularly evaluate the use effect of the testing framework, evaluate the input-output ratio of automated testing, and then promote the scope of application of the automated framework gradually

2. Data-driven framework and practice
(1) The framework generally contains the directory:
Create a new project, the following parts are included
1) Util package: encapsulate commonly used functions and functions (reusable)
Excel, time, fetch elements, write log, mapobject program , Analyze ini files, optional (screenshots, directory creation, file operations, database operations, etc.)
2) Project variable package
Store all common variables or configuration-related variables
3) PageObject package: one There are many methods in a class of a page. The method is used to obtain an element in the page.
Such as: login class get_frame get_username get_password, etc. Return page element objects
4) conf configuration directory: store all configuration files (log Configuration file, positioning element configuration file)
5) Action package:
login function: script logic for all logins
addContact: add contact as script logic
6) Optional (screenshot directory )
Screenshots of errors

(2) Frame building steps:
1) Create a new project in PyCharm: my_datadriven_frame
2) Create a new package under the project my_datadriven_frame: Util
a. Add a new module under Util, namely the python module: Excel.py The content is as follows:

#< /span>encoding=utf-8

from openpyxl import *
from openpyxl.styles import Font
from FormatTime import data_time_chinese

class ParseExcel(object):
def __init__(self,excel_file_path):
self.excel_file_path
=excel_file_path
self.workbook
=load_workbook(excel_file_path)
self.font
=Font(color=None)
self.colorDict
={"red":'FFFF3030< span style="color: #800000;">'
,"green":'FF008B00< /span>'}
self.sheet
=self.get_sheet_by_index(0)

# Set the current sheet to be operated by the serial number, and use index to get Corresponding sheet
def set_sheet_by_index(self,sheet_index):
self.sheet
= self.get_sheet_by_index(sheet_index)

# Set the operation sheet by name
def set_sheet_by_name(self,sheet_name):
self.sheet
= self.workbook.get_sheet_by_name(sheet_name)

# Get the name of the sheet and title of the current operation
def get_default_name(self):
return self.sheet.title

# Get the sheet to be operated by name
def get_sheet_by_name(self,sheet_name):
self.sheet
= self.workbook.get_sheet_by_name(sheet_name)
return self.sheet

# Get the sheet to be operated by serial number
def get_sheet_by_index(self, sheet_index):
sheet_name
= self.workbook.get_sheet_names()[sheet_index]
self.sheet
= self.get_sheet_by_name(sheet_name)
return self.sheet

#Get the maximum line number in the sheet, starting from 0 span>
def get_max_row_no(self):
return self.sheet.max_row

# Get the largest column number in the sheet, starting from 0 span>
def get_max_col_no(self):
return self.sheet.max_column

#Get the smallest line number in the default sheet
def get_min_row_no(self):
return self.sheet.min_row

# Get the smallest column number in the default sheet
def get_min_col_no(self):
return self.sheet.min_column

#Get all row objects in the sheet being operated
def get_all_rows(self):
# rows = []
# for row in self.sheet.iter_rows():
# rows.append(row)
# return rows
#The above methods can also be used
return list(self.sheet.iter_rows())

#Get all column objects in the sheet being operated
def get_all_cols(self):
# cols = []
# for col in self.sheet.iter_cols():
# cols.append(col)
# return cols
#The above methods can also be used
return list(self.sheet.iter_cols())

#Get a row object, the first row starts from 0< /span>
def get_single_row(self,row_no):
return self.get_all_rows()[row_no]

# Get a certain column object, the first column starts from 0< /span>
def get_single_col(self, col_no):
return self.get_all_cols()[col_no]

#Get a cell object, row number and column number from 1 start
def get_cell(self,row_no,col_no):
return self.sheet.cell(row = row_no,column = col_no )

# Get the content of a cell
def get_cell_content(self, row_no, col_no):
return self.sheet.cell(row = row_no,column = col_no ).value

# write specified content to a cell, line number and Column number starts from 1
#do not open excel when calling this method
def write_cell_content(self, row_no, col_no,content,font=None):
self.sheet.cell(row
=row_no,column=col_no).value = content
self.workbook.save(self.excel_file_path)

# write the current time, row number and Column number starts from 1
#do not open excel when calling this method
def write_cell_current_time(self,row_no,col_no):
self.sheet.cell(row
=row_no,column=col_no).value = data_time_chinese()
self.workbook.save(self.excel_file_path)

def save_excel_file(self):
self.workbook.save(self.excel_file_path)
#Save all cell changes

if __name__ == "__main__":
#Test all methods
pe = ParseExcel("D:\test\test.xlsx")
pe.set_sheet_by_index(0)
print pe.get_default_name()
pe.set_sheet_by_name(
"2")
print pe.get_default_name()
print pe.get_sheet_by_name("2")
print pe.get_sheet_by_index(0)

print "max rows:",pe.get_max_row_no()
print "min row",pe.get_min_row_no()
print pe.get_all_rows() #Get all row objects
print pe.get_all_rows()[2] #Get a row
print pe.get_all_rows()[0][2] #< span style="color: #008000;">Get a cell

print pe.get_all_rows()[2][1].value #Get the value of a cell

print " max cols:",pe.get_max_col_no()
print "min col",pe.get_min_col_no()
print pe.get_all_cols() #Get all row objects
print pe.get_all_cols()[2] #Get a row
print pe.get_all_cols()[0][2] #< span style="color: #008000;">Get a cell

print pe.get_all_cols()[2][1].value #Get the value of a cell

print len(pe.get_all_rows())
for cell in pe.get_all_rows()[1 ]:
print cell.value

print len(pe.get_all_cols())
for cell in pe.get_all_cols()[2 ]:
print cell.value

print "==============================="

for cell in pe.get_single_col(0):
print cell.value

for cell in pe.get_single_row(0):
print cell.value

print "--------------------"
print pe.get_cell(1,2)
print pe.get_cell_content(1,1)

pe.write_cell_content(
5,6,"hello ")
print pe.get_cell_content(5,6)
pe.write_cell_current_time(
7,7)
print pe.get_cell_content(7,7)

b. Package time module, FormatTime.py, the content is as follows:

#encoding=utf-8

import time

#returns the year, month, day, hour, minute and second in Chinese
def data_time_chinese():
return time.strftime("%Y year%m month%d day%H hour%M minute%S second",time.localtime())

#Returns hours, minutes and seconds in Chinese
def time_chinese():
return time.strftime("%H hour%M minute%S second" , time.localtime())

# Returns the year, month, day, hour, minute and second in English
def data_time_english():
return time.strftime("%Y-%m-%d %H:%M:%S seconds", time.localtime())

# Back to English hours, minutes and seconds
def time_english():
return time.strftime("%H:%M:%S seconds" , time.localtime())

if __name__ == "__main__":
print data_time_chinese()
print time_chinese()
print data_time_english()
print time_english()

c, package log module, Log.py, content As follows:

#encoding=utf- 8

import logging
import logging.config
from ProjectVar.var import *

#Read the configuration file of the log
logging.config.fileConfig(log_config_file_path)
#Choose a log format
logger = logging.getLogger("example02")


def info(message):
#Print info level information
logging.info(message)

def error(message):
#Print error level information
logging.error(message)

def warning(message):
#Print warning level information
logging.warning(message)

if __name__ == "__main__":
error(
"---ERROR--- ")
info(
"===Test=== ")
warning(
"````Wang`````< /span>")

d. Encapsulate the page element module, ObjectMap.py, the content is as follows:

#encoding=utf-8

from selenium.webdriver.support.ui import WebDriverWait
import time

#Get a single page element object
def getElement(driver,locateType,locateExpression):
try:
element
= WebDriverWait(driver,5).until(lambda x: x.find_element(by = locateType,value = locateExpression))
return element
except Exception,e:
raise e

#Get multiple objects of the same page element and return them as a list span>
def getElements(driver,locateType,locateExpression):
try:
element
= WebDriverWait(driver,5).until(lambda x: x.find_elements(by = locateType,value = locateExpression))
return element
except Exception,e:
raise e

if __name__ == "__main__":
from selenium import webdriver
#Perform unit testing
driver = webdriver.Firefox(executable_path = "D:\geckodriver ")
driver.maximize_window()
driver.get(
"https://mail.126.com /")
time.sleep(
2)
lb
= getElement(driver,"id","lbNormal ")
print lb
driver.quit()

e. The module that encapsulates the parsing configuration file, ParsePageObjectRepository.py, whose content is as follows:

 #encoding=utf-8

from ConfigParser import ConfigParser
from ProjectVar.var import page_object_repository_path

class ParsePageObjectRepositoryConfig(object):
def __init__(self):
self.cf
= ConfigParser()
self.cf.read(page_object_repository_path)

#To get a section, all keys and values, use a dictionary Way back
def getItemsFromSection(self,sectionName):
print self.cf.items(sectionName)
return dict(self.cf.items(sectionName))

#获取某一个具体的选项对应的value
def getOptionValue(self,sectionName,optionName):
return self.cf.get(sectionName,optionName)

3)新建一个包,ProjectVar
在ProjectVar下新增一个模块,var.py,内容如下:

#encoding=utf-8

import os

#获取工程所在目录的绝对路径
project_path = os.path.dirname(os.path.dirname(__file__))
#日志配置文件的绝对路径
log_config_file_path = project_path + "/Conf/logger.conf"
#测试数据excel文件的绝对路径
test_data_excel_path = project_path.decode("utf-8") + u"/TestData/126邮箱联系人.xlsx"
#
page_object_repository_path = project_path.decode("utf-8") + "/Conf/PageProjectRepository.ini"

username_col_no
=1
password_col_no
=2
is_executed_col_no
=4
test_result_col_no
=6
exception_info_col_no
=7
assert_keyword_col_no
= 6
firefox_driver_path
= D:\geckodriver

if __name__ == "__main__":
print os.path.dirname(__file__)
print os.path.dirname(os.path.dirname(__file__))
print os.path.dirname(project_path+"/Conf/logger.conf") #路径斜杠向左向右都可以
print log_config_file_path
print test_data_excel_path

4)新建一个目录 Conf
在Conf下新建一个log配置文件, logger.conf内容如下:

#logger.conf

#
##############################################
[loggers]
keys
=root,example01,example02
[logger_root]
level
=DEBUG
handlers
=hand01,hand02

[logger_example01]
handlers
=hand01,hand02
qualname
=example01
propagate
=0

[logger_example02]
handlers
=hand01,hand03
qualname
=example02
propagate
=0

###############################################
[handlers]
keys
=hand01,hand02,hand03

[handler_hand01]
class=StreamHandler
level
=INFO
formatter
=form01
args
=(sys.stderr,)

[handler_hand02]
class=FileHandler
level
=DEBUG
formatter
=form01
args
=(DataDrivenFrameWork.log, a)

[handler_hand03]
class=handlers.RotatingFileHandler
level
=INFO
formatter
=form01
args
=(DataDrivenFrameWork.log, a, 10*1024*1024, 5)

###############################################
[formatters]
keys
=form01,form02

[formatter_form01]
format
=%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s
datefmt
=%Y-%m-%d %H:%M:%S

[formatter_form02]
format
=%(name)-12s: %(levelname)-8s %(message)s
datefmt
=%Y-%m-%d %H:%M:%S

在Conf目录下新建一个PageProjectRepository配置文件,PageProjectRepository.ini内容如下:

[126mail_login]

login_page.lbnormalbutton
=id>lbNormal
login_page.frame
=xpath>//iframe[contains(@id,"x-URS-iframe")]
login_page.username
=xpath>//input[@name=email]
login_page.password
=xpath>//input[@name=password]
login_page.loginbutton
=id>dologin

[126mail_homepage]
home_page.addressbook
=xpath>//div[text()=通讯录]

[126mail_addcontactspage]
addcontacts_page.createcontactsbtn
=xpath>//span[text()=新建联系人]
addcontacts_page.contactpersonname
=xpath>//a[@title=编辑详细姓名]/preceding-sibling::div/input
addcontacts_page.contactpersonemail
=xpath>//*[@id=iaddress_MAIL_wrap]//input
addcontacts_page.starcontacts
=xpath>//span[text()=设为星标联系人]/preceding-sibling::span/b
addcontacts_page.contactpersonmobile
=xpath>//*[@id=iaddress_TEL_wrap]//dd//input
addcontacts_page.contactpersoncomment
=xpath>//textarea
addcontacts_page.savecontaceperson
=xpath>//span[.=确 定]

5)新建一个目录TestData,存放测试数据: 126邮箱联系人.xlsx

sheet1数据:
序号   用户名    密码       数据表      是否执行    测试结果
1          xxx        xxx          联系人        y
2          xxx        xxx          联系人        y

sheet2数据(联系人):
序号    联系人姓名   联系人邮箱    是否设为星标联系人   联系人手机号    联系人备注信息   验证页面包含的关键字   是否执行   执行时间   测试结果
1     lily       [email protected]        是         13512319865      lily      [email protected]          y
2      张三      [email protected]    否         15812316893      忽略     [email protected]         n
3          amy      am [email protected]     是            13901902408     lily       amy                n
4      李四       [email protected]         否         15796356569      lily       李四                  y

 

6)新建一个包,PageProject(一个页面一个类,里面有很多方法,方法是用于获取页面中的一个元素)
新建login_page(登录页面)模块,login_page.py,内容如下:

#ecoding=utf-8

import time
from Util.ObjectMap import *
from Util.ParsePageObjectRepository import ParsePageObjectRepositoryConfig

class LoginPage(object):
def __init__(self,driver):
self.driver
= driver
self.parse_config_file
= ParsePageObjectRepositoryConfig()
self.login_page_items
= self.parse_config_file.getItemsFromSection("126mail_login")
print self.login_page_items

#获取元素
def lbnormalbutton(self):
locateType, locateExpression
= self.login_page_items[login_page.lbnormalbutton].split(">")
print locateType, locateExpression
return getElement(self.driver, locateType, locateExpression)

def frame(self):
locateType, locateExpression
= self.login_page_items[login_page.frame].split(">")
print locateType, locateExpression
return getElement(self.driver, locateType, locateExpression)

def username(self):
locateType, locateExpression
= self.login_page_items[login_page.username].split(">")
print locateType, locateExpression
return getElement(self.driver, locateType, locateExpression)

def password(self):
locateType, locateExpression
= self.login_page_items[login_page.password].split(">")
print locateType, locateExpression
return getElement(self.driver, locateType, locateExpression)

def loginbutton(self):
locateType, locateExpression
= self.login_page_items[login_page.loginbutton].split(">")
print locateType, locateExpression
return getElement(self.driver, locateType, locateExpression)

#操作元素
def lbnormalbutton_click(self):
self.lbnormalbutton().click()

def switch_to_frame(self):
self.driver.switch_to.frame(self.frame())

def input_username(self,username):
self.username().send_keys(username)

def input_password(self,password):
self.password().send_keys(password)

def loginbutton_click(self):
self.loginbutton().click()


if __name__ == "__main__":
from selenium import webdriver
driver
= webdriver.Firefox(executable_path = "D:\geckodriver")
driver.maximize_window()
driver.get(
"https://mail.126.com")
lp
= LoginPage(driver)
# lp.lbnormalbutton().click()
lp.lbnormalbutton_click()
time.sleep(
1)
# driver.switch_to.frame(lp.frame())
lp.switch_to_frame()
time.sleep(
3)
# lp.username().send_keys("xxx")
lp.input_username("xxx")
# lp.password().send_keys("xxx")
lp.input_password("xxx")
lp.loginbutton_click()
time.sleep(
5)
driver.quit()

新建home_page(邮箱首页)模块,home_page.py,内容如下:

#encoding=utf-8

import time
from Util.ObjectMap import *
from Util.ParsePageObjectRepository import ParsePageObjectRepositoryConfig
from Action.login import *

class HomePage(object):
def __init__(self,driver):
self.driver
= driver
self.parse_config_file
= ParsePageObjectRepositoryConfig()
self.home_page_items
= self.parse_config_file.getItemsFromSection("126mail_homepage")
print self.home_page_items

def address_book_page_link(self):
locateType, locateExpression
= self.home_page_items[home_page.addressbook].split(">")
print locateType, locateExpression
return getElement(self.driver, locateType, locateExpression)

if __name__ == "__main__":
from selenium import webdriver
driver
= webdriver.Firefox(executable_path = "D:\geckodriver")
driver.maximize_window()
login(driver,
"xxx","xxx")
hp
= HomePage(driver)
hp.address_book_page_link().click()
time.sleep(
5)
driver.quit()

新建addressBook(通讯录)模块,addressBook.py,内容如下:

#encoding=utf-8

import time
from Util.ObjectMap import *
from Util.ParsePageObjectRepository import ParsePageObjectRepositoryConfig
from Action.login import *
from Action.visit_address_page import *

class AddressPage(object):
def __init__(self,driver):
self.driver
= driver
self.parse_config_file
= ParsePageObjectRepositoryConfig()
self.address_page_items
= self.parse_config_file.getItemsFromSection("126mail_addcontactspage")
print self.address_page_items

def add_contact_button(self):
locateType, locateExpression
= self.address_page_items[addcontacts_page.createcontactsbtn].split(">")
print locateType, locateExpression
return getElement(self.driver, locateType, locateExpression)

def contact_name(self):
locateType, locateExpression
= self.address_page_items[addcontacts_page.contactpersonname].split(">")
print locateType, locateExpression
return getElement(self.driver, locateType, locateExpression)

def contact_email(self):
locateType, locateExpression
= self.address_page_items[addcontacts_page.contactpersonemail].split(">")
print locateType, locateExpression
return getElement(self.driver, locateType, locateExpression)

def contact_is_star(self):
locateType, locateExpression
= self.address_page_items[addcontacts_page.starcontacts].split(">")
print locateType, locateExpression
return getElement(self.driver, locateType, locateExpression)

def contact_mobile(self):
locateType, locateExpression
= self.address_page_items[addcontacts_page.contactpersonmobile].split(">")
print locateType, locateExpression
return getElement(self.driver, locateType, locateExpression)

def contact_other_info(self):
locateType, locateExpression
= self.address_page_items[addcontacts_page.contactpersoncomment].split(">")
print locateType, locateExpression
return getElement(self.driver, locateType, locateExpression)

def contact_save_button(self):
locateType, locateExpression
= self.address_page_items[addcontacts_page.savecontaceperson].split(">")
print locateType, locateExpression
return getElement(self.driver, locateType, locateExpression)

if __name__ == "__main__":
from selenium import webdriver
driver
= webdriver.Firefox(executable_path="D:\geckodriver")
login(driver,
"xxx", "xxx")
hp
=HomePage(driver)
hp.address_book_page_link().click()
time.sleep(
5)
ap
=AddressPage(driver)
ap.add_contact_button().click()
time.sleep(
2)
ap.contact_name().send_keys(
"gloryroad")
ap.contact_email().send_keys(
"[email protected]")
ap.contact_is_star().click()
ap.contact_mobile().send_keys(
"1322222222")
ap.contact_other_info().send_keys(u
"光荣之路")
ap.contact_save_button().click()

7)新建一个包,Action ,封装各种方法

新建一个模块,login.py,内容如下:

#encoding=utf-8

import time
from selenium import webdriver
from Util.Log import *
from Util.FormatTime import data_time_chinese
from PageProject.login_page import *

def login(driver,username,password):
driver.get(
"https://mail.126.com")
time.sleep(
2)
lp
= LoginPage(driver)
lp.lbnormalbutton_click()
lp.switch_to_frame()
time.sleep(
2)
lp.input_username(username)
lp.input_password(password)
lp.loginbutton_click()
time.sleep(
2)
info(
"Login Successfully!")
print data_time_chinese()

if __name__ == "__main__":
driver
= webdriver.Firefox(executable_path = "D:\geckodriver")
login(driver,
"xxx","xxx")

新建一个模块,visit_address_page.py,内容如下:

#encoding=utf-8

from selenium import webdriver
from Util.Log import *
import time
from PageObject.login_page import *
from PageObject.home_page import *
from login import *

def visit_address_page(driver):
hp
= HomePage(driver)
hp.address_book_page_link().click()
time.sleep(
5)

if __name__ == "__main__":
driver
= webdriver.Firefox(executable_path = "D:\geckodriver")
login(driver,
"xxx","xxx")
visit_address_page(driver)

新建一个模块,add_contact.py,内容如下:

#encoding=utf-8

from selenium import webdriver
from Util.Log import *
from Util.FormatTime import *
import time
from PageObject.login_page import *
from PageObject.home_page import *
from PageObject.addressBook import *
from Util.Excel import *
from ProjectVar.var import *

def add_contact(driver,name="",email="",is_star=True,mobile="",other_info=""):
ap
= AddressPage(driver)
ap.add_contact_button().click()
time.sleep(
2)
ap.contact_name().send_keys(name)
ap.contact_email().send_keys(email)
if is_star == "True":
ap.contact_is_star().click()
ap.contact_mobile().send_keys(mobile)
ap.contact_other_info().send_keys(other_info)
ap.add_contact_button().click()
time.sleep(
3)

if __name__ == "__main__":
driver
= webdriver.Firefox(executable_path = "D:\geckodriver")
login(driver,
"xxx","xxx")
visit_address_page(driver)
add_contact(driver,
"Tom","[email protected]","True","18702235965",u"自己")
driver.quit()

8)新建一个目录TestScript,存放测试脚本
新建一个python文件,testContact.py,内容如下:

#encoding=utf-8

from selenium import webdriver
from Util.Log import *
from Util.Excel import *
from Util.FormatTime import *
import time
from Action.add_contact import *
from Action.visit_address_page import *
from Action.login import *
from ProjectVar.var import *
import sys
reload(sys)
sys.setdefaultencoding(
"utf8")

#取出所有行,使用切片取非第一行的所有行,因为第一行是标题,所以不用取
#
遍历每一行,然后使用读取单元格的方法,将用户名和密码读取到两个变量里面,然后传到login方法中,调用即可
pe = ParseExcel(test_data_excel_path)
pe.set_sheet_by_index(0)
print pe.get_default_name()
rows
= pe.get_all_rows()[1:]
for id,row in enumerate(rows):
if row[is_executed_col_no].value.lower() == "y":
username
= row[username_col_no].value
password
= row[password_col_no].value
print "username:",row[username_col_no].value
print "password:",row[password_col_no].value
driver
= webdriver.Firefox(executable_path = firefox_driver_path)

try:
login(driver,username,password)
visit_address_page(driver)
time.sleep(
3)
pe.set_sheet_by_index(
1)
print pe.get_default_name()
print pe.get_all_rows()
test_data_result_flag
= True #新建联系人都成功才是True,有一个失败就是False
for id2,row in enumerate(pe.get_all_rows()[1:]):
if row[7].value == "y":
try:
print "log:",row[1],row[1].value
print "log:",type(row[1])
add_contact(driver,row[
1].value,row[2].value,row[3].value,row[4].value,row[5].value)
pe.write_cell_content(id2
+ 2,9,data_time_chinese())
print "assert word:",row[assert_keyword_col_no].value
assert row[assert_keyword_col_no].value in driver.page_source
pe.write_cell_content(id2
+ 2,10,"pass")
except Exception,e:
print u"异常信息:",e.message
error(u
"异常信息:" + e.message)
pe.write_cell_content(id2
+ 2,9,data_time_chinese())
pe.write_cell_content(id2
+ 2,10,"fail")
test_data_result_flag
= False
else:
pe.write_cell_content(id2
+ 2,10,u"忽略")
continue
if test_data_result_flag == True:
pe.set_sheet_by_index(0)
pe.write_cell_content(id
+ 2,test_result_col_no,u"成功")
else:
pe.set_sheet_by_index(0)
pe.write_cell_content(id
+ 2, test_result_col_no, u"失败")
except Exception,e:
print u"异常信息:",e.message
info(u
"异常信息:" + e.message)

driver.quit()
else:
print u"" + str(id+1) + u"行数据不执行"
pe.set_sheet_by_index(0)
pe.write_cell_content(id
+2,test_result_col_no,u"忽略")
continue

#encoding=utf-8

from openpyxl import *
from openpyxl.styles import Font
from FormatTime import data_time_chinese

class ParseExcel(object):
def __init__(self,excel_file_path):
self.excel_file_path
=excel_file_path
self.workbook
=load_workbook(excel_file_path)
self.font
=Font(color=None)
self.colorDict
={"red":FFFF3030,"green":FF008B00}
self.sheet
=self.get_sheet_by_index(0)

# 通过序号设置当前要操作的sheet,使用index来获取相应的sheet
def set_sheet_by_index(self,sheet_index):
self.sheet
= self.get_sheet_by_index(sheet_index)

# 通过名字设置操作的sheet
def set_sheet_by_name(self,sheet_name):
self.sheet
= self.workbook.get_sheet_by_name(sheet_name)

# 获取当前操作的sheet和title名字
def get_default_name(self):
return self.sheet.title

# 通过名字获取要操作的sheet
def get_sheet_by_name(self,sheet_name):
self.sheet
= self.workbook.get_sheet_by_name(sheet_name)
return self.sheet

# 通过序号获取要操作的sheet
def get_sheet_by_index(self, sheet_index):
sheet_name
= self.workbook.get_sheet_names()[sheet_index]
self.sheet
= self.get_sheet_by_name(sheet_name)
return self.sheet

#获取sheet中的最大行号,从0开始
def get_max_row_no(self):
return self.sheet.max_row

# 获取sheet中的最大列号,从0开始
def get_max_col_no(self):
return self.sheet.max_column

#获取默认sheet中的最小行号
def get_min_row_no(self):
return self.sheet.min_row

# 获取默认sheet中的最小列号
def get_min_col_no(self):
return self.sheet.min_column

#获取正在操作的sheet中的所有行对象
def get_all_rows(self):
# rows = []
# for row in self.sheet.iter_rows():
# rows.append(row)
# return rows
#也可用以上方法
return list(self.sheet.iter_rows())

#获取正在操作的sheet中的所有列对象
def get_all_cols(self):
# cols = []
# for col in self.sheet.iter_cols():
# cols.append(col)
# return cols
#也可用以上方法
return list(self.sheet.iter_cols())

#获取某一个行对象,第一行从0开始
def get_single_row(self,row_no):
return self.get_all_rows()[row_no]

# 获取某一个列对象,第一列从0开始
def get_single_col(self, col_no):
return self.get_all_cols()[col_no]

#获取某一个单元格对象,行号和列号从1开始
def get_cell(self,row_no,col_no):
return self.sheet.cell(row = row_no,column = col_no)

# 获取某一个单元格内容
def get_cell_content(self, row_no, col_no):
return self.sheet.cell(row = row_no,column = col_no).value

# 给某一个单元格写入指定内容,行号和列号从1开始
#调用此方法时,excel不要处于打开状态
def write_cell_content(self, row_no, col_no,content,font=None):
self.sheet.cell(row
=row_no,column=col_no).value = content
self.workbook.save(self.excel_file_path)

#给某个单元格写入当前时间,行号和列号从1开始
#调用此方法时,excel不要处于打开状态
def write_cell_current_time(self,row_no,col_no):
self.sheet.cell(row
=row_no,column=col_no).value = data_time_chinese()
self.workbook.save(self.excel_file_path)

def save_excel_file(self):
self.workbook.save(self.excel_file_path)
#保存所有对单元格的修改

if __name__ == "__main__":
#测试所有的方法
pe = ParseExcel("D:\test\test.xlsx")
pe.set_sheet_by_index(0)
print pe.get_default_name()
pe.set_sheet_by_name(
"2")
print pe.get_default_name()
print pe.get_sheet_by_name("2")
print pe.get_sheet_by_index(0)

print "max rows:",pe.get_max_row_no()
print "min row",pe.get_min_row_no()
print pe.get_all_rows() #获取所有行对象
print pe.get_all_rows()[2] #获取某一行
print pe.get_all_rows()[0][2] #获取某一个单元格
print pe.get_all_rows()[2][1].value #获取某一单元格的值

print "max cols:",pe.get_max_col_no()
print "min col",pe.get_min_col_no()
print pe.get_all_cols() #获取所有行对象
print pe.get_all_cols()[2] #获取某一行
print pe.get_all_cols()[0][2] #获取某一个单元格
print pe.get_all_cols()[2][1].value #获取某一单元格的值

print len(pe.get_all_rows())
for cell in pe.get_all_rows()[1]:
print cell.value

print len(pe.get_all_cols())
for cell in pe.get_all_cols()[2]:
print cell.value

print "================================"

for cell in pe.get_single_col(0):
print cell.value

for cell in pe.get_single_row(0):
print cell.value

print "--------------------"
print pe.get_cell(1,2)
print pe.get_cell_content(1,1)

pe.write_cell_content(
5,6,"hello")
print pe.get_cell_content(5,6)
pe.write_cell_current_time(
7,7)
print pe.get_cell_content(7,7)

#encoding=utf-8

import time

#返回中文的年月日时分秒
def data_time_chinese():
return time.strftime("%Y年%m月%d日 %H时%M分%S秒",time.localtime())

#返回中文的时分秒
def time_chinese():
return time.strftime("%H时%M分%S秒", time.localtime())

# 返回英文的年月日时分秒
def data_time_english():
return time.strftime("%Y-%m-%d %H:%M:%S秒", time.localtime())

# 返回英文的时分秒
def time_english():
return time.strftime("%H:%M:%S秒", time.localtime())

if __name__ == "__main__":
print data_time_chinese()
print time_chinese()
print data_time_english()
print time_english()

#encoding=utf-8

import logging
import logging.config
from ProjectVar.var import *

#读取日志的配置文件
logging.config.fileConfig(log_config_file_path)
#选择一个日志格式
logger = logging.getLogger("example02")


def info(message):
#打印info级别的信息
logging.info(message)

def error(message):
#打印error级别的信息
logging.error(message)

def warning(message):
#打印warning级别的信息
logging.warning(message)

if __name__ == "__main__":
error(
"---ERROR---")
info(
"===Test===")
warning(
"````Wang`````")

#encoding=utf-8

from selenium.webdriver.support.ui import WebDriverWait
import time

#获取单个页面元素对象
def getElement(driver,locateType,locateExpression):
try:
element
= WebDriverWait(driver,5).until(lambda x: x.find_element(by = locateType,value = locateExpression))
return element
except Exception,e:
raise e

#获取多个相同页面元素对象,以list返回
def getElements(driver,locateType,locateExpression):
try:
element
= WebDriverWait(driver,5).until(lambda x: x.find_elements(by = locateType,value = locateExpression))
return element
except Exception,e:
raise e

if __name__ == "__main__":
from selenium import webdriver
#进行单元测试
driver = webdriver.Firefox(executable_path = "D:\geckodriver")
driver.maximize_window()
driver.get(
"https://mail.126.com/")
time.sleep(
2)
lb
= getElement(driver,"id","lbNormal")
print lb
driver.quit()

#encoding=utf-8

from ConfigParser import ConfigParser
from ProjectVar.var import page_object_repository_path

class ParsePageObjectRepositoryConfig(object):
def __init__(self):
self.cf
= ConfigParser()
self.cf.read(page_object_repository_path)

#获取某个section,所有的key和value,用字典方式返回
def getItemsFromSection(self,sectionName):
print self.cf.items(sectionName)
return dict(self.cf.items(sectionName))

#获取某一个具体的选项对应的value
def getOptionValue(self,sectionName,optionName):
return self.cf.get(sectionName,optionName)

#encoding=utf-8

import os

#获取工程所在目录的绝对路径
project_path = os.path.dirname(os.path.dirname(__file__))
#日志配置文件的绝对路径
log_config_file_path = project_path + "/Conf/logger.conf"
#测试数据excel文件的绝对路径
test_data_excel_path = project_path.decode("utf-8") + u"/TestData/126邮箱联系人.xlsx"
#
page_object_repository_path = project_path.decode("utf-8") + "/Conf/PageProjectRepository.ini"

username_col_no
=1
password_col_no
=2
is_executed_col_no
=4
test_result_col_no
=6
exception_info_col_no
=7
assert_keyword_col_no
= 6
firefox_driver_path
= D:\geckodriver

if __name__ == "__main__":
print os.path.dirname(__file__)
print os.path.dirname(os.path.dirname(__file__))
print os.path.dirname(project_path+"/Conf/logger.conf") #路径斜杠向左向右都可以
print log_config_file_path
print test_data_excel_path

#logger.conf

#
##############################################
[loggers]
keys
=root,example01,example02
[logger_root]
level
=DEBUG
handlers
=hand01,hand02

[logger_example01]
handlers
=hand01,hand02
qualname
=example01
propagate
=0

[logger_example02]
handlers
=hand01,hand03
qualname
=example02
propagate
=0

###############################################
[handlers]
keys
=hand01,hand02,hand03

[handler_hand01]
class=StreamHandler
level
=INFO
formatter
=form01
args
=(sys.stderr,)

[handler_hand02]
class=FileHandler
level
=DEBUG
formatter
=form01
args
=(DataDrivenFrameWork.log, a)

[handler_hand03]
class=handlers.RotatingFileHandler
level
=INFO
formatter
=form01
args
=(DataDrivenFrameWork.log, a, 10*1024*1024, 5)

###############################################
[formatters]
keys
=form01,form02

[formatter_form01]
format
=%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s
datefmt
=%Y-%m-%d %H:%M:%S

[formatter_form02]
format
=%(name)-12s: %(levelname)-8s %(message)s
datefmt
=%Y-%m-%d %H:%M:%S

[126mail_login]

login_page.lbnormalbutton
=id>lbNormal
login_page.frame
=xpath>//iframe[contains(@id,"x-URS-iframe")]
login_page.username
=xpath>//input[@name=email]
login_page.password
=xpath>//input[@name=password]
login_page.loginbutton
=id>dologin

[126mail_homepage]
home_page.addressbook
=xpath>//div[text()=通讯录]

[126mail_addcontactspage]
addcontacts_page.createcontactsbtn
=xpath>//span[text()=新建联系人]
addcontacts_page.contactpersonname
=xpath>//a[@title=编辑详细姓名]/preceding-sibling::div/input
addcontacts_page.contactpersonemail
=xpath>//*[@id=iaddress_MAIL_wrap]//input
addcontacts_page.starcontacts
=xpath>//span[text()=设为星标联系人]/preceding-sibling::span/b
addcontacts_page.contactpersonmobile
=xpath>//*[@id=iaddress_TEL_wrap]//dd//input
addcontacts_page.contactpersoncomment
=xpath>//textarea
addcontacts_page.savecontaceperson
=xpath>//span[.=确 定]

#ecoding=utf-8

import time
from Util.ObjectMap import *
from Util.ParsePageObjectRepository import ParsePageObjectRepositoryConfig

class LoginPage(object):
def __init__(self,driver):
self.driver
= driver
self.parse_config_file
= ParsePageObjectRepositoryConfig()
self.login_page_items
= self.parse_config_file.getItemsFromSection("126mail_login")
print self.login_page_items

#获取元素
def lbnormalbutton(self):
locateType, locateExpression
= self.login_page_items[login_page.lbnormalbutton].split(">")
print locateType, locateExpression
return getElement(self.driver, locateType, locateExpression)

def frame(self):
locateType, locateExpression
= self.login_page_items[login_page.frame].split(">")
print locateType, locateExpression
return getElement(self.driver, locateType, locateExpression)

def username(self):
locateType, locateExpression
= self.login_page_items[login_page.username].split(">")
print locateType, locateExpression
return getElement(self.driver, locateType, locateExpression)

def password(self):
locateType, locateExpression
= self.login_page_items[login_page.password].split(">")
print locateType, locateExpression
return getElement(self.driver, locateType, locateExpression)

def loginbutton(self):
locateType, locateExpression
= self.login_page_items[login_page.loginbutton].split(">")
print locateType, locateExpression
return getElement(self.driver, locateType, locateExpression)

#操作元素
def lbnormalbutton_click(self):
self.lbnormalbutton().click()

def switch_to_frame(self):
self.driver.switch_to.frame(self.frame())

def input_username(self,username):
self.username().send_keys(username)

def input_password(self,password):
self.password().send_keys(password)

def loginbutton_click(self):
self.loginbutton().click()


if __name__ == "__main__":
from selenium import webdriver
driver
= webdriver.Firefox(executable_path = "D:\geckodriver")
driver.maximize_window()
driver.get(
"https://mail.126.com")
lp
= LoginPage(driver)
# lp.lbnormalbutton().click()
lp.lbnormalbutton_click()
time.sleep(
1)
# driver.switch_to.frame(lp.frame())
lp.switch_to_frame()
time.sleep(
3)
# lp.username().send_keys("xxx")
lp.input_username("xxx")
# lp.password().send_keys("xxx")
lp.input_password("xxx")
lp.loginbutton_click()
time.sleep(
5)
driver.quit()

#encoding=utf-8

import time
from Util.ObjectMap import *
from Util.ParsePageObjectRepository import ParsePageObjectRepositoryConfig
from Action.login import *

class HomePage(object):
def __init__(self,driver):
self.driver
= driver
self.parse_config_file
= ParsePageObjectRepositoryConfig()
self.home_page_items
= self.parse_config_file.getItemsFromSection("126mail_homepage")
print self.home_page_items

def address_book_page_link(self):
locateType, locateExpression
= self.home_page_items[home_page.addressbook].split(">")
print locateType, locateExpression
return getElement(self.driver, locateType, locateExpression)

if __name__ == "__main__":
from selenium import webdriver
driver
= webdriver.Firefox(executable_path = "D:\geckodriver")
driver.maximize_window()
login(driver,
"xxx","xxx")
hp
= HomePage(driver)
hp.address_book_page_link().click()
time.sleep(
5)
driver.quit()

#encoding=utf-8

import time
from Util.ObjectMap import *
from Util.ParsePageObjectRepository import ParsePageObjectRepositoryConfig
from Action.login import *
from Action.visit_address_page import *

class AddressPage(object):
def __init__(self,driver):
self.driver
= driver
self.parse_config_file
= ParsePageObjectRepositoryConfig()
self.address_page_items
= self.parse_config_file.getItemsFromSection("126mail_addcontactspage")
print self.address_page_items

def add_contact_button(self):
locateType, locateExpression
= self.address_page_items[addcontacts_page.createcontactsbtn].split(">")
print locateType, locateExpression
return getElement(self.driver, locateType, locateExpression)

def contact_name(self):
locateType, locateExpression
= self.address_page_items[addcontacts_page.contactpersonname].split(">")
print locateType, locateExpression
return getElement(self.driver, locateType, locateExpression)

def contact_email(self):
locateType, locateExpression
= self.address_page_items[addcontacts_page.contactpersonemail].split(">")
print locateType, locateExpression
return getElement(self.driver, locateType, locateExpression)

def contact_is_star(self):
locateType, locateExpression
= self.address_page_items[addcontacts_page.starcontacts].split(">")
print locateType, locateExpression
return getElement(self.driver, locateType, locateExpression)

def contact_mobile(self):
locateType, locateExpression
= self.address_page_items[addcontacts_page.contactpersonmobile].split(">")
print locateType, locateExpression
return getElement(self.driver, locateType, locateExpression)

def contact_other_info(self):
locateType, locateExpression
= self.address_page_items[addcontacts_page.contactpersoncomment].split(">")
print locateType, locateExpression
return getElement(self.driver, locateType, locateExpression)

def contact_save_button(self):
locateType, locateExpression
= self.address_page_items[addcontacts_page.savecontaceperson].split(">")
print locateType, locateExpression
return getElement(self.driver, locateType, locateExpression)

if __name__ == "__main__":
from selenium import webdriver
driver
= webdriver.Firefox(executable_path="D:\geckodriver")
login(driver,
"xxx", "xxx")
hp
=HomePage(driver)
hp.address_book_page_link().click()
time.sleep(
5)
ap
=AddressPage(driver)
ap.add_contact_button().click()
time.sleep(
2)
ap.contact_name().send_keys(
"gloryroad")
ap.contact_email().send_keys(
"[email protected]")
ap.contact_is_star().click()
ap.contact_mobile().send_keys(
"1322222222")
ap.contact_other_info().send_keys(u
"光荣之路")
ap.contact_save_button().click()

#encoding=utf-8

import time
from selenium import webdriver
from Util.Log import *
from Util.FormatTime import data_time_chinese
from PageProject.login_page import *

def login(driver,username,password):
driver.get(
"https://mail.126.com")
time.sleep(
2)
lp
= LoginPage(driver)
lp.lbnormalbutton_click()
lp.switch_to_frame()
time.sleep(
2)
lp.input_username(username)
lp.input_password(password)
lp.loginbutton_click()
time.sleep(
2)
info(
"Login Successfully!")
print data_time_chinese()

if __name__ == "__main__":
driver
= webdriver.Firefox(executable_path = "D:\geckodriver")
login(driver,
"xxx","xxx")

#encoding=utf-8

from selenium import webdriver
from Util.Log import *
import time
from PageObject.login_page import *
from PageObject.home_page import *
from login import *

def visit_address_page(driver):
hp
= HomePage(driver)
hp.address_book_page_link().click()
time.sleep(
5)

if __name__ == "__main__":
driver
= webdriver.Firefox(executable_path = "D:\geckodriver")
login(driver,
"xxx","xxx")
visit_address_page(driver)

#encoding=utf-8

from selenium import webdriver
from Util.Log import *
from Util.FormatTime import *
import time
from PageObject.login_page import *
from PageObject.home_page import *
from PageObject.addressBook import *
from Util.Excel import *
from ProjectVar.var import *

def add_contact(driver,name="",email="",is_star=True,mobile="",other_info=""):
ap
= AddressPage(driver)
ap.add_contact_button().click()
time.sleep(
2)
ap.contact_name().send_keys(name)
ap.contact_email().send_keys(email)
if is_star == "True":
ap.contact_is_star().click()
ap.contact_mobile().send_keys(mobile)
ap.contact_other_info().send_keys(other_info)
ap.add_contact_button().click()
time.sleep(
3)

if __name__ == "__main__":
driver
= webdriver.Firefox(executable_path = "D:\geckodriver")
login(driver,
"xxx","xxx")
visit_address_page(driver)
add_contact(driver,
"Tom","[email protected]","True","18702235965",u"自己")
driver.quit()

#encoding=utf-8

from selenium import webdriver
from Util.Log import *
from Util.Excel import *
from Util.FormatTime import *
import time
from Action.add_contact import *
from Action.visit_address_page import *
from Action.login import *
from ProjectVar.var import *
import sys
reload(sys)
sys.setdefaultencoding(
"utf8")

#取出所有行,使用切片取非第一行的所有行,因为第一行是标题,所以不用取
#
遍历每一行,然后使用读取单元格的方法,将用户名和密码读取到两个变量里面,然后传到login方法中,调用即可
pe = ParseExcel(test_data_excel_path)
pe.set_sheet_by_index(0)
print pe.get_default_name()
rows
= pe.get_all_rows()[1:]
for id,row in enumerate(rows):
if row[is_executed_col_no].value.lower() == "y":
username
= row[username_col_no].value
password
= row[password_col_no].value
print "username:",row[username_col_no].value
print "password:",row[password_col_no].value
driver
= webdriver.Firefox(executable_path = firefox_driver_path)

try:
login(driver,username,password)
visit_address_page(driver)
time.sleep(
3)
pe.set_sheet_by_index(
1)
print pe.get_default_name()
print pe.get_all_rows()
test_data_result_flag
= True #新建联系人都成功才是True,有一个失败就是False
for id2,row in enumerate(pe.get_all_rows()[1:]):
if row[7].value == "y":
try:
print "log:",row[1],row[1].value
print "log:",type(row[1])
add_contact(driver,row[
1].value,row[2].value,row[3].value,row[4].value,row[5].value)
pe.write_cell_content(id2
+ 2,9,data_time_chinese())
print "assert word:",row[assert_keyword_col_no].value
assert row[assert_keyword_col_no].value in driver.page_source
pe.write_cell_content(id2
+ 2,10,"pass")
except Exception,e:
print u"异常信息:",e.message
error(u
"异常信息:" + e.message)
pe.write_cell_content(id2
+ 2,9,data_time_chinese())
pe.write_cell_content(id2
+ 2,10,"fail")
test_data_result_flag
= False
else:
pe.write_cell_content(id2
+ 2,10,u"忽略")
continue
if test_data_result_flag == True:
pe.set_sheet_by_index(0)
pe.write_cell_content(id
+ 2,test_result_col_no,u"成功")
else:
pe.set_sheet_by_index(0)
pe.write_cell_content(id
+ 2, test_result_col_no, u"失败")
except Exception,e:
print u"异常信息:",e.message
info(u
"异常信息:" + e.message)

driver.quit()
else:
print u"" + str(id+1) + u"行数据不执行"
pe.set_sheet_by_index(0)
pe.write_cell_content(id
+2,test_result_col_no,u"忽略")
continue

Leave a Comment

Your email address will not be published.