1

I want to run doc-tests and get the number of failures, but not print any output. For example, I tried this:

    with open(os.devnull, 'w') as sys.stdout:
        tests_failed, tests_run = doctest.testmod(some_module,
                                                  optionflags=doctest.ELLIPSIS)

but this does not play nice with the test runner suite, which requires sys.stdout to write to a JSON file.

How can I run doc-tests without printing any output?

3
  • 1
    I've posted an answer I think will help, but I have one nagging question I'm not sure about: when you say the test suite requires sys.stdout to write to a JSON file, do you need that JSON file to also include the results of these doctest runs? If not, my solution should work for you. If so, please clarify what you need.
    – joanis
    Commented Nov 7 at 2:19
  • 1
    If only part of your test suite runner needs to go to that JSON file, you could use redirect_stdout to write that file out as well, since it also accepts a file opened with open(). Then you wouldn't have restrictions about stdout elsewhere in your test suite.
    – joanis
    Commented Nov 7 at 2:22
  • No, I don't need the file to include the results of those doc-test runs, and your solution works, thank you!
    – emonigma
    Commented Nov 10 at 13:44

1 Answer 1

1

To capture (and thus silence) stdout, I use contextlib.redirect_stdout:

import io
import contextlib

[...]
    
    # in function running tests:
    f = io.StringIO()
    with contextlib.redirect_stdout(f):
       # run code that outputs stuff to stdout

    # stdout contents are now in f.get_value(), which you can use 
    # for further assertions, to output to a file, etc.

I did some experiments, to make sure this plays nice with doctest, and it seems to:

>>> f = io.StringIO()
>>> with contextlib.redirect_stdout(f):
...     doctest.testmod(my_project.utils)
...
>>> f.getvalue()
'TestResults(failed=0, attempted=10)\n'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.