package_coverage(), file_coverage(), code_coverage(),
function_coverage() and environment_coverage() return a coverage
object, which records how many times each part of the code was executed.
Working with coverage objects
Rather than using the list directly, you will usually want to:
Get a data frame with one row for each expression with
as.data.frame()(as.data.frame.coverage()), or one row for each line or function withtally_coverage().Get the overall percentage with
percent_coverage(), or the percentage for each file withcoverage_to_list().Find the lines or functions which were never run with
zero_coverage(), list them as ranges withprint(x, missing = TRUE), or show their source withannotate_coverage().Get the execution counts as a named numeric vector with
value().Browse the coverage with
report()orfile_report().
Structure
A coverage object is a named list with one element for each traced
expression of R code and each line of compiled code. Each element is a list
with:
value: the number of times the expression or line was executed.srcref: a srcref with its location. Itssrcfileattribute holds the name and lines of the source file.functions: the name of the function containing it, orNAfor compiled code.tests: only present withoptions(covr.record_tests = TRUE), see covr.record_tests.
The names of the elements are the base name of the file followed by the
eight numbers of the srcref, separated by :. For example
foo.R:10:3:12:4:3:4:10:12 is an expression from line 10 column 3 to line
12 column 4 of foo.R (see as.data.frame.coverage() for the meaning of
each number). The srcfile of the srcref, or the filename column of
as.data.frame(), gives the path of the file.
Coverage objects from package_coverage() also have the attributes
package (information about the package, such as its package name and
path), root (the directory file names are relative to, or NULL) and,
if clean = FALSE, library (the install_path).
With options(covr.record_tests = TRUE), coverage objects also have a
tests attribute with the test calls, see covr.record_tests.
With options(covr.branch_coverage = TRUE), coverage objects also have a
branches attribute with the branches of each if and switch(), see
covr.branch_coverage.
Examples
cov <- code_coverage("add <- function(x, y) { x + y }", "add(1, 2)")
cov
#> Coverage: 100.00%
#> /tmp/RtmpvpKgL4/source.R190e6c6ed4f: 100.00%
as.data.frame(cov)
#> filename functions first_line first_byte last_line
#> 1 /tmp/RtmpvpKgL4/source.R190e6c6ed4f add 1 25 1
#> last_byte first_column last_column first_parsed last_parsed value
#> 1 29 25 29 1 1 1
names(cov)
#> [1] "source.R190e6c6ed4f:1:25:1:29:25:29:1:1"
cov[[1]]$value
#> [1] 1
