码迷,mamicode.com
首页 > 编程语言 > 详细

基于python语言下的UI自动化测试框架搭建(二)

时间:2019-08-09 17:48:06      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:page   and   text   browser   自己   logs   tle   window   method   

 

framework包中文件如下所示:

 

技术图片

 

base_page.py:常用操作方法

 

在framework包下创建base_page.py文件,文件中封装一些页面常用操作方法,可以自己在这个类中进行对应方法的添加,代码如下:

 

  1 # coding=utf-8
  2 import time
  3 from selenium.common.exceptions import NoSuchElementException
  4 import os.path
  5 from framework.logger import Logger
  6 
  7 # create a logger instance
  8 logger = Logger(logger="BasePage").getlog()
  9 
 10 
 11 class BasePage(object):
 12     """
 13     定义一个页面基类,让所有页面都继承这个类,封装一些常用的页面操作方法到这个类
 14     """
 15 
 16     def __init__(self, driver):
 17         self.driver = driver
 18 
 19     # quit browser and end testing
 20     def quit_browser(self):
 21         self.driver.quit()
 22 
 23     # 浏览器前进操作
 24     def forward(self):
 25         self.driver.forward()
 26         logger.info("Click forward on current page.")
 27 
 28     # 浏览器后退操作
 29     def back(self):
 30         self.driver.back()
 31         logger.info("Click back on current page.")
 32 
 33     # 隐式等待
 34     def wait(self, seconds):
 35         self.driver.implicitly_wait(seconds)
 36         logger.info("wait for %d seconds." % seconds)
 37 
 38     # 点击关闭当前窗口
 39     def close(self):
 40         try:
 41             self.driver.close()
 42             logger.info("Closing and quit the browser.")
 43         except NameError as e:
 44             logger.error("Failed to quit the browser with %s" % e)
 45 
 46     # 保存图片
 47     def get_windows_img(self):
 48         """
 49         在这里我们把file_path这个参数写死,直接保存到我们项目根目录的一个文件夹.\Screenshots下
 50         """
 51         file_path = os.path.dirname(os.path.abspath(.‘)) + \screenshots\\ 52         rq = time.strftime(%Y%m%d%H%M%S, time.localtime(time.time()))
 53         screen_name = file_path + rq + .png 54         try:
 55             self.driver.get_screenshot_as_file(screen_name)
 56             logger.info("Had take screenshot and save to folder : \screenshots")
 57         except NameError as e:
 58             logger.error("Failed to take screenshot! %s" % e)
 59             self.get_windows_img()
 60 
 61     # 定位元素方法
 62     def find_element(self, selector):
 63         """
 64          这个地方为什么是根据=>来切割字符串,请看页面里定位元素的方法
 65          submit_btn = "id=>su"
 66          login_lnk = "xpath => //*[@id=‘u1‘]/a[7]"  # 百度首页登录链接定位
 67          如果采用等号,结果很多xpath表达式中包含一个=,这样会造成切割不准确,影响元素定位
 68         :param selector:
 69         :return: element
 70         """
 71         element = ‘‘
 72         if =>not in selector:
 73             return self.driver.find_element_by_id(selector)
 74         selector_by = selector.split(=>)[0]
 75         selector_value = selector.split(=>‘)[1]
 76 
 77         if selector_by == "i" or selector_by == id:
 78             try:
 79                 element = self.driver.find_element_by_id(selector_value)
 80                 logger.info("Had find the element \‘ %s \‘ successful "
 81                             "by %s via value: %s " % (element.text, selector_by, selector_value))
 82             except NoSuchElementException as e:
 83                 logger.error("NoSuchElementException: %s" % e)
 84                 self.get_windows_img()  # take screenshot
 85         elif selector_by == "n" or selector_by == name:
 86             element = self.driver.find_element_by_name(selector_value)
 87         elif selector_by == "c" or selector_by == class_name:
 88             element = self.driver.find_element_by_class_name(selector_value)
 89         elif selector_by == "l" or selector_by == link_text:
 90             element = self.driver.find_element_by_link_text(selector_value)
 91         elif selector_by == "p" or selector_by == partial_link_text:
 92             element = self.driver.find_element_by_partial_link_text(selector_value)
 93         elif selector_by == "t" or selector_by == tag_name:
 94             element = self.driver.find_element_by_tag_name(selector_value)
 95         elif selector_by == "x" or selector_by == xpath:
 96             try:
 97                 element = self.driver.find_element_by_xpath(selector_value)
 98                 logger.info("Had find the element \‘ %s \‘ successful "
 99                             "by %s via value: %s " % (element.text, selector_by, selector_value))
