Rcpp with testthat and catch unit testing

Page content

The issue

System

This has been tested with R version 3.5.3 in RStudio 1.2.1335, using the following packages:

  • usethis: 1.5.0
  • testthat: 2.0.1
  • Rcpp: 1.0.1
  • devtools: 2.0.2

Apparantly, in R version 3.2.x this approach would not work, with a reference to

RcppExport SEXP run_testthat_tests();

not being created in RcppExports.cpp

Setting up

> library(usethis)
> create_package("~/test/mypackage")
...
> roxygen2::roxygenize()
> library(usethis)
> use_rcpp()
> use_mit_license("my name")

Create a mypackage-package.R file with the following contents:

## usethis namespace: start
#' @useDynLib mypackage, .registration = TRUE
#' @importFrom Rcpp sourceCpp
## usethis namespace: end
NULL

Prepare for testing:

> use_test()

Let’s create a source file, timesTwocpp:


We need to tell R that we have to link against testthat. Add , testthat to the DESCRIPTION file, such that it contains:

LinkingTo:
    Rcpp, testthat

Add a file to create a Catch C++ testrunner in the tests/testthat directory:

$ cat src/test-runner.cpp
#define TESTTHAT_TEST_RUNNER
#include <testthat.h>

and create a test for testthat that pushes the C++ testing:

$ cat tests/testthat/test-cpp.R
context("Catch: C++ unit tests")
test_that("Catch unit tests pass", {
    expect_cpp_tests_pass("auction")
})

We test the setup:

~/test $ R CMD build mypackage
~/test $ R CMD check mypackage_0.0.0.9000.tar.gz
...
 OK

Makevars

At some point R introduced new checks for compile flags. When compiling code in packages, R CMD check will complain about non-portable flags.

In order to resolve this, We create a Makevars file that contains the flags used during compilation of R (as seen from R CMD config CFLAGS), but without the conflicting ones. So if we have

$ R CMD config CFLAGS
-g -O2 -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -g

we use

$ cat ~/.R/Makevars
CXX=clang++
CXXFLAGS=-g -O2 -fstack-protector-strong -D_FORTIFY_SOURCE=2