Pytes正确的配置使用日志功能
redrose2100 人气:0在pytest自动化测试中,如果只是简单的从应用的角度来说,完全可以不去了解pytest中的显示信息的部分以及原理,完全可以通过使用推荐的pytest.ini配置,从而可以做到相对来说比较通用的日志配置。
这里我们推荐使用如下配置,其中log_cli 相关的四条配置是用来配置live log即实时日志的,而其他三条配置则是用例配置capture log即捕获日志的。分别对他们的日志级别、日志格式、时间戳格式进行了设置,比如这里日志级别都设置为info,当然如果脚本稳定之后,提交自动化测试代码仓库时可以将日志级别调整为warning。
[pytest] log_cli = True log_cli_level = info log_cli_format = %(asctime)s | %(levelname)s | %(filename)s:%(lineno)s | %(message)s" log_cli_date_format = %Y-%m-%d %H:%M:%S log_level = info log_format = %(asctime)s | %(levelname)s | %(filename)s:%(lineno)s | %(message)s" log_date_format = %Y-%m-%d %H:%M:%S
下面用一个简单的测试脚本来展示一下上述日志配置的效果。
import logging def test_demo(): logging.debug("this is debug log ...") logging.info("this is info log ...") logging.warning("this is warning log ...") logging.error("this is error log ...") logging.critical("this is critical log ...") assert 1==2
执行结果如下,可以看出这里显示了实时日志(live log),同时未显示debug级别的日志,捕获日志(capture log)同样也未显示debug级别的日志,而且时间戳和日志格式相对来说都是比较符合实际应用的,因此这里的推荐的pytest.ini中对日志的配置,完全可以拿去直接使用。
(demo-HCIhX0Hq) E:\demo>pytest =================== test session starts =================== platform win32 -- Python 3.7.9, pytest-7.2.0, pluggy-1.0.0 rootdir: E:\demo, configfile: pytest.ini plugins: assume-2.4.3, rerunfailures-10.2 collected 1 item test_demo.py::test_demo ---------------------- live log call ---------------------- 2022-12-06 00:42:06 | INFO | test_demo.py:5 | this is info log ..." 2022-12-06 00:42:06 | WARNING | test_demo.py:6 | this is warning log ..." 2022-12-06 00:42:06 | ERROR | test_demo.py:7 | this is error log ..." 2022-12-06 00:42:06 | CRITICAL | test_demo.py:8 | this is critical log ..." FAILED [100%] ======================== FAILURES ========================= ________________________ test_demo ________________________ def test_demo(): logging.debug("this is debug log ...") logging.info("this is info log ...") logging.warning("this is warning log ...") logging.error("this is error log ...") logging.critical("this is critical log ...") > assert 1==2 E assert 1 == 2 test_demo.py:9: AssertionError -------------------- Captured log call -------------------- 2022-12-06 00:42:06 | INFO | test_demo.py:5 | this is info log ..." 2022-12-06 00:42:06 | WARNING | test_demo.py:6 | this is warning log ..." 2022-12-06 00:42:06 | ERROR | test_demo.py:7 | this is error log ..." 2022-12-06 00:42:06 | CRITICAL | test_demo.py:8 | this is critical log ..." ================= short test summary info ================= FAILED test_demo.py::test_demo - assert 1 == 2 ==================== 1 failed in 0.07s ==================== (demo-HCIhX0Hq) E:\demo>
加载全部内容