Python automated testing practical series 2

The first series introduces some basic configurations of Python, and the second series will introduce a point that I think is very important in coding and testing, that is log. The log can record all our traces. As the saying goes, “The passing of a swallow leaves a trace, and the passing of the wind leaves a voice.” The log can not only record bug information, but also know whether the logic of our design is correct through log analysis. Sometimes there is a situation where the developer clearly thinks so, but the output result during execution is different from what we imagined. At this time, we can debug step by step through the log to see how the code works. When running, how the results are presented to us step by step, from which we can find the root cause of the error, because sometimes it is not necessarily the code that has a problem, it may be that there is a problem with the logic we designed. At this time, use the debug function of the IDE The method is not easy to use.

The logging library in the Python standard library is Python’s logging tool. The main benefit of using the logging module recommended here is that all Python modules can participate in logging, and there are many functions that are more flexible. Official document reference address: logging — Python’s logging tool – Python 3.10.12 documentation. You can choose different versions to check. Let’s give a simple example first:

>>> import logging
>>> logging.warning('Watch out!')
WARNING:root:Watch out!

The above example is the basic usage of logging. First introduce the module, and then output the log information according to different levels. Logging logs are divided into levels, namely critical > error > warning > info > debug. There are five levels in total. The higher the level, the fewer logs will be printed, and vice versa. You can refer to the following detailed instructions:

  • debug: print all logs

  • info: Print info, warning, error, critical level logs

  • warning: print warning, error, critical level logs

  • error: print error, critical level logs

  • critical: print critical level

For example, the level in the above example is a warning level log. When the log level is set before warning, the log will be printed. By default, if the level is not set, only logs greater than or equal to the warning level will be printed.

The logging module provides two ways to record logs. The first is to use the module-level functions provided by logging, and the second is to use the four major components of logging.

Let’s first look at the module-level functions defined by Logging. Set the log level and output format through the logging.basicConfig() function, and it needs to be set at the beginning. Setting it in the middle will not work.

logging.basicConfig(filename='./log.log',level=logging.DEBUG)

In the above example, in addition to setting the level, it also defines logging to a file. A log.log file will be generated in the root directory, and log information will be recorded in it.

If there are multiple modules, you can import another module in one module and use logs to display information from another module. Simple example:

a.py module?

import logging
import b
logging.basicConfig(filename='a.log',level=logging.DEBUG)
logging.info('Welcome')
b.run()
logging.info('Done')

b.py module?

import logging
logging.info('Go')

Executing the a.py module will print the corresponding log, and the following information will be displayed in the log file a.log: ?

INFO:root:Welcome
INFO:root:Go
INFO:root:Done

In addition, the format of log display can be modified according to actual needs, such as adding date and time information. ?

import logging
logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S')
logging.warning('Warning')

Results of the:

07/20/2023 05:51:27 Warning

Let’s talk about the four major components of the logging module, Logger, Handler, Filter, and Formatter.

Logger is instantiated through the module-level function logging.getLogger(name). The creation method is:

logger = logging.getLogger(logger_name)
logger.setLevel=(logging.DEBUG)

It is recommended to add the module name of the logging module. Calling the getLogger method with the same name multiple times will return the same logger object, that is, the same log will be recorded multiple times.

There are many types of Handler processors, the commonly used ones are StreamHandler and FileHandler. You can use StreamHandler to output logs to the console, FileHandler to write to the log file, setFormatter to set the appropriate format respectively, and add the two processors to the logger instance.

file_handler = logging.FileHandler('./log.log, mode='w')
console_handler = logging.StreamHandler()
file_handler.setFormatter(
    logging.Formatter(
        fmt='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S')
)
console_handler.setFormatter(
    logging.Formatter(
        fmt='%(asctime)s - %(levelname)s: %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S')
)
logger.addHandler(file_handler)
logger.addHandler(console_handler)

Filter is relatively rarely used. Please quote the official explanation. If you are interested, you can read the documentation.

Filters can be used by Handlers and Loggers to implement more complex filtering operations than provided hierarchically. The base filter class only allows events below a certain level in the logger hierarchy. For example, a filter initialized with ‘A.B’ will allow events logged by the ‘A.B’, ‘A.B.C’, ‘A.B.C.D’, ‘A.B.D’ etc loggers. But ‘A.BB’, ‘B.A.B’ etc. are not allowed. If initialized with an empty string, all events will pass.

https://docs.python.org/zh-cn/3.10/library/logging.html#filter-objects

Formatter allows us to define the output rules, structure and content of log information ourselves. It can be set according to the actual situation. It is recommended to add the general date, module name, etc., so that we can easily understand the time and place of the event when viewing the log.

The four components are all related to each other. You can simply understand that the logger establishes an interface, the handler is used to do practical things, and the filter and formatter formulate some rules. As can be seen from the above example, the logger can contain multiple handlers, and the log levels can be set separately and inherited. For example, for the logs recorded to the log file, we can set the level to debug to record all logs, but for the output To log to the controller, you only need to output the info level, which can greatly reduce some log information that is not usually needed.

The logging module is enough for us here. There are also some log configuration-related contents that we basically don’t need to pay attention to. This issue is over. Let’s take a summer vacation and rest for a few days before continuing! Official accounts have more and more functions, try them all, GOGOGO!

Finally:The complete software testing video tutorial below has been compiled and uploaded. Friends who need it can get it by themselves[Guaranteed 100% Free]

Software Testing Interview Document

We must study to find a high-paying job. The following interview questions are from the latest interview materials from first-tier Internet companies such as Alibaba, Tencent, Byte, etc., and some Byte bosses have given authoritative answers. After finishing this set I believe everyone can find a satisfactory job based on the interview information.