When writing pytest tests for a function that is supposed to print something to the console, to verify the output string I am using the capsys
fixture and capsys.readouterr()
.
This is the code I am currently using:
@pytest.mark.parametrize(
"values,expected",
[
([], "guessed so far: \n"),
(["single one"], "guessed so far: single one\n"),
(["one", "two", "three", "4"], "guessed so far: 4, three, two, one\n"),
],
)
def test_print_guesses(capsys, values: list, expected: str) -> None:
hm.print_guesses(values)
assert capsys.readouterr().out == expected
I am also using the mypy extension in VS Code, so for now I am getting the warning:
Function is missing a type annotation for one or more arguments
I'd like to get rid of that. What is the appropriate type annotation for the capsys
argument?
Per the documentation for capsys
, it:
Returns an instance of
CaptureFixture[str]
.
This class indeed has a readouterr
method (returning a CaptureResult
, which has an out
attribute). So your test should look like:
@pytest.mark.parametrize(
# ...
)
def test_print_guesses(capsys: pytest.CaptureFixture[str], values: list, expected: str) -> None:
hm.print_guesses(values)
assert capsys.readouterr().out == expected