doctest-package {doctest} | R Documentation |
Write testthat tests for your examples, using roxygen tags
Description
The doctest package lets you test the code in your "Examples" section in .Rd files. It uses the roxygen2 and testthat packages. For more information, see @doctest and @expect.
Details
Example
Here's some roxygen documentation for a function:
#' Fibonacci function #' #' @param n Integer #' @return The nth Fibonacci number #' #' @doctest #' #' @expect type("integer") #' fib(2) #' #' n <- 6 #' @expect equal(8) #' fib(n) #' #' @expect warning("not numeric") #' fib("a") #' #' @expect warning("NA") #' fib(NA) fib <- function (n) { if (! is.numeric(n)) warning("n is not numeric") ... }
Instead of an @examples
section, we have a @doctest
section.
This will create tests like:
# Generated by doctest: do not edit by hand # Please edit file in R/<text> test_that("Doctest: fib", { # Created from @doctest for `fib` # Source file: <text> # Source line: 7 expect_type(fib(2), "integer") n <- 6 expect_equal(fib(n), 8) expect_warning(fib("a"), "not numeric") expect_warning(fib(NA), "NA") })
The .Rd file will be created as normal, with an example section like:
\examples{ fib(2) n <- 6 fib(n) fib("a") fib(NA) }
Usage
Install doctest from r-universe:
install.packages("doctest", repos = c("https://hughjonesd.r-universe.dev", "https://cloud.r-project.org"))
Or from CRAN:
install.packages("doctest")
Or get the development version:
devtools::install("hughjonesd/doctest")
To use doctest in your package, alter its DESCRIPTION file to add the
dt_roclet
roclet and "doctest"
package to roxygen:
Roxygen: list(roclets = c("collate", "rd", "namespace", "doctest::dt_roclet"), packages = "doctest")
Then use roxygen2::roxygenize()
or devtools::document()
to build
your package documentation.
Author(s)
Maintainer: David Hugh-Jones davidhughjones@gmail.com
See Also
Useful links: