Python日志记录模块:如果(仅)断言测试失败,如何将日志保存到文件? [英] Python logging module: how to save log to a file if (and only if) assertion test fails?

查看:674
本文介绍了Python日志记录模块:如果(仅)断言测试失败,如何将日志保存到文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种优雅且 Pythonic 的解决方案,以使测试将日志保存到文件中,尽管仅在测试失败的情况下 .我想保持简单,并坚持使用Python内置的 logging 模块.

我当前的解决方案是对每个测试使用断言包装函数:

 import unittest

class superTestCase(unittest.TestCase): 
    ...

    def assertWithLogging(self, assertion, assertion_arguments, expected_response, actual_response, *args):
        try:
            assertion(*assertion_arguments)
        except AssertionError as ae:
            test_name = inspect.stack()[1][3]
            current_date_time = datetime.datetime.now().strftime("%Y.%m.%d %H-%M-%S")
            logging.basicConfig(filename='tests/{}-{}-Failure.log'.format(current_date_time, test_name),
                                filemode='a',
                                format='%(message)s',
                                level=logging.DEBUG
                                )
            logger = logging.getLogger('FailureLogger')
            logger.debug('{} has failed'.format(test_name))
            logger.debug('Expected response(s):')
            logger.debug(expected_response)
            logger.debug('Actual response:')
            logger.debug(actual_response)
            for arg in args:
                logger.debug('Additionl logging info:')
                logger.debug(arg)
            raise ae

    def testSomething(self):
        ...

        self.assertWithLogging(self.assertEqual,
                               [expected_response, actual_response]
                               expected_response,
                               actual_response,
                               some_other_variable
                               )
 

尽管它能按我预期的那样工作,但对我来说,这种解决方案似乎笨拙而不是 Pythonic .

  1. 实现相同结果的一种更优雅的方法是(在那里)?
  2. 当前方法的弊端是什么?

解决方案

您可以使用各种日志记录机制,在其中可以设置要实现的日志类型.

下面的一个将仅记录错误消息.

Logger.error(msg, *args, **kwargs)

这会将msg记录为级别 logging.ERROR这个记录器.参数的解释方式与 debug() 相同.

I am looking for an elegant and Pythonic solution, to make tests save a log to a file, though only in case of test failure. I would like to keep things simple, and stick with Python's built-in logging module.

My current solution is to use a wrapper function for assert of every test:

import unittest

class superTestCase(unittest.TestCase): 
    ...

    def assertWithLogging(self, assertion, assertion_arguments, expected_response, actual_response, *args):
        try:
            assertion(*assertion_arguments)
        except AssertionError as ae:
            test_name = inspect.stack()[1][3]
            current_date_time = datetime.datetime.now().strftime("%Y.%m.%d %H-%M-%S")
            logging.basicConfig(filename='tests/{}-{}-Failure.log'.format(current_date_time, test_name),
                                filemode='a',
                                format='%(message)s',
                                level=logging.DEBUG
                                )
            logger = logging.getLogger('FailureLogger')
            logger.debug('{} has failed'.format(test_name))
            logger.debug('Expected response(s):')
            logger.debug(expected_response)
            logger.debug('Actual response:')
            logger.debug(actual_response)
            for arg in args:
                logger.debug('Additionl logging info:')
                logger.debug(arg)
            raise ae

    def testSomething(self):
        ...

        self.assertWithLogging(self.assertEqual,
                               [expected_response, actual_response]
                               expected_response,
                               actual_response,
                               some_other_variable
                               )

Though it works as I expect it to, this solution seems clumsy and not too Pythonic, to me.

  1. What would be (Is there) a more elegant way to achieve the same result?
  2. What are the downsides of current approach?

解决方案

You can use various logging mechanisms where in you can set the type of logs you want to achieve.

The one below will log only error messages.

Logger.error(msg, *args, **kwargs)

This logs msg with level logging.ERROR on this logger. The arguments are interpreted as for debug().

这篇关于Python日志记录模块:如果(仅)断言测试失败,如何将日志保存到文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