Why is pytest outputting ANSI escape characters?

306 Views Asked by At

I am getting an AssertionError when running the pytest code below. For some reason the expected message is outputting with ansi escape codes instead of outputting the text with color. I am using a Windows machine, VSCode and git bash as my terminal.

import click
from click.testing import CliRunner
from uptimer.uptimer import check

def test_check_one_url(mocker):
    mocker.patch("requests.head", return_value=mock_response_object(200))

    runner = CliRunner()
    result = runner.invoke(check, ["dummyurl"], color=True)

    expected_message = click.style("dummyurl -> 200", fg="green")
    assert result.output == f"{expected_message}\n"

Pytest provides the following output:

E       AssertionError: assert 'dummyurl -> 200\n' == '\x1b[32mdumm... 200\x1b[0m\n'
E         - dummyurl -> 200
E         ? -----               ----
E         + dummyurl -> 200

Pytest output

1

There are 1 best solutions below

0
On

I was able to hack together a solution by installing a package to strip away the ansi codes.

from click.testing import CliRunner
from uptimer.uptimer import check
from strip_ansi import strip_ansi

def test_check_one_url(mocker):
    mocker.patch("requests.head", return_value=mock_response_object(200))

    runner = CliRunner()
    result = runner.invoke(check, ["dummyurl"], color=True)

    expected_message = strip_ansi(click.style("dummyurl -> 200", fg="green"))
    assert result.output == f"{expected_message}\n"