Movatterモバイル変換


[0]ホーム

URL:


Encoding:UTF-8
Title:Test Coverage for Packages
Version:3.6.5
Description:Track and report code coverage for your package and (optionally) upload the results to a coverage service like 'Codecov'https://about.codecov.io or 'Coveralls'https://coveralls.io. 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.
URL:https://covr.r-lib.org,https://github.com/r-lib/covr
BugReports:https://github.com/r-lib/covr/issues
Depends:R (≥ 3.1.0), methods
Imports:digest, stats, utils, jsonlite, rex, httr, cli, withr (≥1.0.2), yaml
Suggests:R6, S7 (≥ 0.2.0), curl, knitr, rmarkdown, htmltools, DT (≥0.2), testthat (≥ 3.0.0), rlang, rstudioapi (≥ 0.2), xml2 (≥1.0.0), parallel, memoise, covr, box (≥ 1.2.0)
License:MIT + file LICENSE
VignetteBuilder:knitr
RoxygenNote:7.3.3
Config/testthat/edition:3
Config/testthat/parallel:TRUE
NeedsCompilation:yes
Packaged:2025-11-06 16:15:28 UTC; jimhester
Author:Jim Hester [aut, cre], Willem Ligtenberg [ctb], Kirill Müller [ctb], Henrik Bengtsson [ctb], Steve Peak [ctb], Kirill Sevastyanenko [ctb], Jon Clayden [ctb], Robert Flight [ctb], Eric Brown [ctb], Brodie Gaslam [ctb], Will Beasley [ctb], Robert Krzyzanowski [ctb], Markus Wamser [ctb], Karl Forner [ctb], Gergely Daróczi [ctb], Jouni Helske [ctb], Kun Ren [ctb], Jeroen Ooms [ctb], Ken Williams [ctb], Chris Campbell [ctb], David Hugh-Jones [ctb], Qin Wang [ctb], Doug Kelkhoff [ctb], Ivan Sagalaev [ctb, cph] (highlight.js library), Mark Otto [ctb] (Bootstrap library), Jacob Thornton [ctb] (Bootstrap library), Bootstrap contributors [ctb] (Bootstrap library), Twitter, Inc [cph] (Bootstrap library)
Maintainer:Jim Hester <james.f.hester@gmail.com>
Repository:CRAN
Date/Publication:2025-11-09 20:50:02 UTC

covr: Test coverage for packages

Description

covr tracks and reports code coverage for your package and (optionally)upload the results to a coverage service like 'Codecov'https://about.codecov.io or'Coveralls'https://coveralls.io. Code coverage is a measure of the amount ofcode being exercised by a set of tests. It is an indirect measure of testquality and completeness. This package is compatible with any testingmethodology or framework and tracks coverage of both R code and compiledC/C++/FORTRAN code.

Details

A coverage report can be used to inspect coverage for each line in yourpackage. Usingreport() requires the additional dependenciesDT andhtmltools.

# If run with no arguments `report()` implicitly calls `package_coverage()`report()

Package options

covr uses the followingoptions() to configure behaviour:

Author(s)

Maintainer: Jim Hesterjames.f.hester@gmail.com

Other contributors:

See Also

Useful links:


Convert a counters object to a coverage object

Description

Convert a counters object to a coverage object

Usage

as_coverage(counters = NULL, ...)

Arguments

counters

An environment of covr trace results to convert to a coverageobject. Ifcounters is not provided, thecovr namespace value.counters is used.

...

Additional attributes to include with the coverage object.


Clean and restructure counter tests for a coverage object

Description

For tests produced withoptions(covr.record_tests), prune any unusedrecords in the $tests$tally matrices of each trace and get rid of thewrapping $tests environment (reassigning with value of $tests$tally)

Usage

as_coverage_with_tests(counters)

Arguments

counters

An environment of covr trace results to convert to a coverageobject. Ifcounters is not provided, thecovr namespace value.counters is used.


Run covr on a package and output the result so it is available on Azure Pipelines

Description

Run covr on a package and output the result so it is available on Azure Pipelines

Usage

azure(  ...,  coverage = package_coverage(..., quiet = quiet),  filename = "coverage.xml",  quiet = TRUE)

