Skip to main content
 首页 » 编程设计

python之python 测试期间忽略的颜色序列

2024年11月24日14kerrycode

相关: timofurrer/colorful#23


我正在重新实现 pure prompt in python所以它可以支持更多的外壳。

但是,在测试颜色时,我得到了“未执行的”行为,即我不理解的行为。

测试输出

    def test_prompt_symbol_is_colored_for_successful_command(): 
        assert str(prompt.prompt_symbol()) == str(colors.primary('❯')) 
>       assert str(prompt.prompt_symbol()) == '\x1b[38;2;155;48;255m❯\x1b[39m' 
E       AssertionError: assert '❯' == '\x1b[38;2;155;48;255m❯\x1b[39m' 
E         - ❯ 
E         + ❯   ← this one is purple 

_colors_test.py_

def test_prompt_symbol_is_colored_for_successful_command(): 
    assert str(prompt.prompt_symbol()) == str(colors.primary('❯')) 
    assert str(prompt.prompt_symbol()) == '\x1b[38;2;155;48;255m❯\x1b[39m' 

我运行测试:

pytest -v tests/ 

颜色.py

import colorful 
 
primary = colorful.purple1 
mute = colorful.gray 

提示.py

from pure import colors 
 
def prompt_symbol(last_command_status=0): 
    symbol = colors.primary('❯') if last_command_status == 0 else colors.danger('❯') 
    return symbol 

问题

第一个断言成功,而第二个断言失败,尽管它们应该是等价的。当我否定第一个断言时,转义序列不存在:

>       assert str(prompt.prompt_symbol()) != str(colors.primary('❯')) 
E       AssertionError: assert '❯' != '❯' 
E        +  where '❯' = str(<colorful.core.ColorfulString object at 0x7f545276f080>) 
E        +    where <colorful.core.ColorfulString object at 0x7f545276f080> = <function prompt_symbol at 0x7f54527b79d8>() 
E        +      where <function prompt_symbol at 0x7f54527b79d8> = prompt.prompt_symbol 
E        +  and   '❯' = str(<colorful.core.ColorfulString object at 0x7f545276f0b8>) 
E        +    where <colorful.core.ColorfulString object at 0x7f545276f0b8> = <colorful.core.Colorful.ColorfulStyle object at 0x7f54527c2278>('❯') 
E        +      where <colorful.core.Colorful.ColorfulStyle object at 0x7f54527c2278> = colors.primary 

在 python REPL 中手动执行命令给我:

>>> from pure import colors, prompt  
>>> str(colors.primary('❯')) 
'\x1b[38;2;155;48;255m❯\x1b[39m' 
>>> str(prompt.prompt_symbol()) 
'\x1b[38;2;155;48;255m❯\x1b[39m' 

请您参考如下方法:

修复了 --capture=no (or -s) flag from pytest :

pytest -v --capture=no tests/ 

有关详细信息,请参阅 https://github.com/timofurrer/colorful/issues/23#issuecomment-468008070 .