Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write tests for cpp functions in R package?

To speed some functions in R package, I have re-coded them in cpp functions using Rcpp and successfully embedded those cpp functions into this package. The next step is to test if the cpp functions can output the same results as the original functions in R. So writing tests is necessary.

However, I was stuck on this step. I have read some links Testing, R package by Hadley Wickham

and CRAN:testthat, page 11.

What I have done is that I run devtools::use_testthat()to create a tests/testthat directory. Then, run use_catch(dir = getwd())to add a test file tests/testthat/test-cpp.R. At this point, I think expect_cpp_tests_pass() might work but was just stuck on it. If I have the original function called add_inflow and add_inflow_Cpp. How can I test if these two functions are equal?

like image 498
Bratt Swan Avatar asked Dec 06 '16 06:12

Bratt Swan


1 Answers

The documentation for ?use_catch attempts to describe exactly how the testing infrastructure for testthat works here, so I'll just copy that as an answer:

Calling use_catch() will:

  1. Create a file src/test-runner.cpp, which ensures that the testthat package will understand how to run your package's unit tests,

  2. Create an example test file src/test-example.cpp, which showcases how you might use Catch to write a unit test, and

  3. Add a test file tests/testthat/test-cpp.R, which ensures that testthat will run your compiled tests during invocations of devtools::test() or R CMD check.

C++ unit tests can be added to C++ source files within the src/ directory of your package, with a format similar to R code tested with testthat.

When your package is compiled, unit tests alongside a harness for running these tests will be compiled into your R package, with the C entry point run_testthat_tests(). testthat will use that entry point to run your unit tests when detected.

In short, if you want to write your own C++ unit tests using Catch, you can follow the example of the auto-generated test-example.cpp file. testthat will automatically run your tests, and report failures during the regular devtools::test() process.

Note that the use of Catch is specifically for writing unit tests at the C++ level. If you want to write R test code, then Catch won't be relevant for your use case.


One package you might look at as motivation is the icd package -- see this file for one example of how you might write Catch unit tests with the testthat wrappers.

like image 80
Kevin Ushey Avatar answered Sep 23 '22 14:09

Kevin Ushey