2

Within an R package I wrote a function that redirects all output from a sourced script to a log file using

sink(file = "some.log", type = "output")
sink(file = "some.log", type = "message")
source("script.R")

within the function. Now I want to test if this function works as expected which means that I need to test if certain output (including messages) was written to the specified log file.

This works fine when I run the test script in the console. But when I use devtools::test() or R CMD check, the messages are captured somewhere else and don't appear in the log file.

I understand that this behavior is somehow necessary for testthat to work, but how can I test if my function call produced all expected messages?

der_grund
  • 1,898
  • 20
  • 36
  • An R package should not use `source`. – Roland Oct 28 '20 at 08:48
  • But I need a function which sources a script file (the path of the script file is not hardcoded, of course!) and logs all input and output. What would be the "correct" / best practice solution to this if I should not use `source`? – der_grund Oct 28 '20 at 08:56
  • if you are creating a package, then you can call other functions within your package without the need of source. – Moh Oct 28 '20 at 08:59
  • @Moh, I know. But I need a function so that users of my package can easily source their scripts and log everything which happend in there. – der_grund Oct 28 '20 at 09:05
  • Is this some kind of utility package to support users who use `source`? – Roland Oct 28 '20 at 09:14
  • @Roland: Yes, that's one thing the package does. It also provides functions which the users should use in their scripts (which they then `source`) and print specific messages to the log file. – der_grund Oct 28 '20 at 09:29
  • I don't think this is a good approach but good luck. – Roland Oct 28 '20 at 10:01
  • I'm open to better approaches if you have any. – der_grund Oct 28 '20 at 10:05

1 Answers1

1

I think the best option is to leave it up to end-users to call sink() rather than include it as a function in your package. You can provide examples in a vignette to show users how you intend them to use sink() with their scripts.

Edit: you might find this vignette on test fixtures helpful, especially the case study on usethis: https://testthat.r-lib.org/articles/test-fixtures.html#case-study-usethis