Custom logs and encapsulation of Python automated testing

preface:

In the daily work of software testing, log is a very important module
For testing, the main functions of logs are as follows:
1. Commissioning procedure
2. Know whether the system program runs normally
3. Fault analysis and problem location of the system in the west of the city
4. It is used for user behavior analysis and data statistics

Therefore, when writing automated test scripts and building automated test frameworks, it is best to add the log collection function to locate problems through logs.

text

Related concepts

Before customizing the log, we need to know the following information:

  1. Log collector
    It can be understood as a container for collecting log information;
  2. Log level:
    The common log levels are: debug, info, warning, error and critical
  3. Output channel (Handle):
    Console output: StreamHandle
    Save log information in a file: FileHandle
  4. Log format:
    Generally, it includes the following information: log time - log name - log level name - file name - line number - log information, etc

Examples

1 # 4. Set the output format of the log
2 fmt = "%(asctime)s %(name)s %(levelname)s %(filename)s-%(lineno)d:%(message)s"
3 formatter = logging.Formatter(fmt)

In the python logging module, the default is the root log collector, and the default output level is WARNING

User defined log operation process

  1. Import logging module: import logging
  2. Create a log collector: logger = logging Getlogger ("name of log collector")
  3. Set the log level of the log collector: logger Setlevel (logging. INFO) # sets the level of the collector to INFO
  4. Create an output channel for the log collector (according to the content in the first part: the log output channel includes console output and file output): take console output as an example, and file output is similar
    4.1 create log output channel: handle1 = logging StreamHandle()
    4.2 the level of log output channel can be set separately: handle1 Setlevel (logging. Error) this step is optional
    [special instructions]
    4.3 when the log Level of the log output channel is not set, the Level set by the log collector is used by default
    4.4 if the log level of the log output channel needs to be set separately, its log level must be higher than the log collector level, otherwise the setting is invalid.
  5. Set the content format of log output
1 # Set the output format of the log
2 fmt = "%(asctime)s %(name)s %(levelname)s %(filename)s-%(lineno)d:%(message)s"
3 formatter = logging.Formatter(fmt)
  1. Bind the set log format to the created output channel, that is, associate the log format with the output channel
handler1.setFormatter(formatter)
  1. Add the set output channel to the log collector
logger.addHandler(handler1)

The operation flow of outputting log information to a file is similar, except for a little difference in step4

handler2 = logging.FileHandler(filename="xxx.log",encoding="utf-8")

Log code reference

import logging

# 1. Create log collector
logger = logging.getLogger(name="login_test")

# 2. Set the level of the log collector: warning level
logger.setLevel(logging.WARN)

# 3. Set the output channel of the log
# 3.1 console log output
handler1 = logging.StreamHandler()
# 3.2 file log output
handler2 = logging.FileHandler(filename="my_log.log",encoding="utf-8")
# Set the log level of the output channel separately
handler1.setLevel(logging.ERROR)    # Optional

# 4. Set the output format of the log
fmt = "%(asctime)s %(name)s %(levelname)s %(filename)s-%(lineno)d:%(message)s"
formatter = logging.Formatter(fmt)

# 5. Correlation 3 and 4
handler1.setFormatter(formatter)
handler2.setFormatter(formatter)

# 6. Correlation 1 and 5
logger.addHandler(handler1)
logger.addHandler(handler2)

# test
logger.warning("Login failure warning")
logger.error("Sign in debug error")

Encapsulation of custom logs

Since the operation process of custom logs is relatively fixed, we can encapsulate custom logs into a class. When we need to use it, we just need to introduce this module.

  1. By checking the source code, we know that the encapsulated class needs to inherit logging Logger class, so you can inherit the functions of the parent class, such as debug(), info();
  2. From the operation flow in the second part, different users may set different log names, log levels and log file information when introducing the module. Therefore, these parameters can enable users to initialize settings when instantiating log objects;
  3. When we need the first mock exam class, we can use this module.

Code reference

import logging

# Encapsulate log operations
class MyLogger(logging.Logger):

    def __init__(self,name,level,file=None):
        super().__init__(name,level)
        # Set the output channel of the log
        handler1 = logging.StreamHandler()
        # Set the output format of the log
        fmt = "%(asctime)s %(name)s %(levelname)s %(filename)s-%(lineno)d:%(message)s"
        formatter = logging.Formatter(fmt)
        handler1.setFormatter(formatter)
        # Add the output channel of the log
        self.addHandler(handler1)

        if file:
            handler2 = logging.FileHandler(filename=file,encoding="utf-8")
            handler2.setFormatter(formatter)
            self.addHandler(handler2)
            pass
        pass
    pass

Later words

The above is a simple user-defined log and its sub packaging. If it is helpful to you, I hope I can give you a little praise. In the future, I will continue to update more automatic testing and learning technologies and methods

The above is some videos and interview questions I collected, which should be the most comprehensive and complete interview preparation warehouse for software testing friends

In order to better organize each module, I also refer to many high-quality online blogs and projects, and strive not to miss every knowledge point. Many friends review with these contents and get offer s from big manufacturers such as BATJ. This warehouse has also helped many learners of software testing. I hope it can also help you

WeChat rookie official account is required to test the hard core resources of software testing. it's fine too click here Enter group chat to receive

In short, learning is like sailing against the current. If you don't advance, you will fall back. How much salary you want, how much effort you have to make.

Keywords: Python software testing Testing

Added by codrgii on Wed, 09 Feb 2022 09:26:46 +0200