有没有办法将Python日志配置为记录断言失败的内容或上下文?

有没有办法将Python日志配置为记录断言失败的内容或上下文?,python,testing,logging,flask,assertions,Python,Testing,Logging,Flask,Assertions,我正在运行测试用例,我希望设置一个my logging,这样它可以自动记录测试失败的所有用例——但我希望得到一个自定义响应,例如,如果断言失败,我希望得到对测试请求的响应,而不仅仅是断言失败的默认消息。目前我只知道断言失败了,但我不知道程序返回了什么 假设我正在测试一个视图函数,例如,我有一个测试看起来大致像这样(整个TestCase类的一部分) 我是否有办法配置日志记录,使每次测试失败都能将rv.data记录到日志文件中 目前,我只是在先前测试中失败的断言之前添加logging.debug(r

我正在运行测试用例,我希望设置一个my logging,这样它可以自动记录测试失败的所有用例——但我希望得到一个自定义响应,例如,如果断言失败,我希望得到对测试请求的响应,而不仅仅是断言失败的默认消息。目前我只知道断言失败了,但我不知道程序返回了什么

假设我正在测试一个视图函数,例如,我有一个测试看起来大致像这样(整个TestCase类的一部分)

我是否有办法配置日志记录,使每次测试失败都能将rv.data记录到日志文件中


目前,我只是在先前测试中失败的断言之前添加logging.debug(rv.data),再次运行测试,调试问题,然后继续,但这是无效的,以后很容易忘记那些logging.debug(),如果我有一个功能,可以在测试请求失败时自动记录我的网页响应,速度会快得多。

您可以这样做:

def test_edit_profile(self):
    rv = self.edit_profile()
    try:
        assert "Edit your profile admin" in rv.data
    except AssertionError:
        # Do your logging here
Edit:有人指出,这从根本上消除了断言功能,因为断言是由except块处理的。欢迎提出建议

编辑:这会有用,但相当草率

def test_edit_profile(self):
    rv = self.edit_profile()
    try:
        assert "Edit your profile admin" in rv.data
    except AssertionError:
        assert "Edit your profile admin" in rv.data
        # Do your logging here
使用
assertwhich
方法。我不完全理解为什么,但是您不应该在
unittest
中使用
assert
语句进行断言。(其他框架允许您使用
assert
进行断言)

作为参考,将消息添加到
assert
断言的工作方式如下:

assert 'Edit your profile admin' in rv.data, rv.data

考虑将断言替换为非抛出检查:

def log_assert(arg=None):
    caller = inspect.stack()[1]
    if arg is None:
        with open(caller[1], "r") as source_code:
            for n, line in enumerate(source_code):
                if n >= caller[2] - 1:
                    arg = line.strip
                break
    logger.error("[%s:%d - %s] %s" % (basename(caller[1]), caller[2], caller[3], arg))

...

"Edit your profile admin" in rv.data or log_assert("profile: \"" + str(rv.data) + "\"")
将打印:

ERROR [TestCase.py:320 - test_edit_profile] profile: "View your profile admin"

好的,这听起来很有趣,但是我不会让控制台的输出失败,对吗?失败将被包装在try中,除了block,如果我不查看日志,我就不会知道失败了?噢,该死,我没想到。。你说得对。那么一定有更好的方法。你可以使用双参数
assert
或使用
raise
重新调用异常,但无论如何,你不应该在
unittest
测试用例中使用
assert
。是的,我正在考虑再次断言它/在except块中引发错误的选项。
def log_assert(arg=None):
    caller = inspect.stack()[1]
    if arg is None:
        with open(caller[1], "r") as source_code:
            for n, line in enumerate(source_code):
                if n >= caller[2] - 1:
                    arg = line.strip
                break
    logger.error("[%s:%d - %s] %s" % (basename(caller[1]), caller[2], caller[3], arg))

...

"Edit your profile admin" in rv.data or log_assert("profile: \"" + str(rv.data) + "\"")
ERROR [TestCase.py:320 - test_edit_profile] profile: "View your profile admin"