使用’pytest’来测试日志输出是否带有颜色。

huangapple go评论52阅读模式
英文:

Use 'pytest' to test if log output is coloured

问题

Using pytest,是否可以测试日志输出是否包含特定颜色的文本?

例如,我已经配置了日志,使logging.debug()以紫色输出,因此我期望捕获的日志中包含紫色的颜色代码(\33[035m)。

但是,使用下面的示例,测试失败。请注意,在实际情况下,日志会按预期的紫色颜色打印。

是否可以实现这一点,如果可以,应该如何修改我的代码来测试颜色代码?

class TestLogging:

    def test_colour(self, caplog):
        logger = Logger('pytest', verbose=True, use_colour=True).logger
        with caplog.at_level(logging.DEBUG):
            logger.debug('Test debug colour')

        assert ('[035mDEBUG[0m') in caplog.text
英文:

Using pytest, is it possible to test that log output contains text of a certain colour?

For example, I've configured logging so that logging.debug() to output in purple, therefore I would expect the colour code for purple (\33[035m) to appear in the captured logs.

However, using the example below, the test fails. Note that in reality, the log prints with the purple colour as expected.

Is it possible to do this, and if so how can I amend my code to test for a colour code?

class TestLogging:

    def test_colour(self, caplog):
        logger = Logger('pytest', verbose=True, use_colour=True).logger
        with caplog.at_level(logging.DEBUG):
            logger.debug('Test debug colour')

        assert ('[035mDEBUG[0m') in caplog.text

答案1

得分: 0

这里有两个阻止我的事情 -

  1. 颜色代码正在从 \33[035m 更改为 \x1b[035m。由于这已经在进行,我更新了所有的颜色代码以匹配。

  2. Caplog 文本似乎以与我的日志格式不同的格式记录,并且似乎会剥离颜色代码。相反,我使用 caplog.records[0].levelname

class TestLogging:

    def test_colour(self, caplog):
        logger = Logger('pytest', verbose=True, use_colour=True).logger
        with caplog.at_level(logging.DEBUG):
            logger.debug('Test debug colour')

        level_name = caplog.records[0].levelname
        assert '\x1b[035mDEBUG\x1b[0m' in caplog.records[0].levelname
英文:

There were two things stopping me here -

  1. The colour code was being changed on the fly from \33[035m to \x1b[035m. As this was happening anyway, I updated all of my colour codes to match.

  2. Caplog text seems to log in a format that differs from my log format, and it seems to strip colour codes. Instead, I'm using caplog.records[0].levelname

class TestLogging:

    def test_colour(self, caplog):
        logger = Logger('pytest', verbose=True, use_colour=True).logger
        with caplog.at_level(logging.DEBUG):
            logger.debug('Test debug colour')

        level_name = caplog.records[0].levelname
        assert '\x1b[035mDEBUG\x1b[0m' in caplog.records[0].levelname

huangapple
  • 本文由 发表于 2023年6月12日 23:58:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76458386.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定