testthat/0000755000176200001440000000000012124613364012114 5ustar liggesuserstestthat/MD50000644000176200001440000000711012124613364012423 0ustar liggesusers7911de1572677049691192e8d475a1b2 *DESCRIPTION a1c9ba16e27472ad9ecf5fee42ccdc33 *NAMESPACE 38609f639b8379d12acb2bfc7794b4e2 *NEWS 6003186cf39dfe81c75f7ad6755d78ed *R/auto-test.r d064c33dd46707ff043ab92e3a24a7bf *R/colour-text.r b9b877dae7e585ac90371134ccee1968 *R/context.r c3d4986fbefefc45e81a93bcde4dc240 *R/expect-that.r 28fee654b5cb6799971e0baabfc44c21 *R/expectation.r 89f0339222b17385982cd24c766c14b9 *R/expectations.r 77cc8a0408da46a65cfce3b2c0120153 *R/library.r eedb0f03a465fb7e08ea26a6f9fadd39 *R/make-expectation.r a9714dee7123504c3a0eadeaedf4a64b *R/reporter-minimal.r 338d498dc07a59d154a8679fb48bd607 *R/reporter-stop.r 4d1a7b9cc3bb75bc4c5d37910526e5e6 *R/reporter-summary.r c5bff9046d66f3860e909afa4de9ae8f *R/reporter-tap.r ee541552c76be09b187450356a0dd893 *R/reporter-zzz.r d752bbe7f40c3df39f6ed42a9e0f13d9 *R/reporter.r 3e68c1540af5a1f1bd3cd8412e5fc528 *R/test-files.r 3958583a4c46449f512035a9a1216501 *R/test-package.r 1dcd82279f8f2e9b3c26eeafd2ae776d *R/test-that.r 3b8959470f290f000f40dadadaddccc0 *R/utils.r 4ae9a4fbf797bff6f530f3ca43ea680a *R/watcher.r 353b3d78203e8a4ddfddbdff56663c76 *README.md dca111da574904db7ea9c6f8d205a1c4 *inst/tests/context.r f6427d37aeddf233e6efe3c10eee4768 *inst/tests/test-bare.r 662c140eb5bd6c4bc887745e0a365aa1 *inst/tests/test-basics.r 212848b75d6d72d718d5f7a05dc60fb2 *inst/tests/test-context.r 240d8edf6c0164ba94613324deabfeba *inst/tests/test-expectations.r ff1eb6ad16b1b338f20c1cc860fd062f *inst/tests/test-reporter.r 9c7d3bffde0a5f544c1979d8a441afc2 *inst/tests/test-watcher.r cfdfa905d9e41849cb5fb65da6c72183 *inst/tests/test-xxx.r a3cdd28ade039ab77cb6495bef6fe614 *man/MinimalReporter.Rd da61097db69076093168871a4e4859ea *man/Reporter.Rd 1c7f62e85e67088e1f338f552745cc7a *man/StopReporter.Rd 25a4dabaed30ebaea3b745eb4310d670 *man/SummaryReporter.Rd e3d3163eedf0dcff2038a89733b44aa6 *man/TapReporter.Rd 2edb7547dcb0e433b199697ff6303d0c *man/auto_test.Rd 6253412dff8eed0f5a1757f4ecebca06 *man/auto_test_package.Rd 839f8c23eb17ee70f55b3b465973a2e9 *man/colourise.Rd 9ef88bf977acceae9663f31fbdb50b62 *man/compare_state.Rd cfe1197011b12b363edf56ef0b58ce1d *man/context.Rd deada6cf2ff5e21f92e70185ca42b500 *man/dir_state.Rd adcd7f800e1b1eb6947cbe32e2c7367a *man/equals.Rd e50b1360413fc3fd79f17c522416896e *man/error_report.Rd 4bf7c5a11c0f7873c47d037aee5750a8 *man/expect_that.Rd 695412466a08deecf5318411383678a9 *man/expectation.Rd 6b4318cfe5216a27cabcf9398e87b1c6 *man/fail.Rd b2ea07c6429e96df95692cafb8239615 *man/find_reporter.Rd a6d26065349d33a7d8ec57958d811a30 *man/gives_warning.Rd 0ce69b36a0eaf121da4de16cfe6555e0 *man/is_a.Rd 62b099115cc2504f9d00735704ca6eab *man/is_equivalent_to.Rd adb4140f57533ff83244495afa6b3371 *man/is_false.Rd 1837f8136c57be25e048c9d635775ff1 *man/is_identical_to.Rd 75591987beca7ce361de6f4592bb7a95 *man/is_true.Rd ee43c65128591c92e43704f413594326 *man/library_if_available.Rd d3de45cd2e98cdd2ae934c21e9a9010e *man/make_expectation.Rd 0e6d040f44ece5d81a6d9c86c3b11c18 *man/matches.Rd 730a833921797b6070db3503545c2bab *man/prints_text.Rd a50eb9db4f72f844b2ab7f91225f7234 *man/shows_message.Rd 66de5979750401d6513908adddaeb324 *man/source_dir.Rd 1a210f04b89716a82423bc2a25cbc168 *man/takes_less_than.Rd 045747a5016a0dd321d58b3dff09f1f8 *man/test_dir.Rd 81ebaf9c6b705202b12cf915df6a3320 *man/test_file.Rd 9515926e1d5ac27cad4a12356480c0c7 *man/test_package.Rd 642db3c63348e7bb49da91e5ba968cef *man/test_that.Rd 19690698b17fe0ee8b407c933431b0ff *man/throws_error.Rd 17069634445471e1c88b0dc21890d528 *man/watch.Rd c728d270bbee4c1fa7165f45fdd70790 *man/with_reporter.Rd 8d86732ac06d5caba296df18490dca01 *tests/dependencies.r ce9ba9a20cef7b4929b5f404382ce096 *tests/test-all.R testthat/tests/0000755000176200001440000000000012122406347013255 5ustar liggesuserstestthat/tests/test-all.R0000644000176200001440000000005312122406046015117 0ustar liggesuserslibrary(testthat) test_package("testthat") testthat/tests/dependencies.r0000644000176200001440000000020612122406347016064 0ustar liggesusersif (Sys.info()["user"] == "hadley") { library(devtools) check_cran("lubridate") check_cran("reshape2") check_cran("stringr") } testthat/README.md0000644000176200001440000000267412122406261013376 0ustar liggesusers# testthat Testing your code is normally painful and boring. `testthat` tries to make testing as fun as possible, so that you get a visceral satisfaction from writing tests. Testing should be fun, not a drag, so you do it all the time. To make that happen, `testthat`: * Provides functions that make it easy to describe what you expect a function to do, including catching errors, warnings and messages. * Easily integrates in your existing workflow, whether it's informal testing on the command line, building test suites or using R CMD check. * Can re-run tests automatically as you change your code or tests. * Displays test progress visually, showing a pass, fail or error for every expectation. If you're using the terminal, it'll even colour the output. `testthat` draws inspiration from the xUnit family of testing packages, as well from many of the innovative ruby testing libraries, like [rspec](http://rspec.info/), [testy](http://github.com/ahoward/testy), [bacon](http://github.com/chneukirchen/bacon) and [cucumber](http://wiki.github.com/aslakhellesoy/cucumber/). I have used what I think works for R, and abandoned what doesn't, creating a testing environment that is philosophically centred in R. Instructions for using this package can be found in the [Testing](https://github.com/hadley/devtools/wiki/Testing) chapter of my forthcoming book [Advanced R development: making reusable code"](https://github.com/hadley/devtools/wiki). testthat/R/0000755000176200001440000000000012124567260012320 5ustar liggesuserstestthat/R/watcher.r0000644000176200001440000000452312124347536014146 0ustar liggesusers#' Watch a directory for changes (additions, deletions & modifications). #' #' This is used to power the \code{\link{auto_test}} and #' \code{link{auto_test_package}} functions which are used to rerun tests #' whenever source code changes. #' #' Use Ctrl + break (windows), Esc (mac gui) or Ctrl + C (command line) to #' stop the watcher. #' #' @param path character vector of paths to watch. Omit trailing backslash. #' @param pattern file pattern passed to \code{\link{dir}} #' @param callback function called everytime a change occurs. It should #' have three parameters: added, deleted, modified, and should return #' TRUE to keep watching, or FALSE to stop. #' @param hash hashes are more accurate at detecting changes, but are slower #' for large files. When FALSE, uses modification time stamps #' @export watch <- function(path, callback, pattern = NULL, hash = TRUE) { prev <- dir_state(path, pattern, hash = hash) while(TRUE) { Sys.sleep(1) curr <- dir_state(path, pattern, hash = hash) changes <- compare_state(prev, curr) if (changes$n > 0) { # cat("C") keep_going <- TRUE try(keep_going <- with(changes, callback(added, deleted, modified))) if (!keep_going) return(invisible()) } else { # cat(".") } prev <- curr } } #' Capture the state of a directory. #' #' @param path path to directory #' @param pattern regular expression with which to filter files #' @param hash use hash (slow but accurate) or time stamp (fast but less #' accurate) #' @keywords internal dir_state <- function(path, pattern = NULL, hash = TRUE) { files <- dir(path, pattern, full.names = TRUE) if (hash) { sapply(files, digest::digest, file = TRUE) } else { setNames(file.info(files)$mtime, files) } } #' Compare two directory states. #' #' @param old previous state #' @param new current state #' @return list containing number of changes and files which have been #' \code{added}, \code{deleted} and \code{modified} #' @keywords internal compare_state <- function(old, new) { added <- setdiff(names(new), names(old)) deleted <- setdiff(names(old), names(new)) same <- intersect(names(old), names(new)) modified <- names(new[same])[new[same] != old[same]] n <- length(added) + length(deleted) + length(modified) list(n = n, added = added, deleted = deleted, modified = modified) } testthat/R/utils.r0000644000176200001440000000032612122406347013640 0ustar liggesusers# Find expression that created a variable find_expr <- function(name, env = parent.frame()) { subs <- do.call("substitute", list(as.name(name), env)) str_c(deparse(subs, width.cutoff = 500), collapse = "\n") } testthat/R/test-that.r0000644000176200001440000000376512122406347014427 0ustar liggesusers#' Create a test. #' #' A test encapsulates a series of expectations about small, self-contained #' set of functionality. Each test is contained in a \link{context} and #' contains multiple expectation generated by \code{\link{expect_that}}. #' #' Tests are evaluated in their own environments, and should not affect #' global state. #' #' When run from the command line, tests return \code{NULL} if all #' expectations are met, otherwise it raises an error. #' #' @param desc test name. Names should be kept as brief as possible, as they #' are often used as line prefixes. #' @param code test code containing expectations #' @importFrom evaluate try_capture_stack create_traceback is.error #' @export #' @examples #' test_that("trigonometric functions match identities", { #' expect_that(sin(pi / 4), equals(1 / sqrt(2))) #' expect_that(cos(pi / 4), equals(1 / sqrt(2))) #' expect_that(tan(pi / 4), equals(1)) #' }) #' # Failing test: #' \dontrun{ #' test_that("trigonometric functions match identities", { #' expect_that(sin(pi / 4), equals(1)) #' }) #' } test_that <- function(desc, code) { test_reporter()$start_test(desc) on.exit(test_reporter()$end_test()) env <- new.env(parent = parent.frame()) res <- suppressMessages(try_capture_stack(substitute(code), env)) if (is.error(res)) { traceback <- create_traceback(res$calls) report <- error_report(res, traceback) test_reporter()$add_result(report) } invisible() } #' Generate error report from traceback. #' #' @keywords internal #' @param error error message #' @param traceback traceback generated by \code{\link{create_traceback}} error_report <- function(error, traceback) { msg <- str_replace(as.character(error), "Error.*?: ", "") if (length(traceback) > 0) { user_calls <- str_c(traceback, collapse = "\n") msg <- str_c(msg, user_calls) } else { # Need to remove trailing newline from error message to be consistent # with other messages msg <- str_replace(msg, "\n$", "") } expectation(NA, msg) } testthat/R/test-package.r0000644000176200001440000000125412122406347015051 0ustar liggesusers#' Run all tests in an installed package #' #' Test are run in an environment that inherits from the package environment #' so that tests can access non-exported functions and variables. #' #' @param package package name #' @inheritParams test_dir #' @export #' @examples #' \dontrun{test_package("testthat")} test_package <- function(package, filter = NULL, reporter = "summary") { test_path <- system.file("tests", package = package) reporter <- find_reporter(reporter) env <- new.env(parent = getNamespace(package)) test_dir(test_path, reporter = reporter, env = env, filter = filter) if (reporter$failed) { stop("Test failures", call. = FALSE) } invisible() } testthat/R/test-files.r0000644000176200001440000000457212122406347014566 0ustar liggesusers#' Run all of the tests in a directory. #' #' Test files start with \code{test} and are executed in alphabetical order #' (but they shouldn't have dependencies). Helper files start with #' \code{helper} and loaded before any tests are run. #' #' @param path path to tests #' @param reporter reporter to use #' @param filter If not \code{NULL}, only tests with file names matching this #' regular expression will be executed. Matching will take on the file #' name after it has been stripped of \code{"test-"} and \code{".r"}. #' @param env environment in which to execute test suite. Defaults to new # environment inheriting from the global environment. #' @export test_dir <- function(path, filter = NULL, reporter = "summary", env = NULL) { reporter <- find_reporter(reporter) if (is.null(env)) { env <- new.env(parent = globalenv()) } source_dir(path, "^helper.*\\.[rR]$", env = env) files <- dir(path, "^test.*\\.[rR]$", full.names = TRUE) if (!is.null(filter)) { test_names <- basename(files) test_names <- str_replace(test_names, "test-?", "") test_names <- str_replace(test_names, "\\.[rR]", "") files <- files[str_detect(test_names, filter)] } with_reporter(reporter, lapply(files, function(file) { sys.source(file, chdir = TRUE, envir = new.env(parent = env)) end_context() })) } #' Load all source files in a directory. #' #' The expectation is that the files can be sourced in alphabetical order. #' #' @param path path to tests #' @param pattern regular expression used to filter files #' @param env environment in which to execute test suite. Defaults to new # environment inheriting from the global environment. #' @param chdir change working directory to path? #' @keywords internal #' @export #' @usage source_dir(path, pattern="\\\\.[rR]$", env = NULL, chdir=TRUE) source_dir <- function(path, pattern = "\\.[rR]$", env = NULL, chdir = TRUE) { files <- sort(dir(path, pattern, full.names = TRUE)) if (is.null(env)) { env <- new.env(parent = globalenv()) } lapply(files, sys.source, chdir = chdir, envir = env) } #' Run all tests in specified file. #' #' @param path path to file #' @param reporter reporter to use #' @export test_file <- function(path, reporter = "summary") { reporter <- find_reporter(reporter) with_reporter(reporter, { sys.source(path, new.env(parent = globalenv()), chdir = TRUE) end_context() }) } testthat/R/reporter.r0000644000176200001440000000155612122406347014350 0ustar liggesusers#' Stub object for managing a reporter of tests. #' #' Do not clone directly from this object - children should implement all #' methods. #' #' @keywords internal. #' @aliases Reporter-class #' @exportClass Reporter Reporter <- setRefClass("Reporter", fields = list( context = "character", test = "ANY", failed = "logical", context_open = "logical" ), methods = list( initialize = function(...) { context_open <<- FALSE failed <<- FALSE test <<- NULL initFields(...) }, start_reporter = function() { failed <<- FALSE }, start_context = function(desc) { context <<- desc }, start_test = function(desc) { test <<- desc }, add_result = function(result) {}, end_test = function() { test <<- "" }, end_context = function() {}, end_reporter = function() {} ) ) testthat/R/reporter-zzz.r0000644000176200001440000000265212122406347015201 0ustar liggesusers#' @include reporter-stop.r reporter_accessors <- local({ # Default has to be the stop reporter, since it is this that will be run by # default from the command line and in R CMD test. reporter <- StopReporter$new() set <- function(value) { reporter <<- value } get <- function() { reporter } list(get = get, set = set) }) test_reporter <- reporter_accessors$get change_reporter_to <- reporter_accessors$set #' Execute code in specified reporter. #' #' Changes global reporter to that specified, runs code and the returns #' global reporter back to previous value. #' #' @keywords internal #' @param reporter test reporter to use #' @param code code block to execute with_reporter <- function(reporter, code) { reporter <- find_reporter(reporter) cur_reporter <- test_reporter() change_reporter_to(reporter) on.exit(change_reporter_to(cur_reporter)) reporter$start_reporter() force(code) reporter$end_reporter() invisible(reporter) } #' Find reporter object given name #' #' If not found, will return informative error message #' #' @param reporter name of reporter #' @keywords internal find_reporter <- function(reporter) { if (inherits(reporter, "Reporter")) return(reporter) name <- reporter str_sub(name, 1, 1) <- toupper(str_sub(name, 1, 1)) name <- str_c(name, "Reporter") if (!exists(name)) { stop("Can not find test reporter ", reporter, call. = FALSE) } get(name)$new() } testthat/R/reporter-tap.r0000644000176200001440000000320412122406261015115 0ustar liggesusers#' @include reporter.r NULL #' Test reporter: TAP format. #' #' This reporter will output results in the Test Anything Protocol (TAP), #' a simple text-based interface between testing modules in a test harness. #' For more information about TAP, see http://testanything.org #' #' @export #' @exportClass TapReporter #' @aliases TapReporter-class #' @keywords debugging TapReporter <- setRefClass("TapReporter", contains = "Reporter", fields = list( "results" = "list", "n" = "integer", "has_tests" = "logical", "contexts" = "character"), methods = list( start_context = function(desc) { contexts[n+1] <<- desc; }, start_reporter = function() { results <<- list() n <<- 0L has_tests <<- FALSE contexts <<- NA_character_ }, add_result = function(result) { has_tests <<- TRUE n <<- n + 1L; if (! result$passed) { failed <<- TRUE } result$test <- if (is.null(test)) "(unknown)" else test results[[n]] <<- result }, end_reporter = function() { if(has_tests) { cat("1..", n, '\n', sep=''); for(i in 1:n) { if (! is.na(contexts[i])) { cat("# Context", contexts[i], "\n") } result <- results[[i]]; if (result$passed) { cat('ok', i, result$test, '\n') } else { cat('not ok', i, result$test, '\n') msg <- str_replace_all(result$message, '\n', '\n ') cat(' ', msg, '\n') } } } } ) )testthat/R/reporter-summary.r0000644000176200001440000000501712122406347016037 0ustar liggesusers#' @include reporter.r NULL #' Test reporter: summary of errors. #' #' This is the most useful reporting reporter as it lets you know both which #' tests have run successfully, as well as fully reporting information about #' failures and errors. It is the default reporting reporter used by #' \code{\link{test_dir}} and \code{\link{test_file}}. #' #' As an additional benefit, this reporter will praise you from time-to-time #' if all your tests pass. #' #' @export #' @exportClass SummaryReporter #' @aliases SummaryReporter-class #' @keywords debugging SummaryReporter <- setRefClass("SummaryReporter", contains = "Reporter", fields = list( "failures" = "list", "n" = "integer", "has_tests" = "logical"), methods = list( start_context = function(desc) { cat(desc, ": ") }, end_context = function() { cat("\n") }, start_reporter = function() { failures <<- list() has_tests <<- FALSE n <<- 0L }, add_result = function(result) { has_tests <<- TRUE if (result$passed) { cat(colourise(".", fg = "light green")) } else { failed <<- TRUE n <<- n + 1L if (n > length(labels)) { n <<- length(labels) cat(colourise("F", fg = "red")) } else { result$test <- if (is.null(test)) "(unknown)" else test failures[[n]] <<- result cat(colourise(labels[n], fg = "red")) } } }, end_reporter = function() { charrep <- function(char, times) { sapply(times, function(i) str_c(rep.int(char, i), collapse = "")) } if (n == 0) { cat("\n") if (has_tests && sample(10, 1) == 1) { cat(colourise(sample(.praise, 1), "light green"), "\n") } } else { label <- labels[seq_len(n)] type <- ifelse(sapply(failures, "[[", "error"), "Error", "Failure") tests <- vapply(failures, "[[", "test", FUN.VALUE = character(1)) header <- str_c(label, ". ", type, ": ", tests, " ") linewidth <- ifelse(nchar(header) > getOption("width"),0,getOption("width") - nchar(header)) line <- charrep("-", linewidth ) message <- sapply(failures, "[[", "message") cat("\n\n") cat(str_c( colourise(header, "red"), line, "\n", message, "\n", collapse = "\n")) } } ) ) .praise <- c( "You rock!", "You are a coding rockstar!", "Keep up the good work.", ":)", "Woot!", "Way to go!", "Nice code." ) labels <- c(1:9, letters, LETTERS) testthat/R/reporter-stop.r0000644000176200001440000000310312122406707015321 0ustar liggesusers#' @include reporter.r NULL #' Test reporter: stop on error. #' #' The default reporter, executed when \code{expect_that} is run #' interactively, or when the test files are executed by R CMD check. It #' responds by \link{stop}()ing on failures and doing nothing otherwise. This #' will ensure that a failing test will raise an error. #' #' This should be used when doing a quick and dirty test, or during the final #' automated testing of R CMD check. Otherwise, use a reporter that runs all #' tests and gives you more context about the problem. #' #' @export #' @exportClass StopReporter #' @aliases StopReporter-class #' @keywords debugging StopReporter <- setRefClass("StopReporter", contains = "Reporter", fields = c("failures"), methods = list( initialize = function(...) { failures <<- list() callSuper(...) }, start_test = function(desc) { test <<- desc }, end_test = function() { cur_test <- test test <<- NULL if (length(failures) == 0) return() messages <- vapply(failures, "[[", "", "message") if (length(messages) > 1) { messages <- str_c("* ", messages, collapse = "\n") } failures <<- list() msg <- str_c("Test failed: '", cur_test, "'\n", messages) stop(msg, call. = FALSE) }, add_result = function(result) { if (result$passed) return() # If running in test suite, store, otherwise raise immediately. if (is.null(test)) { stop(result$message, call. = FALSE) } else { failures <<- c(failures, list(result)) } } ) ) testthat/R/reporter-minimal.r0000644000176200001440000000161112122406347015764 0ustar liggesusers#' @include reporter.r NULL #' Test reporter: minimal. #' #' The minimal test reporter provides the absolutely minimum amount of #' information: whether each expectation has succeeded, failed or experienced #' an error. If you want to find out what the failures and errors actually #' were, you'll need to run a more informative test reporter. #' #' @export #' @exportClass MinimalReporter #' @keywords debugging #' @aliases MinimalReporter-class MinimalReporter <- setRefClass("MinimalReporter", contains = "Reporter", methods = list( add_result = function(result) { if (result$passed) { cat(colourise(".", fg = "light green")) } else { failed <<- TRUE if (result$error) { cat(colourise("F", fg = "red")) } else { cat(colourise("E", fg = "red")) } } }, end_reporter = function() { cat("\n") } ) ) testthat/R/make-expectation.r0000644000176200001440000000135412122414275015737 0ustar liggesusers#' Make an equality test. #' #' This a convenience function to make a expectation that checks that #' input stays the same. #' #' @param x a vector of values #' @param expectation the type of equality you want to test for #' (\code{equals}, \code{is_equivalent_to}, \code{is_identical_to}) #' @export #' @examples #' x <- 1:10 #' make_expectation(x) #' #' make_expectation(mtcars$mpg) #' #' df <- data.frame(x = 2) #' make_expectation(df) make_expectation <- function(x, expectation = "equals") { obj <- substitute(x) expectation <- match.arg(expectation, c("equals", "is_equivalent_to", "is_identical_to")) dput(substitute(expect_that(obj, expectation(values)), list(obj = obj, expectation = as.name(expectation), values = x))) } testthat/R/library.r0000644000176200001440000000133512122406347014145 0ustar liggesusers#' Load package, if available. #' #' Quietly load a package if it is installed, otherwise do nothing. This is #' useful for testing files so that you can run them while you are developing #' your package, before it is installed for the first time; then continue to #' have the same code work when the tests are run automatically by R CMD #' CHECK. #' #' @param package package name (without quotes) #' @export #' @examples #' library_if_available(testthat) #' library_if_available(packagethatdoesntexist) library_if_available <- function(package) { package <- find_expr("package") suppressWarnings(suppressPackageStartupMessages( require(package, quietly = TRUE, warn.conflicts = FALSE, character.only = TRUE) )) } testthat/R/expectations.r0000644000176200001440000003224312122417324015206 0ustar liggesusers#' Expectation: does the object inherit from a class? #' #' Tests whether or not an object inherits from any of a list of classes. #' #' @param class character vector of class names #' @seealso \code{\link{inherits}} #' @family expectations #' @export #' @examples #' expect_that(1, is_a("numeric")) #' a <- matrix(1:10, nrow = 5) #' expect_that(a, is_a("matrix")) #' #' expect_that(mtcars, is_a("data.frame")) #' expect_is(mtcars, "data.frame") #' # alternatively for classes that have an is method #' expect_that(is.data.frame(mtcars), is_true()) #' # doesn't read quite as nicely is_a <- function(class) { function(x) { actual <- str_c(class(x), collapse = ", ") expectation( inherits(x, class), str_c("inherits from ", actual, " not ", class) ) } } #' @export #' @rdname is_a #' @inheritParams expect_that expect_is <- function(object, class, info = NULL, label = NULL) { if (is.null(label)) { label <- find_expr("object") } expect_that(object, is_a(class), info, label) } #' Expectation: is the object true? #' #' This is a fall-back expectation that you can use when none of the other #' more specific expectations apply. The disadvantage is that you may get #' a less informative error message. #' #' Attributes are ignored. #' #' @seealso \code{\link{is_false}} for complement #' @family expectations #' @export #' @examples #' expect_that(2 == 2, is_true()) #' expect_true(2 == 2) #' # Failed expectations will throw an error #' \dontrun{ #' expect_that(2 != 2, is_true()) #' } #' expect_that(!(2 != 2), is_true()) #' # or better: #' expect_that(2 != 2, is_false()) #' #' a <- 1:3 #' expect_that(length(a) == 3, is_true()) #' # but better to use more specific expectation, if available #' expect_that(length(a), equals(3)) is_true <- function() { function(x) { expectation( identical(as.vector(x), TRUE), "isn't true" ) } } #' @export #' @rdname is_true #' @inheritParams expect_that expect_true <- function(object, info = NULL, label = NULL) { if (is.null(label)) { label <- find_expr("object") } expect_that(object, is_true(), info, label) } #' Expectation: is the object false? #' #' A useful fall-back expectation like \code{\link{is_true}} #' #' Attributes are ignored. #' #' @family expectations #' @export #' @examples #' expect_that(3 == 2, is_false()) #' expect_false(3 == 2) #' #' a <- 1:3 #' expect_that(length(a) == 4, is_false()) is_false <- function() { function(x) { expectation( identical(as.vector(x), FALSE), "isn't false" ) } } #' @export #' @rdname is_false #' @inheritParams expect_that expect_false <- function(object, info = NULL, label = NULL) { if (is.null(label)) { label <- find_expr("object") } expect_that(object, is_false(), info, label) } #' Expectation: is the object equal (with numerical tolerance) to a value? #' #' Comparison performed using \code{\link{all.equal}}. # #' @param expected Expected value #' @param label For full form, label of expected object used in error #' messages. Useful to override default (deparsed expected expression) when #' doing tests in a loop. For short cut form, object label. When #' \code{NULL}, computed from deparsed object. #' @param expected.label Equivalent of \code{label} for shortcut form. #' @param ... other values passed to \code{\link{all.equal}} #' @family expectations #' @export #' @examples #' a <- 10 #' expect_that(a, equals(10)) #' expect_equal(a, 10) #' #' # Use equals() when testing for numeric equality #' sqrt(2) ^ 2 - 1 #' expect_that(sqrt(2) ^ 2, equals(2)) #' expect_equal(sqrt(2) ^ 2, 2) #' # Neither of these forms take floating point representation errors into #' # account #' \dontrun{ #' expect_that(sqrt(2) ^ 2 == 2, is_true()) #' expect_that(sqrt(2) ^ 2, is_identical_to(2)) #' } #' #' # You can pass on additional arguments to all.equal: #' \dontrun{ #' # Test the ABSOLUTE difference is within .002 #' expect_equal(object = 10.01, expected = 10, tolerance = .002, #' scale = 1) #' #' # Test the RELATIVE difference is within .002 #' expectedValue <- 10 #' expect_equal(object = 10.01, expected = expectedValue, tolerance = 0.002, #' scale = expectedValue) #' } equals <- function(expected, label = NULL, ...) { if (is.null(label)) { label <- find_expr("expected") } else if (!is.character(label) || length(label) != 1) { label <- deparse(label) } function(actual) { same <- all.equal(expected, actual, ...) expectation( identical(same, TRUE), str_c("not equal to ", label, "\n", str_c(same, collapse = "\n")) ) } } #' @export #' @rdname equals #' @inheritParams expect_that expect_equal <- function(object, expected, ..., info = NULL, label = NULL, expected.label = NULL) { if (is.null(label)) { label <- find_expr("object") } if (is.null(expected.label)) { expected.label <- find_expr("expected") } expect_that(object, equals(expected, label = expected.label, ...), info = info, label = label) } #' Expectation: is the object equivalent to a value? #' This expectation tests for equivalency: are two objects equal once their #' attributes have been removed. #' #' @inheritParams equals #' @family expectations #' @export #' @examples #' a <- b <- 1:3 #' names(b) <- letters[1:3] #' expect_that(a, is_equivalent_to(b, label = b)) #' expect_equivalent(a, b) is_equivalent_to <- function(expected, label = NULL) { if (is.null(label)) { label <- find_expr("expected") } else if (!is.character(label) || length(label) != 1) { label <- deparse(label) } function(actual) { equals(expected, check.attributes = FALSE)(actual) } } #' @export #' @rdname is_equivalent_to #' @inheritParams expect_that expect_equivalent <- function(object, expected, info = NULL, label = NULL, expected.label=NULL) { if (is.null(label)) { label <- find_expr("object") } if (is.null(expected.label)) { expected.label <- find_expr("expected") } expect_that(object, is_equivalent_to(expected, label = expected.label), info = info, label = label) } #' Expectation: is the object identical to another? #' #' Comparison performed using \code{\link{identical}}. #' #' @inheritParams equals #' @family expectations #' @export #' @examples #' a <- letters[1:3] #' expect_that(a, is_identical_to(c("a", "b", "c"))) #' expect_identical(a, c("a", "b", "c")) #' #' # Identical does not take into account numeric tolerance #' \dontrun{ #' expect_that(sqrt(2) ^ 2, is_identical_to(2)) #' expect_identical(sqrt(2) ^ 2, 2) #' } is_identical_to <- function(expected, label = NULL) { if (is.null(label)) { label <- find_expr("expected") } else if (!is.character(label) || length(label) != 1) { label <- deparse(label) } function(actual) { same <- all.equal(expected, actual) if (isTRUE(same)) { diff <- "Objects equal but not identical" } else { diff <- str_c(same, collapse = "\n") } expectation( identical(actual, expected), str_c("is not identical to ", label, ". Differences: \n", diff) ) } } #' @export #' @rdname is_identical_to #' @inheritParams expect_that expect_identical <- function(object, expected, info = NULL, label = NULL, expected.label = NULL) { if (is.null(label)) { label <- find_expr("object") } if (is.null(expected.label)) { expected.label <- find_expr("expected") } expect_that(object, is_identical_to(expected, label = expected.label), info = info, label = label) } #' Expectation: does string match regular expression? #' #' If the object to be tested has length greater than one, all elements of #' the vector must match the pattern in order to pass. #' #' @param regexp regular expression to test against #' @param all should all elements of actual value match \code{regexp} (TRUE), #' or does only one need to match (FALSE) #' @seealso \code{\link[stringr]{str_detect}} for the function that powers #' the string matching #' @family expectations #' @export #' @examples #' expect_that("Testing is fun", matches("fun")) #' expect_that("Testing is fun", matches("f.n")) #' expect_match("Testing is fun", "f.n") matches <- function(regexp, all = TRUE) { function(char) { matches <- str_detect(char, regexp) expectation( if (all) all(matches) else any(matches), str_c("does not match '", regexp, "'. Actual value: \n", char) ) } } #' @export #' @rdname matches #' @inheritParams expect_that expect_match <- function(object, regexp, all = TRUE, info = NULL, label = NULL) { if (is.null(label)) { label <- find_expr("object") } expect_that(object, matches(regexp, all = all), info = info, label = label) } #' Expectation: does printed output match a regular expression? #' #' @param regexp regular expression to test against #' @param ... other arguments passed to \code{\link{grepl}} #' @family expectations #' @export #' @examples #' str(mtcars) #' expect_that(str(mtcars), prints_text("32 obs")) #' expect_that(str(mtcars), prints_text("11 variables")) #' expect_output(str(mtcars), "11 variables") prints_text <- function(regexp, ...) { function(expr) { output <- str_c(capture.output(force(expr)), collapse = "") matches(regexp, ...)(output) } } #' @export #' @rdname prints_text #' @inheritParams expect_that expect_output <- function(object, regexp, ..., info = NULL, label = NULL) { if (is.null(label)) { label <- find_expr("object") } expect_that(object, prints_text(regexp, ...), info = info, label = label) } #' Expectation: does expression throw an error? #' #' @param regexp optional regular expression to match. If not specified, just #' asserts that expression throws some error. #' @family expectations #' @export #' @examples #' f <- function() stop("My error!") #' expect_that(f(), throws_error()) #' expect_error(f()) #' expect_that(f(), throws_error("My error!")) #' expect_error(f(), "My error!") throws_error <- function(regexp = NULL) { function(expr) { res <- try(force(expr), TRUE) no_error <- !inherits(res, "try-error") if (no_error) { return(expectation(FALSE, "code did not generate an error")) } if (!is.null(regexp)) { matches(regexp)(res) } else { expectation(TRUE, "") } } } #' @export #' @rdname throws_error #' @inheritParams expect_that expect_error <- function(object, regexp = NULL, info = NULL, label = NULL) { if (is.null(label)) { label <- find_expr("object") } expect_that(object, throws_error(regexp), info = info, label = label) } #' Expectation: does expression give a warning? #' #' Needs to match at least one of the warnings produced by the expression. #' #' @param regexp optional regular expression to match. If not specified, just #' asserts that expression gives some warning. #' @family expectations #' @export #' @importFrom evaluate is.warning #' @examples #' expect_that(warning("a"), gives_warning()) #' expect_that(warning("a"), gives_warning("a")) gives_warning <- function(regexp = NULL) { function(expr) { res <- evaluate(substitute(expr), parent.frame(), new_device = FALSE) warnings <- vapply(Filter(is.warning, res), "[[", "message", FUN.VALUE=character(1)) if (!is.null(regexp) && length(warnings) > 0) { matches(regexp, all = FALSE)(warnings) } else { expectation( length(warnings) > 0, "no warnings given" ) } } } #' @export #' @rdname gives_warning #' @inheritParams expect_that expect_warning <- function(object, regexp = NULL, info = NULL, label = NULL) { if (is.null(label)) { label <- find_expr("object") } expect_that(object, gives_warning(regexp), info = info, label = label) } #' Expectation: does expression show a message? #' #' Needs to match at least one of the messages produced by the expression. #' #' @param regexp optional regular expression to match. If not specified, just #' asserts that expression shows some message. #' @family expectations #' @export #' @importFrom evaluate evaluate is.message #' @examples #' expect_that(message("a"), shows_message()) #' expect_that(message("a"), shows_message("a")) shows_message <- function(regexp = NULL) { function(expr) { res <- evaluate(substitute(expr), parent.frame(), new_device = FALSE) messages <- vapply(Filter(is.message, res), "[[", "message", FUN.VALUE=character(1)) if (!is.null(regexp) && length(messages) > 0) { matches(regexp, all = FALSE)(messages) } else { expectation( length(messages) > 0, "no messages shown" ) } } } #' @export #' @rdname shows_message #' @inheritParams expect_that expect_message <- function(object, regexp = NULL, info = NULL, label = NULL) { if (is.null(label)) { label <- find_expr("object") } expect_that(object, shows_message(regexp), info = info, label = label) } #' Expectation: does expression take less than a fixed amount of time to run? #' #' This is useful for performance regression testing. #' #' @family expectations #' @export #' @param amount maximum duration in seconds takes_less_than <- function(amount) { function(expr) { duration <- system.time(force(expr))["elapsed"] expectation( duration < amount, str_c("took ", duration, " seconds, which is more than ", amount) ) } } testthat/R/expectation.r0000644000176200001440000000127312122406347015025 0ustar liggesusers#' Expectation class. #' #' Any expectation should return objects of this class - see the built in #' expectations for details. #' #' @aliases expectation print.expectation format.expectation #' @keywords internal #' @export #' @S3method print expectation #' @S3method format expectation expectation <- function(passed, message) { error <- is.na(passed) passed <- passed & !is.na(passed) structure( list(passed = passed, error = error, message = message), class = "expectation" ) } print.expectation <- function(x, ...) cat(format(x), "\n") format.expectation <- function(x, ...) { if (x$passed) { "As expected." } else { str_c("Not expected: ", x$message, ".") } } testthat/R/expect-that.r0000644000176200001440000000453412122410307014722 0ustar liggesusers#' Expect that a condition holds. #' #' An expectation checks whether a single condition holds true. #' \pkg{testthat} currently provides the following expectations. See their #' documentation for more details #' #' \itemize{ #' \item \code{\link{is_true}}: truth #' \item \code{\link{is_false}}: falsehood #' \item \code{\link{is_a}}: inheritance #' \item \code{\link{equals}}: equality with numerical tolerance #' \item \code{\link{is_equivalent_to}}: equality ignoring attributes #' \item \code{\link{is_identical_to}}: exact identity #' \item \code{\link{matches}}: string matching #' \item \code{\link{prints_text}}: output matching #' \item \code{\link{throws_error}}: error matching #' \item \code{\link{gives_warning}}: warning matching #' \item \code{\link{shows_message}}: message matching #' \item \code{\link{takes_less_than}}: performance #' } #' #' Expectations are arranged into tests with \code{\link{test_that}} and #' tests are arranged into contexts with \code{\link{context}}. #' #' @param object object to test #' @param condition, a function that returns whether or not the condition #' is met, and if not, an error message to display. #' @param label object label. When \code{NULL}, computed from deparsed object. #' @param info extra information to be included in the message (useful when #' writing tests in loops). #' @export #' @import stringr #' @seealso \code{\link{fail}} for an expectation that always fails. #' @examples #' expect_that(5 * 2, equals(10)) #' expect_that(sqrt(2) ^ 2, equals(2)) #' \dontrun{ #' expect_that(sqrt(2) ^ 2, is_identical_to(2)) #' } expect_that <- function(object, condition, info = NULL, label = NULL) { if (is.null(label)) { label <- find_expr("object") } results <- condition(object) results$message <- str_c(label, " ", results$message) if (!is.null(info)) { results$message <- str_c(results$message, "\n", info) } test_reporter()$add_result(results) invisible() } #' A default expectation that always fails. #' #' The fail function forces a test to fail. This is useful if you want to #' test a pre-condition ' #' #' @param message a string to display. #' @export #' @examples #' \dontrun{ #' test_that("this test fails", fail()) #' } fail <- function(message = "Failure has been forced.") { results <- expectation(FALSE, message) test_reporter()$add_result(results) invisible() } testthat/R/context.r0000644000176200001440000000135012122406347014162 0ustar liggesusers#' Describe the context of a set of tests. #' #' A context defines a set of tests that test related functionality. Usually #' you will have one context per file, but you may have multiple contexts #' in a single file if you so choose. #' #' @param desc description of context. Should start with a capital letter. #' @export #' @examples #' context("String processing") #' context("Remote procedure calls") context <- function(desc) { rep <- test_reporter() if (rep$context_open) { rep$end_context() } else { rep$context_open <- TRUE } rep$start_context(desc) } end_context <- function() { rep <- test_reporter() if (!rep$context_open) return(invisible()) rep$end_context() rep$context_open <- FALSE invisible() } testthat/R/colour-text.r0000644000176200001440000000336112122406347014767 0ustar liggesusers#' Colourise text for display in the terminal. #' #' If R is not currently running in a system that supports terminal colours #' the text will be returned unchanged. #' #' Allowed colours are: black, blue, brown, cyan, dark gray, green, light #' blue, light cyan, light gray, light green, light purple, light red, #' purple, red, white, yellow #' #' @param text character vector #' @param fg foreground colour, defaults to white #' @param bg background colour, defaults to transparent #' @export #' @examples #' print(colourise("Red", "red")) #' cat(colourise("Red", "red"), "\n") #' cat(colourise("White on red", "white", "red"), "\n") colourise <- function(text, fg = "black", bg = NULL) { term <- Sys.getenv()["TERM"] colour_terms <- c("xterm-color","xterm-256color", "screen", "screen-256color") if(rcmd_running() || !any(term %in% colour_terms, na.rm = TRUE)) { return(text) } col_escape <- function(col) { str_c("\033[", col, "m") } col <- .fg_colours[tolower(fg)] if (!is.null(bg)) { col <- str_c(col, .bg_colours[tolower(bg)], sep = ";") } init <- col_escape(col) reset <- col_escape("0") str_c(init, text, reset) } .fg_colours <- c( "black" = "0;30", "blue" = "0;34", "green" = "0;32", "cyan" = "0;36", "red" = "0;31", "purple" = "0;35", "brown" = "0;33", "light gray" = "0;37", "dark gray" = "1;30", "light blue" = "1;34", "light green" = "1;32", "light cyan" = "1;36", "light red" = "1;31", "light purple" = "1;35", "yellow" = "1;33", "white" = "1;37" ) .bg_colours <- c( "black" = "40", "red" = "41", "green" = "42", "brown" = "43", "blue" = "44", "purple" = "45", "cyan" = "46", "light gray" = "47" ) rcmd_running <- function() { str_length(Sys.getenv('R_TESTS')) != 0 } testthat/R/auto-test.r0000644000176200001440000000563512122406347014435 0ustar liggesusers#' Watches code and tests for changes, rerunning tests as appropriate. #' #' The idea behind \code{auto_test} is that you just leave it running while #' you develop your code. Everytime you save a file it will be automatically #' tested and you can easily see if your changes have caused any test #' failures. #' #' The current strategy for rerunning tests is as follows: #' #' \itemize{ #' \item if any code has changed, then those files are reloaded and all tests #' rerun #' \item otherwise, each new or modified test is run #' } #' In the future, \code{auto_test} might implement one of the following more #' intelligent alternatives: #' #' \itemize{ #' \item Use codetools to build up dependency tree and then rerun tests only #' when a dependency changes. #' #' \item Mimic ruby's autotest and rerun only failing tests until they pass, #' and then rerun all tests. #' } # #' @seealso \code{\link{auto_test_package}} #' @export #' @param code_path path to directory containing code #' @param test_path path to directory containing tests #' @param reporter test reporter to use #' @param env environment in which to execute test suite. Defaults to new #' environment inheriting from the global environment. #' @keywords debugging auto_test <- function(code_path, test_path, reporter = "summary", env = NULL) { reporter <- find_reporter(reporter) code_path <- normalizePath(code_path) test_path <- normalizePath(test_path) # Start by loading all code and running all tests if (is.null(env)) { env <- new.env(parent = globalenv()) } source_dir(code_path, env = env) test_dir(test_path, env = env) starts_with <- function(string, prefix) { str_sub(string, 1, str_length(prefix)) == prefix } # Next set up watcher to monitor changes watcher <- function(added, deleted, modified) { changed <- normalizePath(c(added, modified)) tests <- changed[starts_with(changed, test_path)] code <- changed[starts_with(changed, code_path)] if (length(code) > 0) { # Reload code and rerun all tests cat("Changed code: ", str_c(basename(code), collapse = ", "), "\n") cat("Rerunning all tests\n") source_dir(code_path, env = env) test_dir(test_path, env = env) } else if (length(tests) > 0) { # If test changes, rerun just that test cat("Rerunning tests: ", str_c(basename(tests), collapse = ", "), "\n") with_reporter(reporter$getRefClass()$new(), lapply(tests, sys.source, env = new.env(parent = env), chdir = TRUE)) } TRUE } watch(c(code_path, test_path), watcher) } #' Watches a package for changes, rerunning tests as appropriate. #' #' @param path path to package #' @export #' @param reporter test reporter to use #' @keywords debugging #' @seealso \code{\link{auto_test}} for details on how method works auto_test_package <- function(path, reporter = "summary") { auto_test(file.path(path, "R"), file.path(path, "tests"), reporter) } testthat/NEWS0000644000176200001440000001046612124375540012623 0ustar liggesusersVersion 0.7.1 ------------------------------------------------------------------------------ * Ignore attributes in `is_true` and `is_false` (#49) * `make_expectation` works for more types of input (#52) * Now works better with evaluate 0.4.3. * new `fail()` function always forces a failure in a test. Suggested by Richie Cotton (#47) * Added `TapReporter` to produce output compatible with the "test anything protocol". Contributed by Dan Keshet. * Fixed where `auto_test` would identify the wrong files as having changed. (Thanks to Peter Meilstrup) Version 0.7 ------------------------------------------------------------------------------ * `SummaryReporter`: still return informative messages even if no tests defined (just bare expectations). (Fixes #31) * Improvements to reference classes (Thanks to John Chambers) * Bug fixes for when nothing was generated in `gives_warning` / `shows_message`. (Thanks to Bernd Bischl) * New `make_expectation` function to programmatically generate an equality expectation. (Fixes #24) * `SummaryReporter`: You don't get praise until you have some tests. * Depend on `methods` rather than requiring it so that testthat works when run from `Rscript` * `auto_test` now normalises paths to enable better identification of file changes, and fixes bug in instantiating new reporter object. Version 0.6 ------------------------------------------------------------------------------ * All `mutatr` classes have been replaced with ReferenceClasses. * Better documentation for short-hand expectations. * `test_dir` and `test_package` gain new `filter` argument which allows you to restrict which tests are run. Version 0.5 ------------------------------------------------------------------------------ * bare expectations now correctly throw errors again Changes in version 0.4 ------------------------------------------------------------------------------ * autotest correctly loads code and executes tests in same environment * contexts are never closed before they are opened, and always closed at the end of file * fixed small bug in `test_dir` where each test was not given its own environment * all `expect_*` short cut functions gain a label argument, thanks to Steve Lianoglou Changes in version 0.3 ------------------------------------------------------------------------------ * all expectations now have a shortcut form, so instead of expect_that(a, is_identical_to(b)) you can do expect_identical(a, b) * new shows_message and gives_warning expectations to test warnings and messages * expect_that, equals, is_identical_to and is_equivalent to now have additional label argument which allows you to control the appearance of the text used for the expected object (for expect_that) and actual object (for all other functions) in failure messages. This is useful when you have loops that run tests as otherwise all the variable names are identical, and it's difficult to tell which iteration caused the failure. * executing bare tests gives nicer output * all expectations now give more information on failure to make it easier to track down the problem. * test_file and test_dir now run in code in separate environment to avoid pollution of global environment. They also temporary change the working directory so tests can use relative paths. * test_package makes it easier to run all tests in an installed package. Code run in this manner has access to non-exported functions and objects. If any errors or failures occur, test_package will throw an error, making it suitable for use with R CMD check. Changes in version 0.2 ------------------------------------------------------------------------------ * colourise also works in screen terminal * equals expectation provides more information about failure * expect_that has extra info argument to allow you to pass in any extra information you'd like included in the message - this is very helpful if you're using a loop to run tests * is_equivalent_to: new expectation that tests for equality ignoring attributes * library_if_available now works! (thanks to report and fix from Felix Andrews) * specify larger width and join pieces back together whenever deparse used (thanks to report and fix from Felix Andrews) * test_dir now looks for any files starting with test (not test- as before) testthat/NAMESPACE0000644000176200001440000000237012122410377013332 0ustar liggesusersS3method(format,expectation) S3method(print,expectation) export(MinimalReporter) export(StopReporter) export(SummaryReporter) export(TapReporter) export(auto_test) export(auto_test_package) export(colourise) export(context) export(equals) export(expect_equal) export(expect_equivalent) export(expect_error) export(expect_false) export(expect_identical) export(expect_is) export(expect_match) export(expect_message) export(expect_output) export(expect_that) export(expect_true) export(expect_warning) export(expectation) export(fail) export(gives_warning) export(is_a) export(is_equivalent_to) export(is_false) export(is_identical_to) export(is_true) export(library_if_available) export(make_expectation) export(matches) export(prints_text) export(shows_message) export(source_dir) export(takes_less_than) export(test_dir) export(test_file) export(test_package) export(test_that) export(throws_error) export(watch) exportClasses(MinimalReporter) exportClasses(Reporter) exportClasses(StopReporter) exportClasses(SummaryReporter) exportClasses(TapReporter) import(stringr) importFrom(evaluate,create_traceback) importFrom(evaluate,evaluate) importFrom(evaluate,is.error) importFrom(evaluate,is.message) importFrom(evaluate,is.warning) importFrom(evaluate,try_capture_stack) testthat/man/0000755000176200001440000000000012124375454012674 5ustar liggesuserstestthat/man/with_reporter.Rd0000644000176200001440000000056212124375454016063 0ustar liggesusers\name{with_reporter} \alias{with_reporter} \title{Execute code in specified reporter.} \usage{ with_reporter(reporter, code) } \arguments{ \item{reporter}{test reporter to use} \item{code}{code block to execute} } \description{ Changes global reporter to that specified, runs code and the returns global reporter back to previous value. } \keyword{internal} testthat/man/watch.Rd0000644000176200001440000000164712124375454014301 0ustar liggesusers\name{watch} \alias{watch} \title{Watch a directory for changes (additions, deletions & modifications).} \usage{ watch(path, callback, pattern = NULL, hash = TRUE) } \arguments{ \item{path}{character vector of paths to watch. Omit trailing backslash.} \item{pattern}{file pattern passed to \code{\link{dir}}} \item{callback}{function called everytime a change occurs. It should have three parameters: added, deleted, modified, and should return TRUE to keep watching, or FALSE to stop.} \item{hash}{hashes are more accurate at detecting changes, but are slower for large files. When FALSE, uses modification time stamps} } \description{ This is used to power the \code{\link{auto_test}} and \code{link{auto_test_package}} functions which are used to rerun tests whenever source code changes. } \details{ Use Ctrl + break (windows), Esc (mac gui) or Ctrl + C (command line) to stop the watcher. } testthat/man/throws_error.Rd0000644000176200001440000000266412124375454015732 0ustar liggesusers\name{throws_error} \alias{expect_error} \alias{throws_error} \title{Expectation: does expression throw an error?} \usage{ throws_error(regexp = NULL) expect_error(object, regexp = NULL, info = NULL, label = NULL) } \arguments{ \item{regexp}{optional regular expression to match. If not specified, just asserts that expression throws some error.} \item{object}{object to test} \item{info}{extra information to be included in the message (useful when writing tests in loops).} \item{label}{object label. When \code{NULL}, computed from deparsed object.} } \description{ Expectation: does expression throw an error? } \examples{ f <- function() stop("My error!") expect_that(f(), throws_error()) expect_error(f()) expect_that(f(), throws_error("My error!")) expect_error(f(), "My error!") } \seealso{ Other expectations: \code{\link{equals}}, \code{\link{expect_equal}}, \code{\link{expect_equivalent}}, \code{\link{expect_false}}, \code{\link{expect_identical}}, \code{\link{expect_is}}, \code{\link{expect_match}}, \code{\link{expect_message}}, \code{\link{expect_output}}, \code{\link{expect_true}}, \code{\link{expect_warning}}, \code{\link{gives_warning}}, \code{\link{is_a}}, \code{\link{is_equivalent_to}}, \code{\link{is_false}}, \code{\link{is_identical_to}}, \code{\link{is_true}}, \code{\link{matches}}, \code{\link{prints_text}}, \code{\link{shows_message}}, \code{\link{takes_less_than}} } testthat/man/test_that.Rd0000644000176200001440000000204412124375454015162 0ustar liggesusers\name{test_that} \alias{test_that} \title{Create a test.} \usage{ test_that(desc, code) } \arguments{ \item{desc}{test name. Names should be kept as brief as possible, as they are often used as line prefixes.} \item{code}{test code containing expectations} } \description{ A test encapsulates a series of expectations about small, self-contained set of functionality. Each test is contained in a \link{context} and contains multiple expectation generated by \code{\link{expect_that}}. } \details{ Tests are evaluated in their own environments, and should not affect global state. When run from the command line, tests return \code{NULL} if all expectations are met, otherwise it raises an error. } \examples{ test_that("trigonometric functions match identities", { expect_that(sin(pi / 4), equals(1 / sqrt(2))) expect_that(cos(pi / 4), equals(1 / sqrt(2))) expect_that(tan(pi / 4), equals(1)) }) # Failing test: \dontrun{ test_that("trigonometric functions match identities", { expect_that(sin(pi / 4), equals(1)) }) } } testthat/man/test_package.Rd0000644000176200001440000000123712124375454015620 0ustar liggesusers\name{test_package} \alias{test_package} \title{Run all tests in an installed package} \usage{ test_package(package, filter = NULL, reporter = "summary") } \arguments{ \item{package}{package name} \item{filter}{If not \code{NULL}, only tests with file names matching this regular expression will be executed. Matching will take on the file name after it has been stripped of \code{"test-"} and \code{".r"}.} \item{reporter}{reporter to use} } \description{ Test are run in an environment that inherits from the package environment so that tests can access non-exported functions and variables. } \examples{ \dontrun{test_package("testthat")} } testthat/man/test_file.Rd0000644000176200001440000000040012124375454015133 0ustar liggesusers\name{test_file} \alias{test_file} \title{Run all tests in specified file.} \usage{ test_file(path, reporter = "summary") } \arguments{ \item{path}{path to file} \item{reporter}{reporter to use} } \description{ Run all tests in specified file. } testthat/man/test_dir.Rd0000644000176200001440000000135312124375454015002 0ustar liggesusers\name{test_dir} \alias{test_dir} \title{Run all of the tests in a directory.} \usage{ test_dir(path, filter = NULL, reporter = "summary", env = NULL) } \arguments{ \item{path}{path to tests} \item{reporter}{reporter to use} \item{filter}{If not \code{NULL}, only tests with file names matching this regular expression will be executed. Matching will take on the file name after it has been stripped of \code{"test-"} and \code{".r"}.} \item{env}{environment in which to execute test suite. Defaults to new} } \description{ Test files start with \code{test} and are executed in alphabetical order (but they shouldn't have dependencies). Helper files start with \code{helper} and loaded before any tests are run. } testthat/man/TapReporter.Rd0000644000176200001440000000053512124375454015435 0ustar liggesusers\name{TapReporter} \alias{TapReporter} \alias{TapReporter-class} \title{Test reporter: TAP format.} \description{ This reporter will output results in the Test Anything Protocol (TAP), a simple text-based interface between testing modules in a test harness. For more information about TAP, see http://testanything.org } \keyword{debugging} testthat/man/takes_less_than.Rd0000644000176200001440000000167612124375454016344 0ustar liggesusers\name{takes_less_than} \alias{takes_less_than} \title{Expectation: does expression take less than a fixed amount of time to run?} \usage{ takes_less_than(amount) } \arguments{ \item{amount}{maximum duration in seconds} } \description{ This is useful for performance regression testing. } \seealso{ Other expectations: \code{\link{equals}}, \code{\link{expect_equal}}, \code{\link{expect_equivalent}}, \code{\link{expect_error}}, \code{\link{expect_false}}, \code{\link{expect_identical}}, \code{\link{expect_is}}, \code{\link{expect_match}}, \code{\link{expect_message}}, \code{\link{expect_output}}, \code{\link{expect_true}}, \code{\link{expect_warning}}, \code{\link{gives_warning}}, \code{\link{is_a}}, \code{\link{is_equivalent_to}}, \code{\link{is_false}}, \code{\link{is_identical_to}}, \code{\link{is_true}}, \code{\link{matches}}, \code{\link{prints_text}}, \code{\link{shows_message}}, \code{\link{throws_error}} } testthat/man/SummaryReporter.Rd0000644000176200001440000000104212124375454016340 0ustar liggesusers\name{SummaryReporter} \alias{SummaryReporter} \alias{SummaryReporter-class} \title{Test reporter: summary of errors.} \description{ This is the most useful reporting reporter as it lets you know both which tests have run successfully, as well as fully reporting information about failures and errors. It is the default reporting reporter used by \code{\link{test_dir}} and \code{\link{test_file}}. } \details{ As an additional benefit, this reporter will praise you from time-to-time if all your tests pass. } \keyword{debugging} testthat/man/StopReporter.Rd0000644000176200001440000000117212124375454015634 0ustar liggesusers\name{StopReporter} \alias{StopReporter} \alias{StopReporter-class} \title{Test reporter: stop on error.} \description{ The default reporter, executed when \code{expect_that} is run interactively, or when the test files are executed by R CMD check. It responds by \link{stop}()ing on failures and doing nothing otherwise. This will ensure that a failing test will raise an error. } \details{ This should be used when doing a quick and dirty test, or during the final automated testing of R CMD check. Otherwise, use a reporter that runs all tests and gives you more context about the problem. } \keyword{debugging} testthat/man/source_dir.Rd0000644000176200001440000000077012124375454015325 0ustar liggesusers\name{source_dir} \alias{source_dir} \title{Load all source files in a directory.} \usage{ source_dir(path, pattern="\\\\.[rR]$", env = NULL, chdir=TRUE) } \arguments{ \item{path}{path to tests} \item{pattern}{regular expression used to filter files} \item{env}{environment in which to execute test suite. Defaults to new} \item{chdir}{change working directory to path?} } \description{ The expectation is that the files can be sourced in alphabetical order. } \keyword{internal} testthat/man/shows_message.Rd0000644000176200001440000000261312124375454016034 0ustar liggesusers\name{shows_message} \alias{expect_message} \alias{shows_message} \title{Expectation: does expression show a message?} \usage{ shows_message(regexp = NULL) expect_message(object, regexp = NULL, info = NULL, label = NULL) } \arguments{ \item{regexp}{optional regular expression to match. If not specified, just asserts that expression shows some message.} \item{object}{object to test} \item{info}{extra information to be included in the message (useful when writing tests in loops).} \item{label}{object label. When \code{NULL}, computed from deparsed object.} } \description{ Needs to match at least one of the messages produced by the expression. } \examples{ expect_that(message("a"), shows_message()) expect_that(message("a"), shows_message("a")) } \seealso{ Other expectations: \code{\link{equals}}, \code{\link{expect_equal}}, \code{\link{expect_equivalent}}, \code{\link{expect_error}}, \code{\link{expect_false}}, \code{\link{expect_identical}}, \code{\link{expect_is}}, \code{\link{expect_match}}, \code{\link{expect_output}}, \code{\link{expect_true}}, \code{\link{expect_warning}}, \code{\link{gives_warning}}, \code{\link{is_a}}, \code{\link{is_equivalent_to}}, \code{\link{is_false}}, \code{\link{is_identical_to}}, \code{\link{is_true}}, \code{\link{matches}}, \code{\link{prints_text}}, \code{\link{takes_less_than}}, \code{\link{throws_error}} } testthat/man/Reporter.Rd0000644000176200001440000000034712124375454014771 0ustar liggesusers\name{Reporter} \alias{Reporter} \alias{Reporter-class} \title{Stub object for managing a reporter of tests.} \description{ Do not clone directly from this object - children should implement all methods. } \keyword{internal.} testthat/man/prints_text.Rd0000644000176200001440000000267612124375454015561 0ustar liggesusers\name{prints_text} \alias{expect_output} \alias{prints_text} \title{Expectation: does printed output match a regular expression?} \usage{ prints_text(regexp, ...) expect_output(object, regexp, ..., info = NULL, label = NULL) } \arguments{ \item{regexp}{regular expression to test against} \item{...}{other arguments passed to \code{\link{grepl}}} \item{object}{object to test} \item{info}{extra information to be included in the message (useful when writing tests in loops).} \item{label}{object label. When \code{NULL}, computed from deparsed object.} } \description{ Expectation: does printed output match a regular expression? } \examples{ str(mtcars) expect_that(str(mtcars), prints_text("32 obs")) expect_that(str(mtcars), prints_text("11 variables")) expect_output(str(mtcars), "11 variables") } \seealso{ Other expectations: \code{\link{equals}}, \code{\link{expect_equal}}, \code{\link{expect_equivalent}}, \code{\link{expect_error}}, \code{\link{expect_false}}, \code{\link{expect_identical}}, \code{\link{expect_is}}, \code{\link{expect_match}}, \code{\link{expect_message}}, \code{\link{expect_true}}, \code{\link{expect_warning}}, \code{\link{gives_warning}}, \code{\link{is_a}}, \code{\link{is_equivalent_to}}, \code{\link{is_false}}, \code{\link{is_identical_to}}, \code{\link{is_true}}, \code{\link{matches}}, \code{\link{shows_message}}, \code{\link{takes_less_than}}, \code{\link{throws_error}} } testthat/man/MinimalReporter.Rd0000644000176200001440000000065712124375454016304 0ustar liggesusers\name{MinimalReporter} \alias{MinimalReporter} \alias{MinimalReporter-class} \title{Test reporter: minimal.} \description{ The minimal test reporter provides the absolutely minimum amount of information: whether each expectation has succeeded, failed or experienced an error. If you want to find out what the failures and errors actually were, you'll need to run a more informative test reporter. } \keyword{debugging} testthat/man/matches.Rd0000644000176200001440000000316612124375454014615 0ustar liggesusers\name{matches} \alias{expect_match} \alias{matches} \title{Expectation: does string match regular expression?} \usage{ matches(regexp, all = TRUE) expect_match(object, regexp, all = TRUE, info = NULL, label = NULL) } \arguments{ \item{regexp}{regular expression to test against} \item{all}{should all elements of actual value match \code{regexp} (TRUE), or does only one need to match (FALSE)} \item{object}{object to test} \item{info}{extra information to be included in the message (useful when writing tests in loops).} \item{label}{object label. When \code{NULL}, computed from deparsed object.} } \description{ If the object to be tested has length greater than one, all elements of the vector must match the pattern in order to pass. } \examples{ expect_that("Testing is fun", matches("fun")) expect_that("Testing is fun", matches("f.n")) expect_match("Testing is fun", "f.n") } \seealso{ \code{\link[stringr]{str_detect}} for the function that powers the string matching Other expectations: \code{\link{equals}}, \code{\link{expect_equal}}, \code{\link{expect_equivalent}}, \code{\link{expect_error}}, \code{\link{expect_false}}, \code{\link{expect_identical}}, \code{\link{expect_is}}, \code{\link{expect_message}}, \code{\link{expect_output}}, \code{\link{expect_true}}, \code{\link{expect_warning}}, \code{\link{gives_warning}}, \code{\link{is_a}}, \code{\link{is_equivalent_to}}, \code{\link{is_false}}, \code{\link{is_identical_to}}, \code{\link{is_true}}, \code{\link{prints_text}}, \code{\link{shows_message}}, \code{\link{takes_less_than}}, \code{\link{throws_error}} } testthat/man/make_expectation.Rd0000644000176200001440000000104012124375454016476 0ustar liggesusers\name{make_expectation} \alias{make_expectation} \title{Make an equality test.} \usage{ make_expectation(x, expectation = "equals") } \arguments{ \item{x}{a vector of values} \item{expectation}{the type of equality you want to test for (\code{equals}, \code{is_equivalent_to}, \code{is_identical_to})} } \description{ This a convenience function to make a expectation that checks that input stays the same. } \examples{ x <- 1:10 make_expectation(x) make_expectation(mtcars$mpg) df <- data.frame(x = 2) make_expectation(df) } testthat/man/library_if_available.Rd0000644000176200001440000000114712124375454017310 0ustar liggesusers\name{library_if_available} \alias{library_if_available} \title{Load package, if available.} \usage{ library_if_available(package) } \arguments{ \item{package}{package name (without quotes)} } \description{ Quietly load a package if it is installed, otherwise do nothing. This is useful for testing files so that you can run them while you are developing your package, before it is installed for the first time; then continue to have the same code work when the tests are run automatically by R CMD CHECK. } \examples{ library_if_available(testthat) library_if_available(packagethatdoesntexist) } testthat/man/is_true.Rd0000644000176200001440000000323412124375454014637 0ustar liggesusers\name{is_true} \alias{expect_true} \alias{is_true} \title{Expectation: is the object true?} \usage{ is_true() expect_true(object, info = NULL, label = NULL) } \arguments{ \item{object}{object to test} \item{info}{extra information to be included in the message (useful when writing tests in loops).} \item{label}{object label. When \code{NULL}, computed from deparsed object.} } \description{ This is a fall-back expectation that you can use when none of the other more specific expectations apply. The disadvantage is that you may get a less informative error message. } \details{ Attributes are ignored. } \examples{ expect_that(2 == 2, is_true()) expect_true(2 == 2) # Failed expectations will throw an error \dontrun{ expect_that(2 != 2, is_true()) } expect_that(!(2 != 2), is_true()) # or better: expect_that(2 != 2, is_false()) a <- 1:3 expect_that(length(a) == 3, is_true()) # but better to use more specific expectation, if available expect_that(length(a), equals(3)) } \seealso{ \code{\link{is_false}} for complement Other expectations: \code{\link{equals}}, \code{\link{expect_equal}}, \code{\link{expect_equivalent}}, \code{\link{expect_error}}, \code{\link{expect_false}}, \code{\link{expect_identical}}, \code{\link{expect_is}}, \code{\link{expect_match}}, \code{\link{expect_message}}, \code{\link{expect_output}}, \code{\link{expect_warning}}, \code{\link{gives_warning}}, \code{\link{is_a}}, \code{\link{is_equivalent_to}}, \code{\link{is_false}}, \code{\link{is_identical_to}}, \code{\link{matches}}, \code{\link{prints_text}}, \code{\link{shows_message}}, \code{\link{takes_less_than}}, \code{\link{throws_error}} } testthat/man/is_identical_to.Rd0000644000176200001440000000334012124375454016314 0ustar liggesusers\name{is_identical_to} \alias{expect_identical} \alias{is_identical_to} \title{Expectation: is the object identical to another?} \usage{ is_identical_to(expected, label = NULL) expect_identical(object, expected, info = NULL, label = NULL, expected.label = NULL) } \arguments{ \item{expected}{Expected value} \item{label}{For full form, label of expected object used in error messages. Useful to override default (deparsed expected expression) when doing tests in a loop. For short cut form, object label. When \code{NULL}, computed from deparsed object.} \item{object}{object to test} \item{info}{extra information to be included in the message (useful when writing tests in loops).} \item{expected.label}{Equivalent of \code{label} for shortcut form.} } \description{ Comparison performed using \code{\link{identical}}. } \examples{ a <- letters[1:3] expect_that(a, is_identical_to(c("a", "b", "c"))) expect_identical(a, c("a", "b", "c")) # Identical does not take into account numeric tolerance \dontrun{ expect_that(sqrt(2) ^ 2, is_identical_to(2)) expect_identical(sqrt(2) ^ 2, 2) } } \seealso{ Other expectations: \code{\link{equals}}, \code{\link{expect_equal}}, \code{\link{expect_equivalent}}, \code{\link{expect_error}}, \code{\link{expect_false}}, \code{\link{expect_is}}, \code{\link{expect_match}}, \code{\link{expect_message}}, \code{\link{expect_output}}, \code{\link{expect_true}}, \code{\link{expect_warning}}, \code{\link{gives_warning}}, \code{\link{is_a}}, \code{\link{is_equivalent_to}}, \code{\link{is_false}}, \code{\link{is_true}}, \code{\link{matches}}, \code{\link{prints_text}}, \code{\link{shows_message}}, \code{\link{takes_less_than}}, \code{\link{throws_error}} } testthat/man/is_false.Rd0000644000176200001440000000237512124375454014757 0ustar liggesusers\name{is_false} \alias{expect_false} \alias{is_false} \title{Expectation: is the object false?} \usage{ is_false() expect_false(object, info = NULL, label = NULL) } \arguments{ \item{object}{object to test} \item{info}{extra information to be included in the message (useful when writing tests in loops).} \item{label}{object label. When \code{NULL}, computed from deparsed object.} } \description{ A useful fall-back expectation like \code{\link{is_true}} } \details{ Attributes are ignored. } \examples{ expect_that(3 == 2, is_false()) expect_false(3 == 2) a <- 1:3 expect_that(length(a) == 4, is_false()) } \seealso{ Other expectations: \code{\link{equals}}, \code{\link{expect_equal}}, \code{\link{expect_equivalent}}, \code{\link{expect_error}}, \code{\link{expect_identical}}, \code{\link{expect_is}}, \code{\link{expect_match}}, \code{\link{expect_message}}, \code{\link{expect_output}}, \code{\link{expect_true}}, \code{\link{expect_warning}}, \code{\link{gives_warning}}, \code{\link{is_a}}, \code{\link{is_equivalent_to}}, \code{\link{is_identical_to}}, \code{\link{is_true}}, \code{\link{matches}}, \code{\link{prints_text}}, \code{\link{shows_message}}, \code{\link{takes_less_than}}, \code{\link{throws_error}} } testthat/man/is_equivalent_to.Rd0000644000176200001440000000344212124375454016540 0ustar liggesusers\name{is_equivalent_to} \alias{expect_equivalent} \alias{is_equivalent_to} \title{Expectation: is the object equivalent to a value? This expectation tests for equivalency: are two objects equal once their attributes have been removed.} \usage{ is_equivalent_to(expected, label = NULL) expect_equivalent(object, expected, info = NULL, label = NULL, expected.label = NULL) } \arguments{ \item{expected}{Expected value} \item{label}{For full form, label of expected object used in error messages. Useful to override default (deparsed expected expression) when doing tests in a loop. For short cut form, object label. When \code{NULL}, computed from deparsed object.} \item{object}{object to test} \item{info}{extra information to be included in the message (useful when writing tests in loops).} \item{expected.label}{Equivalent of \code{label} for shortcut form.} } \description{ Expectation: is the object equivalent to a value? This expectation tests for equivalency: are two objects equal once their attributes have been removed. } \examples{ a <- b <- 1:3 names(b) <- letters[1:3] expect_that(a, is_equivalent_to(b, label = b)) expect_equivalent(a, b) } \seealso{ Other expectations: \code{\link{equals}}, \code{\link{expect_equal}}, \code{\link{expect_error}}, \code{\link{expect_false}}, \code{\link{expect_identical}}, \code{\link{expect_is}}, \code{\link{expect_match}}, \code{\link{expect_message}}, \code{\link{expect_output}}, \code{\link{expect_true}}, \code{\link{expect_warning}}, \code{\link{gives_warning}}, \code{\link{is_a}}, \code{\link{is_false}}, \code{\link{is_identical_to}}, \code{\link{is_true}}, \code{\link{matches}}, \code{\link{prints_text}}, \code{\link{shows_message}}, \code{\link{takes_less_than}}, \code{\link{throws_error}} } testthat/man/is_a.Rd0000644000176200001440000000300012124375454014067 0ustar liggesusers\name{is_a} \alias{expect_is} \alias{is_a} \title{Expectation: does the object inherit from a class?} \usage{ is_a(class) expect_is(object, class, info = NULL, label = NULL) } \arguments{ \item{class}{character vector of class names} \item{object}{object to test} \item{info}{extra information to be included in the message (useful when writing tests in loops).} \item{label}{object label. When \code{NULL}, computed from deparsed object.} } \description{ Tests whether or not an object inherits from any of a list of classes. } \examples{ expect_that(1, is_a("numeric")) a <- matrix(1:10, nrow = 5) expect_that(a, is_a("matrix")) expect_that(mtcars, is_a("data.frame")) expect_is(mtcars, "data.frame") # alternatively for classes that have an is method expect_that(is.data.frame(mtcars), is_true()) # doesn't read quite as nicely } \seealso{ \code{\link{inherits}} Other expectations: \code{\link{equals}}, \code{\link{expect_equal}}, \code{\link{expect_equivalent}}, \code{\link{expect_error}}, \code{\link{expect_false}}, \code{\link{expect_identical}}, \code{\link{expect_match}}, \code{\link{expect_message}}, \code{\link{expect_output}}, \code{\link{expect_true}}, \code{\link{expect_warning}}, \code{\link{gives_warning}}, \code{\link{is_equivalent_to}}, \code{\link{is_false}}, \code{\link{is_identical_to}}, \code{\link{is_true}}, \code{\link{matches}}, \code{\link{prints_text}}, \code{\link{shows_message}}, \code{\link{takes_less_than}}, \code{\link{throws_error}} } testthat/man/gives_warning.Rd0000644000176200001440000000261312124375454016027 0ustar liggesusers\name{gives_warning} \alias{expect_warning} \alias{gives_warning} \title{Expectation: does expression give a warning?} \usage{ gives_warning(regexp = NULL) expect_warning(object, regexp = NULL, info = NULL, label = NULL) } \arguments{ \item{regexp}{optional regular expression to match. If not specified, just asserts that expression gives some warning.} \item{object}{object to test} \item{info}{extra information to be included in the message (useful when writing tests in loops).} \item{label}{object label. When \code{NULL}, computed from deparsed object.} } \description{ Needs to match at least one of the warnings produced by the expression. } \examples{ expect_that(warning("a"), gives_warning()) expect_that(warning("a"), gives_warning("a")) } \seealso{ Other expectations: \code{\link{equals}}, \code{\link{expect_equal}}, \code{\link{expect_equivalent}}, \code{\link{expect_error}}, \code{\link{expect_false}}, \code{\link{expect_identical}}, \code{\link{expect_is}}, \code{\link{expect_match}}, \code{\link{expect_message}}, \code{\link{expect_output}}, \code{\link{expect_true}}, \code{\link{is_a}}, \code{\link{is_equivalent_to}}, \code{\link{is_false}}, \code{\link{is_identical_to}}, \code{\link{is_true}}, \code{\link{matches}}, \code{\link{prints_text}}, \code{\link{shows_message}}, \code{\link{takes_less_than}}, \code{\link{throws_error}} } testthat/man/find_reporter.Rd0000644000176200001440000000040312124375454016022 0ustar liggesusers\name{find_reporter} \alias{find_reporter} \title{Find reporter object given name} \usage{ find_reporter(reporter) } \arguments{ \item{reporter}{name of reporter} } \description{ If not found, will return informative error message } \keyword{internal} testthat/man/fail.Rd0000644000176200001440000000055012124375454014076 0ustar liggesusers\name{fail} \alias{fail} \title{A default expectation that always fails.} \usage{ fail(message = "Failure has been forced.") } \arguments{ \item{message}{a string to display.} } \description{ The fail function forces a test to fail. This is useful if you want to test a pre-condition ' } \examples{ \dontrun{ test_that("this test fails", fail()) } } testthat/man/expectation.Rd0000644000176200001440000000045112124375454015506 0ustar liggesusers\name{expectation} \alias{expectation} \alias{format.expectation} \alias{print.expectation} \title{Expectation class.} \usage{ expectation(passed, message) } \description{ Any expectation should return objects of this class - see the built in expectations for details. } \keyword{internal} testthat/man/expect_that.Rd0000644000176200001440000000322012124375454015470 0ustar liggesusers\name{expect_that} \alias{expect_that} \title{Expect that a condition holds.} \usage{ expect_that(object, condition, info = NULL, label = NULL) } \arguments{ \item{object}{object to test} \item{condition,}{a function that returns whether or not the condition is met, and if not, an error message to display.} \item{label}{object label. When \code{NULL}, computed from deparsed object.} \item{info}{extra information to be included in the message (useful when writing tests in loops).} } \description{ An expectation checks whether a single condition holds true. \pkg{testthat} currently provides the following expectations. See their documentation for more details } \details{ \itemize{ \item \code{\link{is_true}}: truth \item \code{\link{is_false}}: falsehood \item \code{\link{is_a}}: inheritance \item \code{\link{equals}}: equality with numerical tolerance \item \code{\link{is_equivalent_to}}: equality ignoring attributes \item \code{\link{is_identical_to}}: exact identity \item \code{\link{matches}}: string matching \item \code{\link{prints_text}}: output matching \item \code{\link{throws_error}}: error matching \item \code{\link{gives_warning}}: warning matching \item \code{\link{shows_message}}: message matching \item \code{\link{takes_less_than}}: performance } Expectations are arranged into tests with \code{\link{test_that}} and tests are arranged into contexts with \code{\link{context}}. } \examples{ expect_that(5 * 2, equals(10)) expect_that(sqrt(2) ^ 2, equals(2)) \dontrun{ expect_that(sqrt(2) ^ 2, is_identical_to(2)) } } \seealso{ \code{\link{fail}} for an expectation that always fails. } testthat/man/error_report.Rd0000644000176200001440000000050712124375454015711 0ustar liggesusers\name{error_report} \alias{error_report} \title{Generate error report from traceback.} \usage{ error_report(error, traceback) } \arguments{ \item{error}{error message} \item{traceback}{traceback generated by \code{\link{create_traceback}}} } \description{ Generate error report from traceback. } \keyword{internal} testthat/man/equals.Rd0000644000176200001440000000437212124375454014463 0ustar liggesusers\name{equals} \alias{equals} \alias{expect_equal} \title{Expectation: is the object equal (with numerical tolerance) to a value?} \usage{ equals(expected, label = NULL, ...) expect_equal(object, expected, ..., info = NULL, label = NULL, expected.label = NULL) } \arguments{ \item{expected}{Expected value} \item{label}{For full form, label of expected object used in error messages. Useful to override default (deparsed expected expression) when doing tests in a loop. For short cut form, object label. When \code{NULL}, computed from deparsed object.} \item{expected.label}{Equivalent of \code{label} for shortcut form.} \item{...}{other values passed to \code{\link{all.equal}}} \item{object}{object to test} \item{info}{extra information to be included in the message (useful when writing tests in loops).} } \description{ Comparison performed using \code{\link{all.equal}}. } \examples{ a <- 10 expect_that(a, equals(10)) expect_equal(a, 10) # Use equals() when testing for numeric equality sqrt(2) ^ 2 - 1 expect_that(sqrt(2) ^ 2, equals(2)) expect_equal(sqrt(2) ^ 2, 2) # Neither of these forms take floating point representation errors into # account \dontrun{ expect_that(sqrt(2) ^ 2 == 2, is_true()) expect_that(sqrt(2) ^ 2, is_identical_to(2)) } # You can pass on additional arguments to all.equal: \dontrun{ # Test the ABSOLUTE difference is within .002 expect_equal(object = 10.01, expected = 10, tolerance = .002, scale = 1) # Test the RELATIVE difference is within .002 expectedValue <- 10 expect_equal(object = 10.01, expected = expectedValue, tolerance = 0.002, scale = expectedValue) } } \seealso{ Other expectations: \code{\link{expect_equivalent}}, \code{\link{expect_error}}, \code{\link{expect_false}}, \code{\link{expect_identical}}, \code{\link{expect_is}}, \code{\link{expect_match}}, \code{\link{expect_message}}, \code{\link{expect_output}}, \code{\link{expect_true}}, \code{\link{expect_warning}}, \code{\link{gives_warning}}, \code{\link{is_a}}, \code{\link{is_equivalent_to}}, \code{\link{is_false}}, \code{\link{is_identical_to}}, \code{\link{is_true}}, \code{\link{matches}}, \code{\link{prints_text}}, \code{\link{shows_message}}, \code{\link{takes_less_than}}, \code{\link{throws_error}} } testthat/man/dir_state.Rd0000644000176200001440000000062612124375454015145 0ustar liggesusers\name{dir_state} \alias{dir_state} \title{Capture the state of a directory.} \usage{ dir_state(path, pattern = NULL, hash = TRUE) } \arguments{ \item{path}{path to directory} \item{pattern}{regular expression with which to filter files} \item{hash}{use hash (slow but accurate) or time stamp (fast but less accurate)} } \description{ Capture the state of a directory. } \keyword{internal} testthat/man/context.Rd0000644000176200001440000000073712124375454014656 0ustar liggesusers\name{context} \alias{context} \title{Describe the context of a set of tests.} \usage{ context(desc) } \arguments{ \item{desc}{description of context. Should start with a capital letter.} } \description{ A context defines a set of tests that test related functionality. Usually you will have one context per file, but you may have multiple contexts in a single file if you so choose. } \examples{ context("String processing") context("Remote procedure calls") } testthat/man/compare_state.Rd0000644000176200001440000000057412124375454016017 0ustar liggesusers\name{compare_state} \alias{compare_state} \title{Compare two directory states.} \usage{ compare_state(old, new) } \arguments{ \item{old}{previous state} \item{new}{current state} } \value{ list containing number of changes and files which have been \code{added}, \code{deleted} and \code{modified} } \description{ Compare two directory states. } \keyword{internal} testthat/man/colourise.Rd0000644000176200001440000000134712124375454015174 0ustar liggesusers\name{colourise} \alias{colourise} \title{Colourise text for display in the terminal.} \usage{ colourise(text, fg = "black", bg = NULL) } \arguments{ \item{text}{character vector} \item{fg}{foreground colour, defaults to white} \item{bg}{background colour, defaults to transparent} } \description{ If R is not currently running in a system that supports terminal colours the text will be returned unchanged. } \details{ Allowed colours are: black, blue, brown, cyan, dark gray, green, light blue, light cyan, light gray, light green, light purple, light red, purple, red, white, yellow } \examples{ print(colourise("Red", "red")) cat(colourise("Red", "red"), "\\n") cat(colourise("White on red", "white", "red"), "\\n") } testthat/man/auto_test_package.Rd0000644000176200001440000000067012124375454016650 0ustar liggesusers\name{auto_test_package} \alias{auto_test_package} \title{Watches a package for changes, rerunning tests as appropriate.} \usage{ auto_test_package(path, reporter = "summary") } \arguments{ \item{path}{path to package} \item{reporter}{test reporter to use} } \description{ Watches a package for changes, rerunning tests as appropriate. } \seealso{ \code{\link{auto_test}} for details on how method works } \keyword{debugging} testthat/man/auto_test.Rd0000644000176200001440000000251012124375454015170 0ustar liggesusers\name{auto_test} \alias{auto_test} \title{Watches code and tests for changes, rerunning tests as appropriate.} \usage{ auto_test(code_path, test_path, reporter = "summary", env = NULL) } \arguments{ \item{code_path}{path to directory containing code} \item{test_path}{path to directory containing tests} \item{reporter}{test reporter to use} \item{env}{environment in which to execute test suite. Defaults to new environment inheriting from the global environment.} } \description{ The idea behind \code{auto_test} is that you just leave it running while you develop your code. Everytime you save a file it will be automatically tested and you can easily see if your changes have caused any test failures. } \details{ The current strategy for rerunning tests is as follows: \itemize{ \item if any code has changed, then those files are reloaded and all tests rerun \item otherwise, each new or modified test is run } In the future, \code{auto_test} might implement one of the following more intelligent alternatives: \itemize{ \item Use codetools to build up dependency tree and then rerun tests only when a dependency changes. \item Mimic ruby's autotest and rerun only failing tests until they pass, and then rerun all tests. } } \seealso{ \code{\link{auto_test_package}} } \keyword{debugging} testthat/inst/0000755000176200001440000000000011571445650013077 5ustar liggesuserstestthat/inst/tests/0000755000176200001440000000000012124567260014236 5ustar liggesuserstestthat/inst/tests/test-xxx.r0000644000176200001440000000105412122410357016215 0ustar liggesusersif (interactive()) { context("Should fail") test_that("false is not true (should fail)", { expect_that(FALSE, is_true()) }) test_that("true is not false (should fail)", { expect_that(TRUE, is_false()) }) test_that("fail fails (should fail)", { fail() }) test_that("random errors are caught (should err)", { function_that_doesnt_exist() }) f <- function() g() g <- function() stop("I made a mistake", call. = FALSE) test_that("errors are captured (should err)", { f() }) expect_that(1, equals(2)) } testthat/inst/tests/test-watcher.r0000644000176200001440000000523612124347536017043 0ustar liggesusersif (interactive()) { context("Watcher components") test_that("compare state works correctly", { loc <- tempfile("watcher", tmpdir = "/tmp") dir.create(loc) empty <- dir_state(loc) expect_that(length(empty), equals(0)) file.create(file.path(loc, "test-1.txt")) one <- dir_state(loc) expect_that(length(one), equals(1)) expect_that(basename(names(one)), equals("test-1.txt")) diff <- compare_state(empty, one) expect_that(diff$n, equals(1)) expect_that(basename(diff$added), equals("test-1.txt")) write.table(mtcars, file.path(loc, "test-1.txt")) diff <- compare_state(one, dir_state(loc)) expect_that(diff$n, equals(1)) expect_that(basename(diff$modified), equals("test-1.txt")) file.rename(file.path(loc, "test-1.txt"), file.path(loc, "test-2.txt")) diff <- compare_state(one, dir_state(loc)) expect_that(diff$n, equals(2)) expect_that(basename(diff$deleted), equals("test-1.txt")) expect_that(basename(diff$added), equals("test-2.txt")) diff <- compare_state(c(file1 = "62da2", file2 = "e14a6", file3 = "6e6dd"), c(file1 = "62da2", file2 = "e14a6", file21= "532fa", file3 = "3f4sa")) expect_that(diff$n, equals(2)) expect_that(basename(diff$added), equals("file21")) expect_that(basename(diff$modified), equals("file3")) }) test_that("watcher works correctly", { loc <- tempfile("watcher", tmpdir = "/tmp") dir.create(loc) code_path = file.path(loc, "R") test_path = file.path(loc, "tests") dir.create(code_path) dir.create(test_path) delayed.bash.cmd <- function(command) { system(str_c("sleep 1;", command), wait=FALSE) } add.code.file <- function(file.name) { delayed.bash.cmd(str_c("touch ", file.path(code_path, file.name))) } remove.code.file <- function(file.name) { delayed.bash.cmd(str_c("rm ", file.path(code_path, file.name))) } test.added <- function(added, deleted, modified) { expect_that(length(added), equals(1)) expect_that(grepl("test1.R", added), is_true()) expect_that(length(deleted), equals(0)) expect_that(length(modified), equals(0)) FALSE } test.removed <- function(added, deleted, modified) { expect_that(length(added), equals(0)) expect_that(length(deleted), equals(1)) expect_that(grepl("test1.R", deleted), is_true()) expect_that(length(modified), equals(0)) FALSE } add.code.file("test1.R") watch(c(code_path, test_path), test.added) remove.code.file("test1.R") watch(c(code_path, test_path), test.removed) }) } testthat/inst/tests/test-reporter.r0000644000176200001440000000055512122406367017243 0ustar liggesuserscontext("Reporter") test_that("can locate reporter from name", { expect_that(find_reporter("minimal"), equals(MinimalReporter$new())) expect_that(find_reporter("summary"), equals(SummaryReporter$new())) expect_that(find_reporter("tap"), equals(TapReporter$new())) expect_that(find_reporter("blah"), throws_error("Can not find test reporter blah")) }) testthat/inst/tests/test-expectations.r0000644000176200001440000000277312122406347020111 0ustar liggesuserscontext("Expectations") test_that("errors are caught with throws_error", { res <- throws_error()(stop()) expect_that(res$passed, is_true()) res <- throws_error("Yes")(stop("Yes")) expect_that(res$passed, is_true()) res <- throws_error("Yes")(stop("No")) expect_that(res$passed, is_false()) }) test_that("failure to throw an error is a failure", { res <- throws_error()(log(1)) expect_that(res$passed, is_false()) res <- throws_error("error")(log(1)) expect_that(res$passed, is_false()) res <- throws_error()(NULL) expect_that(res$passed, is_false()) res <- throws_error("error")(NULL) expect_that(res$passed, is_false()) }) test_that("warnings are caught by gives_warning", { f <- function() { warning("a") } g <- function() { warning("a") warning("b") } expect_that(f(), gives_warning()) expect_that(f(), gives_warning("a")) expect_that(g(), gives_warning("a")) expect_that(g(), gives_warning("b")) }) test_that("messages are caught by shows_message", { f <- function() { message("a") } g <- function() { message("a") message("b") } expect_that(f(), shows_message()) expect_that(f(), shows_message("a")) expect_that(g(), shows_message("a")) expect_that(g(), shows_message("b")) }) test_that("shows_mesage / gives_warning work when no messages are generated", { expect_that(gives_warning("a")(1)$message, is_identical_to("no warnings given")) expect_that(shows_message("a")(1)$message, is_identical_to("no messages shown")) }) testthat/inst/tests/test-context.r0000644000176200001440000000174512122406347017065 0ustar liggesuserscontext("Contexts") CountReporter <- setRefClass("CountReporter", contains = "Reporter", fields = c("context_count", "test_count", "context_i", "test_i"), methods = list( initialize = function() { context_i <<- 0 context_count <<- 0 test_i <<- 0 test_count <<- 0 callSuper() }, start_context = function(desc) { context_count <<- context_count + 1 context_i <<- context_i + 1 }, end_context = function() { context_i <<- context_i - 1 stopifnot(context_i >= 0) }, start_test = function(desc) { test_count <<- test_count + 1 test_i <<- test_i + 1 }, end_test = function() { test_i <<- test_i - 1 stopifnot(test_i >= 0) } )) test_that("contexts are opened, then closed", { report <- CountReporter$new() test_file("context.r", report) expect_that(report$context_count, equals(2)) expect_that(report$context_i, equals(0)) expect_that(report$test_count, equals(4)) expect_that(report$test_i, equals(0)) }) testthat/inst/tests/test-basics.r0000644000176200001440000000103112122417257016633 0ustar liggesuserscontext("Basic tests") test_that("logical tests act as expected", { expect_that(TRUE, is_true()) expect_that(FALSE, is_false()) }) test_that("logical tests ignore attributes", { expect_that(c(a = TRUE), is_true()) expect_that(c(a = FALSE), is_false()) }) test_that("equality holds", { expect_that(5, equals(5)) expect_that(10, is_identical_to(10)) }) test_that("can't access variables from other tests 2", { a <- 10 }) test_that("can't access variables from other tests 1", { expect_that(exists("a"), is_false()) }) testthat/inst/tests/test-bare.r0000644000176200001440000000011312122406046016272 0ustar liggesuserscontext("Bare expectations") expect_that(1, equals(1)) expect_equal(2, 2) testthat/inst/tests/context.r0000644000176200001440000000053712122406046016102 0ustar liggesuserscontext("First context.") test_that("Logical equivalence", { x <- TRUE expect_that(x, equals(TRUE)) }) test_that("Numerical equivalence", { x <- 1 expect_that(x, equals(1)) }) context("Second context.") test_that("A passing test", { expect_that(TRUE, equals(TRUE)) }) test_that("A failing test", { expect_that(TRUE, equals(FALSE)) }) testthat/DESCRIPTION0000644000176200001440000000161112124613364013621 0ustar liggesusersPackage: testthat Type: Package Title: Testthat code. Tools to make testing fun :) Version: 0.7.1 Author: Hadley Wickham Maintainer: Hadley Wickham Description: A testing package specifically tailored for R that's fun, flexible and easy to set up. URL: http://had.co.nz/ Depends: R (>= 2.12.0), methods Imports: digest, stringr (>= 0.4), evaluate (>= 0.4.3) License: GPL LazyData: true Collate: 'auto-test.r' 'colour-text.r' 'context.r' 'expect-that.r' 'expectation.r' 'expectations.r' 'library.r' 'reporter.r' 'reporter-minimal.r' 'reporter-stop.r' 'reporter-summary.r' 'reporter-tap.r' 'reporter-zzz.r' 'test-files.r' 'test-package.r' 'test-that.r' 'utils.r' 'watcher.r' 'make-expectation.r' Packaged: 2013-03-27 13:05:52 UTC; hadley NeedsCompilation: no Repository: CRAN Date/Publication: 2013-03-27 16:57:40