I am writing tests for an R function that imports an xml file, settings.xml
.
Currently, when I write a test for functions that depend on the contents of foo.xml
, including the function read.settings
in the following example:
writeLines("<fee><fi><\fi>\fee>", con = "/tmp/foo.xml")
settings <- read.settings("/tmp/foo.xml")
file.remove("/tmp/foo.xml")
But a number of issues have come up related to making the test system-independent. For example, /tmp/
may not be writeable or an error in read.settings()
leaves an orphaned file in the test directory, etc. This is a trivial example and I can think of ways around these issues, but I recall such a solution in an answer to a previous question, which I now can not find, in which the con
is not a file but an object in memory. I am sure that there are many situations in which it would be useful not to actually write a file.
?connections
appears to be a good lead, but it is not clear to me how to use the information providedAs follow up (but not to be too open-ended)
Here's a construct that might be helpful. tempfile()
returns a valid name for a temporary file on any operating system, and the call to on.exit(unlink())
ensures that the temporary file gets removed, no matter what else happens.
test1 <- function() {
temp <- tempfile()
on.exit(unlink(temp))
writeLines("<fee><fi><\fi>\fee>", con = temp)
settings <- readLines(temp)
settings
}
test1()
# [1] "<fee><fi><\fi>\fee>"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With