4

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

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

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 记录到日志文件中?

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

4

3 回答 3

2

你可以这样做:

def test_edit_profile(self):
    rv = self.edit_profile()
    try:
        assert "Edit your profile admin" in rv.data
    except AssertionError:
        # Do your logging here

编辑:有人指出,这基本上取消了断言功能,因为断言是由 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
于 2013-08-06T19:34:15.370 回答
2
self.assertIn('Edit your profile admin', rv.data, msg=rv.data)

使用assertWhatever方法。我不完全理解为什么,但你不应该assertunittest. (其他框架让你断言assert。)

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

assert 'Edit your profile admin' in rv.data, rv.data
于 2013-08-06T19:39:44.990 回答
0

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

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"
于 2019-09-25T09:44:50.940 回答