Fix stdout/stderr redirect after tests that print to stdout and stderr

This fixes the bug introduced by the new tests in #8251, where stdout/stderr weren't restored correctly.