Web自动化测试项目(七)日志
一、日志作用
- 调试程序
- 了解系统程序运行的情况,是否正常
- 系统程序运行故障分析与问题定位
- 用来做用户行为分析和数据统计
二、为项目添加日志
└── utils
├── log_utils.py
└── se_utils.py
log_utils.py
import logging.handlers
import time
class GetLogger():
logger = None
@classmethod
def get_logger(cls):
if cls.logger == None:
# 日志器实例
cls.logger = logging.getLogger()
# 设置日志级别
cls.logger .setLevel(level=logging.INFO)
# 控制台处理器实例
ch = logging.StreamHandler()
# 以时间切分日志文件处理器
filename = '../logs' + '/' + time.strftime('%Y%m%d') + 'WebUiTestLog.log'
th = logging.handlers.TimedRotatingFileHandler(filename=filename, when='midnight', interval=1,
backupCount=30, encoding='utf-8')
# 设置日志格式
fmt = "%(asctime)s %(levelname)s [%(name)s] [filename: %(filename)s - moudle: %(module)s - func: %(funcName)s %(lineno)d line] - %(message)s"
fm = logging.Formatter(fmt)
# 将日志格式添加到处理器
ch.setFormatter(fm)
th.setFormatter(fm)
# 将处理器添加到日志器
cls.logger .addHandler(ch)
cls.logger .addHandler(th)
return cls.logger
se_utils.py 添加浏览器启动和关闭的日志
from selenium import webdriver
from utils.log_utils import GetLogger
logger = GetLogger.get_logger()
class Driver():
_driver = None
@classmethod
def get_driver(cls, browser_name='Chrome'):
if cls._driver == None:
logger.info('正在打开浏览器.....')
if browser_name == 'Chrome':
cls._driver = webdriver.Chrome()
elif browser_name == 'Firefox':
cls._driver = webdriver.Firefox()
elif browser_name == 'Safari':
cls._driver == webdriver.Safari()
elif browser_name == 'Opera':
cls._driver == webdriver.Opera()
elif browser_name == 'edge':
cls._driver == webdriver.Edge()
elif browser_name == 'Ie':
cls._driver == webdriver.Ie()
else:
raise NameError(
"Not found %s browser,You can enter 'Chrome', 'Firefox', 'Ie', 'Edge', 'Safari',Opera" % browser_name)
logger.info('打开{}浏览器'.format(cls._driver.name))
return cls._driver
@classmethod
def quit_driver(cls):
if cls._driver:
logger.info('正在关闭{}浏览器'.format(cls._driver.name))
cls._driver.quit()
logger.info('已关闭{}浏览器'.format(cls._driver.name))
cls._driver = None
base_page.py 添加定位信息的日志
def find_element(self, locator):
try:
WebDriverWait(driver=self.driver, timeout=TIMEOUT, poll_frequency=POLL_FREQUENCY).until(
EC.visibility_of_element_located(locator))
return self.driver.find_element(*locator)
except Exception as e:
msg = "元素定位超时 {}: {}".format(locator[0], locator[-1])
logger.error(msg)
raise TimeoutException(msg)