有没有办法配置 Python 日志记录来记录断言失败的内容或上下文? [英] Is there a way to configure Python logging to log content or context of assert failures?

查看:26
本文介绍了有没有办法配置 Python 日志记录来记录断言失败的内容或上下文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行测试用例,我想设置我的日志记录,以便它自动记录测试失败的所有情况 - 但我想获得自定义响应,例如,如果断言失败 我想得到对我的测试提出的请求的响应,而不仅仅是断言失败的默认消息.目前只知道断言失败,不知道程序返回了什么.

I'm running test cases and I'd like to set up a my logging in such a way that it automatically logs all cases where tests fails - but I'd like to get a custom response, for example if an assertion fails I'd like to get the response to a request made by my test, not just default message which assertion failed. At present I only know that the assertion failed, but I don't know what the program returned.

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

So say I'm testing a view function, for example I have a test which looks roughly likes this (part of whole TestCase class)

def edit_profile(self):
    return self.app.get("/edit_profile", follow_redirects=True)

def test_edit_profile(self):
    rv = self.edit_profile()
    assert "Edit your profile admin" in rv.data

有没有办法让我配置日志记录,每次测试失败都会将 rv.data 记录到日志文件中?

Is there a way for me to configure logging in such a way that each test failure will log rv.data to a logs file?

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

Currently I simply add logging.debug(rv.data) before the assertion that failed in previous tests, run the test again, debug the issue, and go on, but this is ineffective, it's easy to forget about those loggging.debug() later on, and it would be much faster if I had an function to automatically log my webpage response to test requests if they fail.

推荐答案

self.assertIn('Edit your profile admin', rv.data, msg=rv.data)

使用 assertWhatever 方法.我不完全理解为什么,但是您不应该在 unittest 中使用 assert 语句进行断言.(其他框架允许您使用 assert 进行断言.)

Use the assertWhatever methods. I don't fully understand why, but you're not supposed to use assert statements for assertions in unittest. (Other frameworks let you assert with assert.)

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

For reference, adding a message to an assert assertion works as follows:

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

这篇关于有没有办法配置 Python 日志记录来记录断言失败的内容或上下文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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