Arguments

...

arguments passed topackage_coverage()

coverage

an existing coverage object to submit, ifNULL,package_coverage() will be called with the arguments from...

filename

the name of the Cobertura XML file

quiet

ifFALSE, print the coverage before submission.


clear all previous counters

Description

clear all previous counters

Usage

clear_counters()

Calculate coverage of code directly

Description

This function is useful for testing, and is a thin wrapper aroundfile_coverage() because parseData is not populated properlyunless the functions are defined in a file.

Usage

code_coverage(  source_code,  test_code,  line_exclusions = NULL,  function_exclusions = NULL,  ...)

Arguments

source_code

A character vector of source code

test_code

A character vector of test code

line_exclusions

a named list of files with the lines to exclude fromeach file.

function_exclusions

a vector of regular expressions matching functionnames to exclude. Example⁠print\\\.⁠ to match print methods.

...

Additional arguments passed tofile_coverage()

Examples

source <- "add <- function(x, y) { x + y }"test <- "add(1, 2) == 3"code_coverage(source, test)

Run covr on a package and upload the result to codecov.io

Description

Run covr on a package and upload the result to codecov.io

Usage

codecov(  ...,  coverage = NULL,  base_url = "https://codecov.io",  token = NULL,  commit = NULL,  branch = NULL,  pr = NULL,  flags = NULL,  quiet = TRUE)

Arguments

...

arguments passed topackage_coverage()

coverage

an existing coverage object to submit, ifNULL,package_coverage() will be called with the arguments from...

base_url

Codecov url (change for Enterprise)

token

a codecov upload token, ifNULL then following externalsources will be checked in this order:

  1. the environment variable ‘CODECOV_TOKEN’. If it is empty, then

  2. package will look at directory of the package for a filecodecov.yml.File must havecodecov section where fieldtoken is set to a token thatwill be used.

commit

explicitly set the commit this coverage result objectcorresponds to. Is looked up from the service or locally if it isNULL.

branch

explicitly set the branch this coverage result objectcorresponds to, this is looked up from the service or locally if it isNULL.

pr

explicitly set the pr this coverage result object corresponds to,this is looked up from the service if it isNULL.

flags

A flag to use for this coverage upload seehttps://docs.codecov.com/docs/flags for details.

quiet

ifFALSE, print the coverage before submission.

Examples

## Not run: codecov(path = "test")## End(Not run)

increment a given counter

Description

increment a given counter

Usage

count(key)

Arguments

key

generated withkey()


Append a test trace to a counter, updating global current test

Description

Append a test trace to a counter, updating global current test

Usage

count_test(key)

Arguments

key

generated withkey()


Convert a coverage dataset to a list

Description

Convert a coverage dataset to a list

Usage

coverage_to_list(x = package_coverage())

Arguments

x

a coverage dataset, defaults to runningpackage_coverage().

Value

A list containing coverage result for each individual file and the whole package


Run covr on a package and upload the result to coveralls

Description

Run covr on a package and upload the result to coveralls

Usage

coveralls(  ...,  coverage = NULL,  repo_token = Sys.getenv("COVERALLS_TOKEN"),  service_name = Sys.getenv("CI_NAME", "travis-ci"),  quiet = TRUE)

Arguments

...

arguments passed topackage_coverage()

coverage

an existing coverage object to submit, ifNULL,package_coverage() will be called with the arguments from...

repo_token

The secret repo token for your repository,found at the bottom of your repository's page on Coveralls. This is usefulif your job is running on a service Coveralls doesn't support out-of-the-box.If set to NULL, it is assumed that the job is running on travis-ci

service_name

the CI service to use, if environment variable‘CI_NAME’ is set that is used, otherwise ‘travis-ci’ is used.

quiet

ifFALSE, print the coverage before submission.


Record Test Traces During Coverage Execution

Description

By settingoptions(covr.record_tests = TRUE), the result of covr coveragecollection functions will include additional data pertaining to the testswhich are executed and an index of which tests, at what stack depth, triggerthe execution of each trace.

Details

This functionality requires that the package code and tests are installed andsourced with the source. For more details, refer to R options,keep.source,keep.source.pkgs andkeep.parse.data.pkgs.

