When the expected result of a test is relatively complex (in the case of the package I'm currently working on, a numeric array), it can be awkward to write it as a literal within an expect_that call. It would be convenient to store such results in a file instead and have an expectation that checks against that file. To avoid code duplication, it would also be helpful if that same test code would be used to create the file if it doesn't yet exist.
I knocked up the following as a proof of principle.
matches_file <- function (file, compare = equals, label = NULL, ...)
{
if (file.exists(file)) {
reference <- readRDS(file)
compare <- match.fun(compare)
if (is.null(label))
label <- paste("reference from", file)
compare(reference, label=label, ...)
} else {
return (function(actual) {
saveRDS(actual, file)
expectation(TRUE, "should never fail", "saved to file")
})
}
}
This is then called like
expect_that(shapeKernel(c(5,5),type="box"), matches_file("box_kernel.rds"))
I'm happy to put this, or a modification, in a pull request if it would be helpful. The only issue I can see with this as it stands is that you need to check by hand what goes into the files the first time. Once that's verified then the tests will ensure the correct result on future runs. Comments?
When the expected result of a test is relatively complex (in the case of the package I'm currently working on, a numeric array), it can be awkward to write it as a literal within an
expect_thatcall. It would be convenient to store such results in a file instead and have an expectation that checks against that file. To avoid code duplication, it would also be helpful if that same test code would be used to create the file if it doesn't yet exist.I knocked up the following as a proof of principle.
This is then called like
I'm happy to put this, or a modification, in a pull request if it would be helpful. The only issue I can see with this as it stands is that you need to check by hand what goes into the files the first time. Once that's verified then the tests will ensure the correct result on future runs. Comments?