100             except NoSuchElementException as e:
101                 logger.error("NoSuchElementException: %s" % e)
102                 self.get_windows_img()
103         elif selector_by == "s" or selector_by == selector_selector:
104             element = self.driver.find_element_by_css_selector(selector_value)
105         else:
106             raise NameError("Please enter a valid type of targeting elements.")
107 
108         return element
109 
110 
111     # 输入
112     def type(self, selector, text):
113 
114         el = self.find_element(selector)
115         el.clear()
116         try:
117             el.send_keys(text)
118             logger.info("Had type \‘ %s \‘ in inputBox" % text)
119         except NameError as e:
120             logger.error("Failed to type in input box with %s" % e)
121             self.get_windows_img()
122 
123     # 清除文本框
124     def clear(self, selector):
125 
126         el = self.find_element(selector)
127         try:
128             el.clear()
129             logger.info("Clear text in input box before typing.")
130         except NameError as e:
131             logger.error("Failed to clear in input box with %s" % e)
132             self.get_windows_img()
133 
134     # 点击元素
135     def click(self, selector):
136 
137         el = self.find_element(selector)
138         try:
139             el.click()
140             logger.info("The element \‘ %s \‘ was clicked." % el.text)
141         except NameError as e:
142             logger.error("Failed to click the element with %s" % e)
143 
144     # 或者网页标题
145     def get_page_title(self):
146         logger.info("Current page title is %s" % self.driver.title)
147         return self.driver.title
148 
149     @staticmethod
150     def sleep(seconds):
151         time.sleep(seconds)
152         logger.info("Sleep for %d seconds" % seconds)

 

browser_engine.py:浏览器操作方法

 

browser_engine.py中封装获取根目录下浏览器驱动方法和浏览器操作方法,但需要注意的是,如果在里面使用中文,需要切换方法,但是小编在切换了以后还是不对,可能是因为使用2.7版本python吧,用3.x版本的朋友可以尝试一下使用中文进行日志打印的操作,代码如下:

 

 1 # -*- coding:utf-8 -*-
 2 import ConfigParser
 3 import os.path
 4 from selenium import webdriver
 5 from framework.logger import Logger
 6 
 7 logger = Logger(logger="BrowserEngine").getlog()
 8 
 9 
10 class BrowserEngine(object):
11     dir = os.path.dirname(os.path.abspath(.‘))  # 注意相对路径获取方法
12     chrome_driver_path = dir + /tools/chromedriver.exe13     ie_driver_path = dir + /tools/IEDriverServer.exe14 
15     def __init__(self, driver):
16         self.driver = driver
17 
18     # read the browser type from config.ini file, return the driver
19     def open_browser(self, driver):
20         config = ConfigParser.ConfigParser()
21         # file_path = os.path.dirname(os.getcwd()) + ‘/config/config.ini‘
22         file_path = os.path.dirname(os.path.abspath(.‘)) + /config/config.ini23         config.read(file_path)
24         # config.read(file_path,encoding=‘UTF-8‘), 如果代码有中文注释,用这个,不然报解码错误
25 
26         browser = config.get("browserType", "browserName")
27         logger.info("You had select %s browser." % browser)
28         url = config.get("testServer", "URL")
29         logger.info("The test server url is: %s" % url)
30 
31         if browser == "Firefox":
32             driver = webdriver.Firefox()
33             logger.info("Starting firefox browser.")
34         elif browser == "Chrome":
35             driver = webdriver.Chrome(self.chrome_driver_path)
36             logger.info("Starting Chrome browser.")
37         elif browser == "IE":
38             driver = webdriver.Ie(self.ie_driver_path)
39             logger.info("Starting IE browser.")
40 
41         driver.get(url)
42         logger.info("Open url: %s" % url)
43         driver.maximize_window()
44         logger.info("Maximize the current window.")
45         driver.implicitly_wait(10)
46         logger.info("Set implicitly wait 10 seconds.")
47         return driver
48 
49     def quit_browser(self):
50         logger.info("Now, Close and quit the browser.")
51         self.driver.quit()

 

logger.py:日志处理

现在,我们来看一下logger.py中是怎么写的,logger需要实现的功能是要指定保存的日志文件路径,日志级别还有调用文件后将日志存入到指定的文件夹中,日志命名格式为当前案例执行时间并精确到秒,可以保证在执行案例过程中精确的打印出当前案例执行过程的日志。代码如下:

 1 #_*_coding:utf-8 _*_
 2 import logging
 3 import os.path
 4 import time
 5 
 6 class Logger(object):
 7     def __init__(self,logger):
 8         ‘‘‘指定保存日志的文件路径,日志级别以及调用文件将日志存入到指定的文件中‘‘‘
 9         #创建一个logger
10         self.logger = logging.getLogger(logger)
11         self.logger.setLevel(logging.DEBUG)
12         #创建一个handler,用于写入日志文件
13         rq = time.strftime(%Y%m%d%H%M%S,time.localtime(time.time()))
14         log_path = os.path.dirname(os.path.abspath(.))+\logs\\
15         #如果case组织结构式/testsuit/fraturemoddel/xxx.py,那么得到的相对路径的父路径就是项目的根目录
16         log_name = log_path + rq + .log
17         fh = logging.FileHandler(log_name)
18         fh.setLevel(logging.INFO)
19 
20         #再创建一个handler,用于输出到控制台
21         ch = logging.StreamHandler()
22         ch.setLevel(logging.INFO)
23         #定义handler的输出格式
24         formatter = logging.Formatter(%(asctime)s - %(name)s - %(levelname)s - %(message)s)
25         fh.setFormatter(formatter)
26         ch.setFormatter(formatter)
27         #给logger添加handler
28         self.logger.addHandler(fh)
29         self.logger.addHandler(ch)
30     def getlog(self):
31         return self.logger

 

基于python语言下的UI自动化测试框架搭建(二)

标签:page   and   text   browser   自己   logs   tle   window   method   

原文地址:https://www.cnblogs.com/yk617558302/p/11328316.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!