1

Is it possible to change the capturing behavior in pytest for just one test — i.e., within the test script?

I have a bunch of tests that I use with pytest. There are several useful quantities that I like to print during some tests, so I use the -s flag to show them in the pytest output. But I also test for warnings, which also get printed, and look ugly and distracting. I've tried using the warnings.simplefilter as usual to just not show the warnings, but that doesn't seem to do anything. (Maybe pytest hacks it???) Anyway, I'd like some way to quiet the warnings but still check that they are raised, while also being able to see the captured output from my other print statements. Is there any way to do this — e.g., by change the capture for just one test function?

2 Answers 2

2

With pytest 3.x there is an easy way to temporarily disable capturing (see the section about capsys.disabled().

There's also the pytest-warnings plugin which shows the warning in a dedicated report section.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for pointing those out; they both look great. I tried installing from github, but it says capsys has no disabled attribute. Must be pretty bleeding-edge! :)
The master branch is for stable releases, so to see what's upcoming in 3.0 (a lot!) you'll need to use the features branch.
Ah, I see. Thank you.
1

I've done it by manually redirecting stderr:

import os import sys import warnings import pytest def test(): stderr = sys.stderr sys.stderr = open(os.devnull, 'w') with pytest.warns(UserWarning): warnings.warn("Warning!", UserWarning) sys.stderr = stderr 

For good measure, I could similarly redirect stdout to devnull, if other print statements are not wanted.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.