Python+Selenium框架设计篇之4-框架内封装日志类和浏览器引擎类

本文开始一步一步介绍,如何创建自己的第一个自动化测试框架。这一篇,我们介绍,如何封装自己的日志类和浏览器引擎类。

相关步骤:

1. 打开PyCharm,创建如下格式的项目层级结构,文件名称和我保持一样;

Python+Selenium框架设计篇之4-框架内封装日志类和浏览器引擎类_第1张图片

2. 相关文件代码如下

配置文件config.ini相关设计如下:

 

#  this is config file, only store browser type and server URL

[browserType]
#browserName = Firefox
browserName = Chrome
#browserName = IE

[testServer]
URL = https://www.baidu.com
#URL = www.google.com

浏览器引擎类browser_engine.py相关脚本代码如下:

 

 

# -*- coding:utf-8 -*-
import ConfigParser
import os.path
from selenium import webdriver
from framework.logger import Logger

logger = Logger(logger="BrowserEngine").getlog()


class BrowserEngine(object):

    dir = os.path.dirname(os.path.abspath('.'))  # 注意相对路径获取方法
    chrome_driver_path = dir + '/tools/chromedriver.exe'
    ie_driver_path = dir + '/tools/IEDriverServer.exe'

    def __init__(self, driver):
        self.driver = driver

    # read the browser type from config.ini file, return the driver
    def open_browser(self, driver):
        config = ConfigParser.ConfigParser()
        # file_path = os.path.dirname(os.getcwd()) + '/config/config.ini'
        file_path = os.path.dirname(os.path.abspath('.')) + '/config/config.ini'
        config.read(file_path)
        #config.read(file_path,encoding='UTF-8'), 如果代码有中文注释,用这个,不然报解码错误

        browser = config.get("browserType", "browserName")
        logger.info("You had select %s browser." % browser)
        url = config.get("testServer", "URL")
        logger.info("The test server url is: %s" % url)


        if browser == "Firefox":
            driver = webdriver.Firefox()
            logger.info("Starting firefox browser.")
        elif browser == "Chrome":
            driver = webdriver.Chrome(self.chrome_driver_path)
            logger.info("Starting Chrome browser.")
        elif browser == "IE":
            driver = webdriver.Ie(self.ie_driver_path)
            logger.info("Starting IE browser.")

        driver.get(url)
        logger.info("Open url: %s" % url)
        driver.maximize_window()
        logger.info("Maximize the current window.")
        driver.implicitly_wait(10)
        logger.info("Set implicitly wait 10 seconds.")
        return driver

    def quit_browser(self):
        logger.info("Now, Close and quit the browser.")
        self.driver.quit()

日志类logger.py相关脚本代码如下:

 

 

# _*_ coding: utf-8 _*_
import logging
import os.path
import time


class Logger(object):

    def __init__(self, logger):
        '''
            指定保存日志的文件路径,日志级别,以及调用文件
            将日志存入到指定的文件中
        '''

        # 创建一个logger
        self.logger = logging.getLogger(logger)
        self.logger.setLevel(logging.DEBUG)

        # 创建一个handler,用于写入日志文件
        rq = time.strftime('%Y%m%d%H%M', time.localtime(time.time()))
        # log_path = os.path.dirname(os.getcwd()) + '/Logs/'  # 项目根目录下/Logs 保存日志
        log_path = os.path.dirname(os.path.abspath('.')) + '/logs/'
        # 如果case组织结构式 /testsuit/featuremodel/xxx.py , 那么得到的相对路径的父路径就是项目根目录
        log_name = log_path + rq + '.log'
        fh = logging.FileHandler(log_name)
        fh.setLevel(logging.INFO)

        # 再创建一个handler,用于输出到控制台
        ch = logging.StreamHandler()
        ch.setLevel(logging.INFO)

        # 定义handler的输出格式
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        fh.setFormatter(formatter)
        ch.setFormatter(formatter)

        # 给logger添加handler
        self.logger.addHandler(fh)
        self.logger.addHandler(ch)

    def getlog(self):
        return self.logger

页面对象pageobject这里暂不用,下一篇介绍

 

测试脚本baidu_search.py相关脚本如下:

 

# coding=utf-8
import time
import unittest
from framework.browser_engine import BrowserEngine


class BaiduSearch(unittest.TestCase):


    def setUp(self):
        """
        测试固件的setUp()的代码,主要是测试的前提准备工作
        :return:
        """
        browse = BrowserEngine(self)
        self.driver = browse.open_browser(self)


    def tearDown(self):
        """
        测试结束后的操作,这里基本上都是关闭浏览器
        :return:
        """
        self.driver.quit()

    def test_baidu_search(self):
        """
        这里一定要test开头,把测试逻辑代码封装到一个test开头的方法里。
        :return:
        """
        self.driver.find_element_by_id('kw').send_keys('selenium')
        time.sleep(1)
        try:
            assert 'selenium' in self.driver.title
            print ('Test Pass.')
        except Exception as e:
            print ('Test Fail.', format(e))

if __name__ == '__main__':
    unittest.main()

 

工具包,这里把三个浏览器的driver文件都放根目录一个文件夹里,这样别人拷贝这个项目也不需要去下载这些文件。

运行测试脚本baidu_search.py,会在根目录下的logs文件生成日志文件,例如我:

 

2017-04-19 17:49:06,220 - BrowserEngine - INFO - You had select Chrome browser.
2017-04-19 17:49:06,220 - BrowserEngine - INFO - The test server url is: https://www.baidu.com
2017-04-19 17:49:10,049 - BrowserEngine - INFO - Starting Chrome browser.
2017-04-19 17:49:11,115 - BrowserEngine - INFO - Open url: https://www.baidu.com
2017-04-19 17:49:12,349 - BrowserEngine - INFO - Maximize the current window.
2017-04-19 17:49:12,349 - BrowserEngine - INFO - Set implicitly wait 10 seconds.

 

 

 

 

 

你可能感兴趣的:(python,selenium,自动化测试,自动化测试框架设计)