如何为 R 包中的 cpp 函数编写测试?

How to write tests for cpp functions in R package?

为了加速 R 包中的一些函数,我使用 Rcpp 将它们重新编码为 cpp 函数,并成功地将这些 cpp 函数嵌入到这个包中。下一步是测试 cpp 函数是否可以输出与 R 中原始函数相同的结果。因此编写测试是必要的。

然而,我卡在了这一步。我已经阅读了一些链接 Testing, R package by Hadley Wickham

CRAN:testthat, page 11

我所做的是 运行 devtools::use_testthat() 创建一个 tests/testthat 目录。然后,运行use_catch(dir = getwd())添加测试文件tests/testthat/test-cpp.R。在这一点上,我认为 expect_cpp_tests_pass() 可能会起作用,但只是停留在它上面。如果我的原始函数名为 add_inflowadd_inflow_Cpp。如何测试这两个函数是否相等?

?use_catch 的文档试图在此处准确描述 testthat 的测试基础结构如何工作,因此我将复制它作为答案:

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.

简而言之,如果您想使用Catch 编写自己的C++ 单元测试,您可以按照自动生成的test-example.cpp 文件的示例进行操作。 testthat 将自动 运行 您的测试,并在常规 devtools::test() 过程中报告失败。

请注意,Catch 的使用专门用于在 C++ 级别编写单元测试。如果您想编写 R 测试代码,那么 Catch 将与您的用例无关。


一个您可能会认为是动机的包是 icd package -- see this file 的一个示例,说明您如何使用 testthat 包装器编写 Catch 单元测试。