Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the type hint for the pytest fixture "capsys"?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading