英文:
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
这里有两个阻止我的事情 -
-
颜色代码正在从
\33[035m
更改为\x1b[035m
。由于这已经在进行,我更新了所有的颜色代码以匹配。 -
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 -
-
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. -
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论