Python Automated Test Series [v1.0.0] [Log]

In the actual automated test code debugging process, we often need to record some logs. On the one hand, it is printed to the console for us to debug the code. If it is an unattended environment of continuous integration, it is also a recording process of the test execution process.

Method encapsulation

Create a new Python file and name it ConstantConfig, then write the following code in the file.

# 用于定义整个框架中所需要的全局常量值
# encoding = utf-8
import os
# 获取当前文件所在目录的父目录的绝对路径
parent_directory_path = os.path.abspath('..')
print(parent_directory_path)
# encoding = utf-8
import time
import logging
from Configuration.ConstantConfig import parent_directory_path
class Logger(object):
    def __init__(self, logger):
        """
        指定保存日志的文件路径,日志级别,以及调用文件
            将日志存入到指定的文件中
        :param logger:
        """
        # 创建一个logger
        self.logger = logging.getLogger(logger)
        self.logger.setLevel(logging.DEBUG)
        # 创建一个handler,用于写入日志文件
        rq = time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime(time.time()))
        log_path = parent_directory_path + '/TestResult/TestLog/'
        log_name = log_path + rq + '.log'
        filehandler = logging.FileHandler(log_name)
        filehandler.setLevel(logging.INFO)
        # 再创建一个handler,用于输出到控制台
        consolehandler = logging.StreamHandler()
        consolehandler.setLevel(logging.INFO)
        # 定义handler的输出格式
        formatter = logging.Formatter('%(asctime)s-%(name)s-%(levelname)s-%(message)s')
        filehandler.setFormatter(formatter)
        consolehandler.setFormatter(formatter)
        # 给logger添加handler
        self.logger.addHandler(filehandler)
        self.logger.addHandler(consolehandler)
    def getlog(self):
        return self.logger

Create a new folder named TestLog to store the generated log file
Insert picture description here

Method call

testlogger = GetLog.Logger('Test_Advanced_Application').getlog()
class Test_Advanced_Application(unittest.TestCase): 
	def test_get_log(self):
    	testlogger.info("打开浏览器")
    	driver = webdriver.Chrome()
    	driver.maximize_window()
    	testlogger.info("最大化浏览器窗口。")
    	driver.implicitly_wait(10)
    	testlogger.info("打开百度首页。")
    	driver.get("https://www.baidu.com")
    	testlogger.info("暂停3秒。")
    	time.sleep(3)
    	testlogger.info("关闭并退出浏览器")
    	driver.quit()
    	with self.assertLogs(testlogger, level=20) as log:
        	testlogger.error("打开浏览器")
        	testlogger.info('关闭并退出浏览器')
        	self.assertEqual(log.output,
            	             ['ERROR:Test_Advanced_Application:打开浏览器',
                	          'INFO:Test_Advanced_Application:关闭并退出浏览器']
                    	     )

Results of the

Insert picture description here
You can see the process of printing our logs to the console one by one during the execution process,
Insert picture description here
and then go to the TestLog folder we created to view the log files. If you encounter garbled characters, as shown in Figure 11.13, do n’t panic because the encoding does not match As a result, click Reload in 'GBK' to convert the encoding format to GBK and it will display normally
Insert picture description here
Insert picture description here
. The reason for the garbled code is that File Encodings in the project settings, Global Encoding is UTF-8
Insert picture description here

Published 231 original articles · praised 188 · 120,000 views

Guess you like

Origin blog.csdn.net/dawei_yang000000/article/details/105648317