Additional fields

Within thecovr result, you can explore this information in two places:

Test traces

The content of test traces are dependent on the unit testing framework thatis used by the target package. The behavior is contingent on the availableinformation in the sources kept for the testing files.

Test traces are extracted by the following criteria:

  1. If anysrcref files are are provided by a file withincovr's temporarylibrary, all calls from those files are kept as a test trace. This willcollect traces from tests run with common testing frameworks such astestthat andRUnit.

  2. Otherwise, as a conservative fallback in situations where no sourcereferences are found, or when none are from within the temporarydirectory, the entire call stack is collected.

These calls are subsequently subset for only those up until the call tocovr's internalcount function, and will always include the last call inthe call stack prior to a call tocount.

Examples

fcode <- 'f <- function(x) {  if (x)    f(!x)  else    FALSE}'options(covr.record_tests = TRUE)cov <- code_coverage(fcode, "f(TRUE)")# extract executed test code for the first testtail(attr(cov, "tests")[[1L]], 1L)# [[1]]# f(TRUE)# extract test itemization per tracecov[[3]][c("srcref", "tests")]# $srcref# f(!x)## $tests#      test call depth i# [1,]    1    1     2 4# reconstruct the code path of a test by ordering test traces by [,"i"]lapply(cov, `[[`, "tests")# $`source.Ref2326138c55:4:6:4:10:6:10:4:4`#      test call depth i# [1,]    1    1     1 2## $`source.Ref2326138c55:3:8:3:8:8:8:3:3`#      test call depth i# [1,]    1    1     1 1# [2,]    1    1     2 3## $`source.Ref2326138c55:6:6:6:10:6:10:6:6`#      test call depth i# [1,]    1    1     2 4

Retrieve the number of times the test call was called

Description

A single test expression might be evaluated many times. Each time the sameexpression is called, the call count is incremented.

Usage

current_test_call_count()

Value

An integer value representing the number of calls of the currentcall into the package from the testing suite.


Retrieve the index for the test in.counters$tests

Description

If the test was encountered before, the index will be the index of the testin the logged tests list. Otherwise, the index will be the next index beyondthe length of the tests list.

Usage

current_test_index()

Value

An integer index for the test call


Build key for the current test

Description

If the current test has a srcref, a unique character key is built from itssrcref. Otherwise, an empty string is returned.

Usage

current_test_key()

Value

A unique character string if the test call has a srcref, or an emptystring otherwise.


Retrieve the path name (filename) for each coverage object

Description

Retrieve the path name (filename) for each coverage object

Usage

display_name(x)

Arguments

x

A coverage object


Calculate coverage of an environment

Description

Calculate coverage of an environment

Usage

environment_coverage(  env = parent.frame(),  test_files,  line_exclusions = NULL,  function_exclusions = NULL)

Arguments

env

The environment to be instrumented.

test_files

Character vector of test files with code to test thefunctions

line_exclusions

a named list of files with the lines to exclude fromeach file.

function_exclusions

a vector of regular expressions matching functionnames to exclude. Example⁠print\\\.⁠ to match print methods.


Exclusions

Description

covr supports a couple of different ways of excluding some or all of a file.

Line Exclusions

Theline_exclusions argument topackage_coverage() can be usedto exclude some or all of a file. This argument takes a list of filenamesor named ranges to exclude.

Function Exclusions

Alternativelyfunction_exclusions can be used to exclude R functionsbased on regular expression(s). For example⁠print\\\.*⁠ can be used toexclude all the print methods defined in a package from coverage.

Exclusion Comments

In addition you can exclude lines from the coverage by putting special commentsin your source code. This can be done per line or by specifying a range.The patterns used can be specified by theexclude_pattern,exclude_start,exclude_end arguments topackage_coverage() or by setting the globaloptionscovr.exclude_pattern,covr.exclude_start,covr.exclude_end.

Examples

