Here is a full test example:
thon
from transformers.testing_utils import CaptureStdout
msg = "Secret message\r"
final = "Hello World"
with CaptureStdout() as cs:
    print(msg + final)
assert cs.out == final + "\n", f"captured: {cs.out}, expecting {final}"

If you'd like to capture stderr use the CaptureStderr class instead:
thon
from transformers.testing_utils import CaptureStderr
with CaptureStderr() as cs:
    function_that_writes_to_stderr()
print(cs.err)