Is there a way to configure Python logging to log content or context of assert failures?

非 Y 不嫁゛ 提交于 2019-12-02 00:06:33
self.assertIn('Edit your profile admin', rv.data, msg=rv.data)

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.)

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

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

You can do something like this:

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: Was pointed out that this takes the assert functionality away basically, since the assertion is handled by the except block. Suggestions welcome.

Edit: This would work, but is pretty sloppy.

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

Consider replacing assert with a non-throwing check:

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) + "\"")

will print:

ERROR [TestCase.py:320 - test_edit_profile] profile: "View your profile admin"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!