rlegendi
rlegendi

Reputation: 10606

R code coverage for the testthat package

Is there any tools to evaluate code coverage for R scripts using the testthat package? I found nothing by Google except a mention of the topic in the Future work section of an RJournal article.

Upvotes: 16

Views: 4956

Answers (4)

Eike P.
Eike P.

Reputation: 3493

There is the newly-arrived covr package which seems to do everything you want, and more! It provides integration with various CI services and shiny. It works with any kind of testing infrastructure (testthat, RUnit, anything else) and also works with compiled code.


What follows is just a very simple demo case I compiled quickly to get you started.

install.packages("covr")

Add a file testcovr/R/doublefun.r containing

doublefun <- function(x, superfluous_option) {
    if (superfluous_option) {
        2*x
    } else {
        3*x
    }
}

and a file testcovr/tests/testthat/test.doublefun.r containing

context("doublefun")

test_that("doublefun doubles correctly", {

    expect_equal(doublefun(1, TRUE), 2)
})

and then run e.g.

test("testcovr")
## Testing testcovr
## doublefun : .

library(covr)
package_coverage("testcovr")
## doublefun : .
##
## Package Coverage: 66.67%
## R/doublefun.r: 66.67%
zero_coverage(package_coverage("testcovr"))
## doublefun : .
##
##        filename first_line last_line first_column last_column value
## 3 R/doublefun.r          5         5            9          11     0

Upvotes: 25

screechOwl
screechOwl

Reputation: 28159

You can use the following solution to evaluate code coverage for R scripts using the testthat package:

library(covr)
coverage_to_list()

Upvotes: 1

cannin
cannin

Reputation: 3285

Here's an attempt at calculating test coverage for a set of R files at the function level:

https://gist.github.com/cannin/819e73426b4ebd5752d5

It depends on using regular expressions to find where functions are created and when they are called.

Upvotes: 1

rlegendi
rlegendi

Reputation: 10606

The I'll answer my own question :-)

I asked the same question at the project site. It seems at the moment there is no such support for the testthat library, but the possibility recently opened by using the development version of R and exploiting some new features of the profiler. Unfortunately, it seems a huge work to do that, but hopefully someone will take the lead on that.

Find the details in this ticket.

Upvotes: 8

Related Questions