## Not run: # exclude whole file of R/test.Rpackage_coverage(exclusions = "R/test.R")# exclude lines 1 to 10 and 15 from R/test.Rpackage_coverage(line_exclusions = list("R/test.R" = c(1:10, 15)))# exclude lines 1 to 10 from R/test.R, all of R/test2.Rpackage_coverage(line_exclusions = list("R/test.R" = 1:10, "R/test2.R"))# exclude all print and format methods from the package.package_coverage(function_exclusions = c("print\\.", "format\\."))# single line exclusionsf1 <- function(x) {  x + 1 # nocov}# ranged exclusionsf2 <- function(x) { # nocov start  x + 2} # nocov end## End(Not run)

Calculate test coverage for sets of files

Description

The files insource_files are first sourced into a new environmentto define functions to be checked. Then they are instrumented to trackcoverage and the files intest_files are sourced.

Usage

file_coverage(  source_files,  test_files,  line_exclusions = NULL,  function_exclusions = NULL,  parent_env = parent.frame())

Arguments

source_files

Character vector of source files with functiondefinitions to measure coverage

test_files

Character vector of test files with code to test thefunctions

line_exclusions

a named list of files with the lines to exclude fromeach file.

function_exclusions

a vector of regular expressions matching functionnames to exclude. Example⁠print\\\.⁠ to match print methods.

parent_env

The parent environment to use when sourcing the files.

Examples

# For the purpose of this example, save code containing code and tests to filescat("add <- function(x, y) { x + y }", file="add.R")cat("add(1, 2) == 3", file="add_test.R")# Use file_coverage() to calculate test coveragefile_coverage(source_files = "add.R", test_files = "add_test.R")# cleanupfile.remove(c("add.R", "add_test.R"))

A coverage report for a specific file

Description

A coverage report for a specific file

Usage

file_report(  x = package_coverage(),  file = NULL,  out_file = file.path(tempdir(), paste0(get_package_name(x), "-file-report.html")),  browse = interactive())

Arguments

x

a coverage dataset, defaults to runningpackage_coverage().

file

The file to report on, ifNULL, use the first file in thecoverage output.

out_file

The output file

browse

whether to open a browser to view the report.


Calculate test coverage for a specific function.

Description

Calculate test coverage for a specific function.

Usage

function_coverage(fun, code = NULL, env = NULL, enc = parent.frame())

Arguments

fun

name of the function.

code

expressions to run.

env

environment the function is defined in.

enc

the enclosing environment which to run the expressions.

Examples

add <- function(x, y) { x + y }function_coverage(fun = add, code = NULL) # 0% coveragefunction_coverage(fun = add, code = add(1, 2) == 3) # 100% coverage

Run covr on package and create report for GitLab

Description

Utilize internal GitLab static pages to publish package coverage.Creates local covr report in a package subdirectory.Uses thepagesGitLab job to publish the report.

Usage

gitlab(..., coverage = NULL, file = "public/coverage.html", quiet = TRUE)

Arguments

...

arguments passed topackage_coverage()

coverage

an existing coverage object to submit, ifNULL,package_coverage() will be called with the arguments from...

file

The report filename.

quiet

ifFALSE, print the coverage before submission.


Is the source bound to the expression

Description

Is the source bound to the expression

Usage

has_srcref(expr)

Arguments

expr

A language object which may have asrcref attribute

Value

A logical value indicating whether the language object has source


Determine if code is being run in covr

Description

covr functions set the environment variableR_COVR when they are running.in_covr() returnsTRUE if this environment variable is set andFALSEotherwise.

Usage

in_covr()

Examples

if (require(testthat)) {  testthat::skip_if(in_covr())}

Is the expression a call to covr:::count

Description

Is the expression a call to covr:::count

Usage

is_covr_count_call(expr)

Arguments

expr

A language object

Value

A logical value indicating whether the object is a call tocovr:::count.


Returns TRUE if we've moved on from test reflected in .current_test

Description

Quickly dismiss the need to update the current test if we can. To test ifwe're still in the last test, check if the same srcref (or call, if source isnot kept) exists at the last recorded calling frame prior to entering a covrtrace. If this has changed, do a more comprehensive test to see if any of thetest call stack has changed, in which case we are onto a new test.

Usage

is_current_test_finished()

Generate a key for a call

Description

Generate a key for a call

Usage

key(x)

Arguments

x

the srcref of the call to create a key for


initialize a new counter

Description

initialize a new counter

