Print outputs to console during a testthat test

Viewed 61

I'm trying to use the testthat package in R to test a script. Within my script, I have several cat statements that print things to the console. However, when I run my test, nothing prints out.

I tried adding an arbitrary print statement above one of the cat statements, and the print statement worked, so I changed my main cat statement to a print statement, which also worked. However, the output of print is ugly, so I'd like to be able to keep a cat statement there that I can see whenever I run the test, rather than having to manually change it to a print statement every time.

Adding to the mystery, I tried changing the arbitrary print statement to be a cat statement, and it printed to the console -- but when I changed the main statement back to cat, it no longer printed.

What is going on??

Summary of the code:

Nothing prints to the console:

cat(sprintf('\n\nCalculating regressions for site %s', site)))

This prints 'hello world', but not the 'calculating regressions for...':

print('hello world')
cat(sprintf('\n\nCalculating regressions for site %s', site)))

This does print both, but the formatting for the second statement doesn't treat newlines as newlines, just as strings:

print('hello world')
print(sprintf('\n\nCalculating regressions for site %s', site)))

This also prints 'hello world', but not the 'calculating regressions for...':

cat('hello world')
cat(sprintf('\n\nCalculating regressions for site %s', site)))

EDIT: Clarifying that the above code is in the script that's being tested, not the testthat script.

0 Answers
Related