Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 506
rlegendi Avatar asked Sep 07 '12 07:09

rlegendi


People also ask

What is Testthat in R?

testthat is the most popular unit testing package for R and is used by thousands of CRAN packages. If you're not familiar with testthat, the testing chapter in R packages gives a good overview, along with workflow advice and concrete examples.

What is code coverage R?

Code coverage is a measure of the amount of code being exercised by a set of tests. It is an indirect measure of test quality and completeness. This package is compatible with any testing methodology or framework and tracks coverage of both R code and compiled C/C++/FORTRAN code. Version: 3.6.1.

How do you write a unit test in R?

Create a directory called tests and put there one ore more R scripts all starting with test_ as a file name. After this you could just start the unit testing code by calling testthat::test_dir(“tests”) within R and you will see an output similar to that. The output is shown after calling the tests.

What is code coverage JUnit?

Basically, it is a tool used to maintain all project-related documents of all source code including JUnit and project source code. It also helps us to display the coverage level of method and class implementation.


2 Answers

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
like image 135
jhin Avatar answered Oct 10 '22 19:10

jhin


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

library(covr)
coverage_to_list()
like image 27
screechOwl Avatar answered Oct 10 '22 20:10

screechOwl