Usage

new_counter(src_ref, parent_functions)

Arguments

src_ref

abase::srcref()

parent_functions

the functions that this srcref is contained in.


Initialize a new test counter for a coverage trace

Description

Initialize a test counter, a matrix used to tally tests, their stack depthand the execution order as the trace associated withkey is hit. Eachtest trace is an environment, which allows assignment into a pre-allocatedtests matrix with minimall reallocation.

Usage

new_test_counter(key)

Arguments

key

generated withkey()

Details

Thetests matrix has columnstests,depth andi,corresponding to the test index (the index of the associated test in.counters$tests), the stack depth when the trace is evaluated and thenumber of traces that have been hit so far during test evaluation.


Calculate test coverage for a package

Description

This function calculates the test coverage for a development package on thepath. By default it runs only the package tests, but it can also runvignette and example code.

Usage

package_coverage(  path = ".",  type = c("tests", "vignettes", "examples", "all", "none"),  combine_types = TRUE,  relative_path = TRUE,  quiet = TRUE,  clean = TRUE,  line_exclusions = NULL,  function_exclusions = NULL,  code = character(),  install_path = temp_file("R_LIBS"),  ...,  exclusions,  pre_clean = TRUE)

Arguments

path

file path to the package.

type

run the package ‘tests’, ‘vignettes’,‘examples’, ‘all’, or ‘none’. The default is‘tests’.

combine_types

IfTRUE (the default) the coverage for all typesis simply summed into one coverage object. IfFALSE separate objectsare used for each type of coverage.

relative_path

whether to output the paths as relative or absolutepaths. If a string, it is interpreted as a root path and all paths will berelative to that root.

quiet

whether to load and compile the package quietly, useful fordebugging errors.

clean

whether to clean temporary output files after running, mainlyuseful for debugging errors.

line_exclusions

a named list of files with the lines to exclude fromeach file.

function_exclusions

a vector of regular expressions matching functionnames to exclude. Example⁠print\\\.⁠ to match print methods.

code

A character vector of additional test code to run.

install_path

The path the instrumented package will be installed toand tests run in. By default it is a path in the R sessions temporarydirectory. It can sometimes be useful to set this (along withclean = FALSE) to help debug test failures.

...

Additional arguments passed totools::testInstalledPackage().

exclusions

‘Deprecated’, please use ‘line_exclusions’ instead.

pre_clean

whether to delete all objects present in the src directory before recompiling

Details

This function usestools::testInstalledPackage() to run thecode, if you would like to test your package in another way you can settype = "none" and pass the code to run as a character vector to thecode parameter.

Parallelized code usingparallel'smcparallel() needs touse a patchedparallel:::mcexit. This is done automatically if thepackage depends onparallel, but can also be explicitly set using theenvironment variableCOVR_FIX_PARALLEL_MCEXIT or the global optioncovr.fix_parallel_mcexit.

See Also

exclusions() For details on excluding parts of thepackage from the coverage calculations.


Provide percent coverage of package

Description

Calculate the total percent coverage from a coverage result object.

Usage

percent_coverage(x, ...)

Arguments

x

the coverage object returned frompackage_coverage()

...

additional arguments passed totally_coverage()

Value

The total percentage as anumeric(1).


Print a coverage object

Description

Print a coverage object

Usage

## S3 method for class 'coverage'print(x, group = c("filename", "functions"), by = "line", ...)

Arguments

x

the coverage object to be printed

group

whether to group coverage by filename or function

by

whether to count coverage by line or expression

...

additional arguments ignored

Value

The coverage object (invisibly).


Display covr results using a standalone report

Description

Display covr results using a standalone report

Usage

report(  x = package_coverage(),  file = file.path(tempdir(), paste0(get_package_name(x), "-report.html")),  browse = interactive())

Arguments

x

a coverage dataset, defaults to runningpackage_coverage().

file

The report filename.

browse

whether to open a browser to view the report.

Examples

## Not run: x <- package_coverage()report(x)## End(Not run)

Run a system command and check if it succeeds.

Description

This function automatically quotes both the command and eachargument so they are properly protected from shell expansion.

Usage

system_check(  cmd,  args = character(),  env = character(),  quiet = FALSE,  echo = FALSE,  ...)

Arguments

cmd

the command to run.

args

a vector of command arguments.

env

a named character vector of environment variables. Will be quoted

quiet

ifTRUE, the command output will be echoed.

echo

ifTRUE, the command to run will be echoed.

...

additional arguments passed tobase::system()

Value

TRUE if the command succeeds, an error will be thrown if thecommand fails.


Run a system command and capture the output.

Description

This function automatically quotes both the command and eachargument so they are properly protected from shell expansion.

Usage

system_output(  cmd,  args = character(),  env = character(),  quiet = FALSE,  echo = FALSE,  ...)

Arguments

cmd

the command to run.

args

a vector of command arguments.

env

a named character vector of environment variables. Will be quoted

quiet

ifTRUE, the command output will be echoed.

echo

ifTRUE, the command to run will be echoed.

...

additional arguments passed tobase::system()

Value

command output if the command succeeds, an error will be thrown ifthe command fails.


Tally coverage by line or expression

Description

Tally coverage by line or expression

Usage

tally_coverage(x, by = c("line", "expression"))

Arguments

x

the coverage object returned frompackage_coverage()

by

whether to tally coverage by line or expression

Value

adata.frame of coverage tallied by line or expression.


Create a Cobertura XML file

Description

Create acobertura-compliant XML report followingthis DTD.Because there aretwo DTDs called⁠coverage-04.dtd⁠ and some tools do not seem toadhere to either of them, the parser you're using may balk at the file. Please seethis github discussion forcontext. Wherecovr doesn't provide a coverage metric (branch coverage,complexity), a zero is reported.

Usage

to_cobertura(cov, filename = "cobertura.xml")

Arguments

cov

the coverage object returned frompackage_coverage()

filename

the name of the Cobertura XML file

Details

Note: This functionality requires the xml2 package be installed.


Create a SonarQube Generic XML file for test coverage according tohttps://docs.sonarqube.org/latest/analysis/generic-test/Based on cobertura.R

Description

This functionality requires the xml2 package be installed.

Usage

to_sonarqube(cov, filename = "sonarqube.xml")

Arguments

cov

the coverage object returned frompackage_coverage()

filename

the name of the SonarQube Generic XML file

Author(s)

Talkdesk Inc.


trace each call with a srcref attribute

Description

This function calls itself recursively so it can properly traverse the AST.

Usage

trace_calls(x, parent_functions = NULL, parent_ref = NULL)

Arguments

x

the call

parent_functions

the functions which this call is a child of.

parent_ref

argument used to set the srcref of the current call duringthe recursion.

Value

a modified expression with count calls inserted before each previouscall.

See Also

http://adv-r.had.co.nz/Expressions.html


Truncate call objects to limit the number of arguments

Description

A helper to circumvent R errors when deserializing large call objects fromRds. Trims the number of arguments in a call object, and replaces the lastargument with a⁠<truncated>⁠ symbol.

Usage

truncate_call(call_obj, limit = 10000)

Arguments

call_obj

A (possibly large)call object

limit

Acall length limit to impose

Value

Thecall_obj with arguments trimmed


Update current test if unit test expression has progressed

Description

Updating a test logs some metadata regarding the current call stack, noteablytrying to capture information about the call stack prior to the covr::countcall being traced.

Usage

update_current_test()

Details

There are a couple patterns of behavior, which try to accommodate a varietyof testing suites:

checks to see if the current call stack has the samesrcref (or expression, if no source is available) at the same frame priorto entering into a package wherecovr:::count is called.


Retrieve the value from an object

Description

Retrieve the value from an object

Usage

value(x, ...)

Arguments

x

object from which to retrieve the value

...

additional arguments passed to methods


Provide locations of zero coverage

Description

When examining the test coverage of a package, it is useful to know if there areany locations where there is0 test coverage.

Usage

zero_coverage(x, ...)

Arguments

x

a coverage object returnedpackage_coverage()

...

additional arguments passed totally_coverage()

Details

if used within RStudio this function outputs the results using theMarker API.

Value

Adata.frame with coverage data where the coverage is 0.


[8]ページ先頭

©2009-2025 Movatter.jp